diff --git a/Makefile b/Makefile index 075c79a55b69..efcb11a2ba98 100644 --- a/Makefile +++ b/Makefile @@ -610,10 +610,13 @@ _need_lld_${target}_${target_arch} != \ # XXX: Passing HOST_OBJTOP into the PATH would allow skipping legacy, # bootstrap-tools, and cross-tools. Need to ensure each tool actually # supports all TARGETS though. +# For now we only pass UNIVERSE_TOOLCHAIN_PATH which will be added at the end +# of STRICTTMPPATH to ensure that the target-specific binaries come first. MAKE_PARAMS_${target}+= \ XCC="${HOST_OBJTOP}/tmp/usr/bin/cc" \ XCXX="${HOST_OBJTOP}/tmp/usr/bin/c++" \ - XCPP="${HOST_OBJTOP}/tmp/usr/bin/cpp" + XCPP="${HOST_OBJTOP}/tmp/usr/bin/cpp" \ + UNIVERSE_TOOLCHAIN_PATH=${HOST_OBJTOP}/tmp/usr/bin .endif .if defined(_need_lld_${target}_${target_arch}) && \ ${_need_lld_${target}_${target_arch}} == "yes" diff --git a/Makefile.inc1 b/Makefile.inc1 index e888b58b6571..383b7c7b3264 100644 --- a/Makefile.inc1 +++ b/Makefile.inc1 @@ -580,8 +580,25 @@ BUILD_ARCH!= uname -p WORLDTMP?= ${OBJTOP}/tmp BPATH= ${CCACHE_WRAPPER_PATH_PFX}${WORLDTMP}/legacy/usr/sbin:${WORLDTMP}/legacy/usr/bin:${WORLDTMP}/legacy/bin XPATH= ${WORLDTMP}/usr/sbin:${WORLDTMP}/usr/bin -STRICTTMPPATH= ${BPATH}:${XPATH} + +# When building we want to find the cross tools before the host tools in ${BPATH}. +# We also need to add UNIVERSE_TOOLCHAIN_PATH so that we can find the shared +# toolchain files (clang, lld, etc.) during make universe/tinderbox +STRICTTMPPATH= ${XPATH}:${BPATH}:${UNIVERSE_TOOLCHAIN_PATH} +# We should not be using tools from /usr/bin accidentally since this could cause +# the build to break on other systems that don't have that tool. For now we +# still allow using the old behaviour (inheriting $PATH) if +# BUILD_WITH_STRICT_TMPPATH is set to 0 but this will eventually be removed. + +# Currently strict $PATH can cause build failures and does not work yet with +# USING_SYSTEM_LINKER/USING_SYSTEM_COMPILER. Once these issues have been +# resolved it will be turned on by default. +BUILD_WITH_STRICT_TMPPATH?=0 +.if ${BUILD_WITH_STRICT_TMPPATH} != 0 +TMPPATH= ${STRICTTMPPATH} +.else TMPPATH= ${STRICTTMPPATH}:${PATH} +.endif # # Avoid running mktemp(1) unless actually needed. @@ -589,7 +606,15 @@ TMPPATH= ${STRICTTMPPATH}:${PATH} # when in the middle of installing over this system. # .if make(distributeworld) || make(installworld) || make(stageworld) -INSTALLTMP!= mktemp -d -u -t install +.if ${BUILD_WITH_STRICT_TMPPATH} != 0 +MKTEMP=${WORLDTMP}/legacy/usr/bin/mktemp +.if !exists(${MKTEMP}) +.error "mktemp binary doesn't exist in expected location: ${MKTEMP}" +.endif +.else +MKTEMP=mktemp +.endif +INSTALLTMP!= ${MKTEMP} -d -u -t install .endif .if make(stagekernel) || make(distributekernel) @@ -647,6 +672,8 @@ CROSSENV+= BUILD_TOOLS_META=.NOMETA CROSSENV+= ${TARGET_CFLAGS} .endif +BOOTSTRAPPING_OSRELDATE?=${OSRELDATE} + # bootstrap-tools stage BMAKEENV= INSTALL="sh ${.CURDIR}/tools/install.sh" \ TOOLS_PREFIX=${TOOLS_PREFIX_UNDEF:U${WORLDTMP}} \ @@ -658,7 +685,7 @@ BSARGS= DESTDIR= \ OBJTOP='${WORLDTMP}/obj-tools' \ OBJROOT='$${OBJTOP}/' \ MAKEOBJDIRPREFIX= \ - BOOTSTRAPPING=${OSRELDATE} \ + BOOTSTRAPPING=${BOOTSTRAPPING_OSRELDATE} \ BWPHASE=${.TARGET:C,^_,,} \ SSP_CFLAGS= \ MK_HTML=no NO_LINT=yes MK_MAN=no \ @@ -680,7 +707,7 @@ TMAKE= \ ${BMAKEENV} ${MAKE} ${WORLD_FLAGS} -f Makefile.inc1 \ TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH} \ DESTDIR= \ - BOOTSTRAPPING=${OSRELDATE} \ + BOOTSTRAPPING=${BOOTSTRAPPING_OSRELDATE} \ BWPHASE=${.TARGET:C,^_,,} \ SSP_CFLAGS= \ -DNO_LINT \ @@ -705,7 +732,7 @@ KTMAKE= \ OBJTOP='${WORLDTMP}/obj-kernel-tools' \ OBJROOT='$${OBJTOP}/' \ MAKEOBJDIRPREFIX= \ - BOOTSTRAPPING=${OSRELDATE} \ + BOOTSTRAPPING=${BOOTSTRAPPING_OSRELDATE} \ SSP_CFLAGS= \ MK_HTML=no -DNO_LINT MK_MAN=no \ -DNO_PIC MK_PROFILE=no -DNO_SHARED \ @@ -874,6 +901,9 @@ WORLDTMP_MTREEFLAGS= -deUW DESTDIR_MTREEFLAGS+= -W .endif MTREE?= mtree +.if ${BUILD_WITH_STRICT_TMPPATH} != 0 +MTREE= ${WORLDTMP}/legacy/usr/sbin/mtree +.endif WORLDTMP_MTREE= ${MTREE} ${WORLDTMP_MTREEFLAGS} DESTDIR_MTREE= ${MTREE} ${DESTDIR_MTREEFLAGS} @@ -948,10 +978,15 @@ _worldtmp: .PHONY .if !defined(NO_CLEAN) rm -rf ${WORLDTMP} .else +# Note: for delete-old we need to set $PATH to also include the host $PATH +# since otherwise a partial build with missing symlinks in ${WORLDTMP}/legacy/ +# will fail to run due to missing binaries. $WMAKE sets PATH to only ${TMPPATH} +# so we remove that assingnment from $WMAKE and prepend the new $PATH ${_+_}@if [ -e "${WORLDTMP}" ]; then \ echo ">>> Deleting stale files in build tree..."; \ - cd ${.CURDIR}; ${WMAKE} -DBATCH_DELETE_OLD_FILES _NO_INCLUDE_COMPILERMK=t \ - delete-old delete-old-libs >/dev/null; \ + cd ${.CURDIR}; env PATH=${TMPPATH}:${PATH} ${WMAKE:NPATH=*} \ + _NO_INCLUDE_COMPILERMK=t -DBATCH_DELETE_OLD_FILES delete-old \ + delete-old-libs >/dev/null; \ fi rm -rf ${WORLDTMP}/legacy/usr/include .if ${USING_SYSTEM_COMPILER} == "yes" @@ -972,6 +1007,11 @@ _worldtmp: .PHONY # available on the target system (this happens e.g. when building on non-FreeBSD) cd ${.CURDIR}/tools/build; \ ${MAKE} DIRPRFX=tools/build/ DESTDIR=${WORLDTMP}/legacy installdirs +# In order to build without inheriting $PATH we need to add symlinks to the host +# tools in $WORLDTMP for the tools that we don't build during bootstrap-tools + cd ${.CURDIR}/tools/build; \ + ${MAKE} DIRPRFX=tools/build/ DESTDIR=${WORLDTMP}/legacy host-symlinks + _legacy: @echo @echo "--------------------------------------------------------------" @@ -1931,15 +1971,6 @@ update: .PHONY # build-tools or cross-tools. # -# ELF Tool Chain libraries are needed for ELF tools and dtrace tools. -# r296685 fix cross-endian objcopy -# r310724 fixed PR 215350, a crash in libdwarf with objects built by GCC 6.2. -# r334881 added libdwarf constants used by ctfconvert. -# r338478 fixed a crash in objcopy for mips64el objects -# r339083 libelf: correct mips64el test to use ELF header -.if ${BOOTSTRAPPING} < 1200085 -_elftoolchain_libs= lib/libelf lib/libdwarf -.endif # libnv and libl are both requirements for config(8), which is an unconditional # bootstrap-tool. @@ -1951,7 +1982,7 @@ legacy: .PHONY false .endif -.for _tool in tools/build ${_elftoolchain_libs} ${_config_deps} +.for _tool in tools/build ${_config_deps} ${_+_}@${ECHODIR} "===> ${_tool} (obj,includes,all,install)"; \ cd ${.CURDIR}/${_tool}; \ if [ -z "${NO_OBJWALK}" ]; then ${MAKE} DIRPRFX=${_tool}/ obj; fi; \ @@ -1965,10 +1996,34 @@ legacy: .PHONY # bootstrap-tools: Build tools needed for compatibility. These are binaries that # are built to build other binaries in the system. However, the focus of these # binaries is usually quite narrow. Bootstrap tools use the host's compiler and -# libraries, augmented by -legacy. +# libraries, augmented by -legacy, in addition to the libraries built during +# bootstrap-tools. # _bt= _bootstrap-tools +# We want to run the build with only ${WORLDTMP} in $PATH to ensure we don't +# accidentally run tools that are incompatible but happen to be in $PATH. +# This is especially important when building on Linux/MacOS where many of the +# programs used during the build accept different flags or generate different +# output. On those platforms we only symlink the tools known to be compatible +# (e.g. basic utilities such as mkdir) into ${WORLDTMP} and build all others +# from the FreeBSD sources during the bootstrap-tools stage. +# We want to build without the user's $PATH starting in the bootstrap-tools +# phase so the tools used in that phase (ln, cp, etc) must have already been +# linked to $WORLDTMP. The tools are listed in the _host_tools_to_symlink +# variable in tools/build/Makefile and are linked during the legacy phase. +# Since they could be Linux or MacOS binaries, too we must only use flags that +# are portable across operating systems. + +# If BOOTSTRAP_ALL_TOOLS is set we will build all the required tools from the +# current source tree. Otherwise we create a symlink to the version found in +# $PATH during the bootstrap-tools stage. +.if defined(BOOTSTRAP_ALL_TOOLS) +# BOOTSTRAPPING will be set on the command line so we can't override it here. +# Instead set BOOTSTRAPPING_OSRELDATE so that the value 0 is set ${BSARGS} +BOOTSTRAPPING_OSRELDATE:= 0 +.endif + .if ${MK_GAMES} != "no" _strfile= usr.bin/fortune/strfile .endif @@ -1981,12 +2036,34 @@ _gperf= gnu/usr.bin/gperf _vtfontcvt= usr.bin/vtfontcvt .endif +# If we are not building the bootstrap because BOOTSTRAPPING is sufficient +# we symlink the host version to $WORLDTMP instead. By doing this we can also +# detect when a bootstrap tool is being used without the required MK_FOO. +# If you add a new bootstrap tool where we could also use the host version, +# please ensure that you also add a .else case where you add the tool to the +# _bootstrap_tools_links variable. .if ${BOOTSTRAPPING} < 1000033 _m4= usr.bin/m4 _lex= usr.bin/lex +# Note: lex needs m4 to build but m4 also depends on lex. However, lex can be +# bootstrapped so we build lex first. +${_bt}-usr.bin/m4: ${_bt}-lib/libopenbsd ${_bt}-usr.bin/yacc ${_bt}-${_lex} +_bt_m4_depend=${_bt}-${_m4} +_bt_lex_depend=${_bt}-${_lex} ${_bt_m4_depend} +.else +_bootstrap_tools_links+=m4 lex +.endif -${_bt}-usr.bin/m4: ${_bt}-lib/libopenbsd -${_bt}-usr.bin/lex: ${_bt}-usr.bin/m4 +# ELF Tool Chain libraries are needed for ELF tools and dtrace tools. +# r296685 fix cross-endian objcopy +# r310724 fixed PR 215350, a crash in libdwarf with objects built by GCC 6.2. +# r334881 added libdwarf constants used by ctfconvert. +# r338478 fixed a crash in objcopy for mips64el objects +# r339083 libelf: correct mips64el test to use ELF header +.if ${BOOTSTRAPPING} < 1200085 +_elftoolchain_libs= lib/libelf lib/libdwarf +${_bt}-lib/libelf: ${_bt_m4_depend} +${_bt}-lib/libdwarf: ${_bt_m4_depend} .endif # r245440 mtree -N support added @@ -1998,17 +2075,23 @@ _nmtree= lib/libmd \ ${_bt}-lib/libnetbsd: ${_bt}-lib/libmd ${_bt}-usr.sbin/nmtree: ${_bt}-lib/libnetbsd +.else +_bootstrap_tools_links+=mtree .endif # r246097: log addition login.conf.db, passwd, pwd.db, and spwd.db with cat -l .if ${BOOTSTRAPPING} < 1000027 _cat= bin/cat +.else +_bootstrap_tools_links+=cat .endif # r277259 crunchide: Correct 64-bit section header offset # r281674 crunchide: always include both 32- and 64-bit ELF support .if ${BOOTSTRAPPING} < 1100078 _crunchide= usr.sbin/crunch/crunchide +.else +_bootstrap_tools_links+=crunchide .endif # r285986 crunchen: use STRIPBIN rather than STRIP @@ -2018,12 +2101,16 @@ _crunchide= usr.sbin/crunch/crunchide (${MK_AUTO_OBJ} == "yes" && ${BOOTSTRAPPING} < 1100114) || \ (${MK_META_MODE} == "yes" && ${BOOTSTRAPPING} < 1200006) _crunchgen= usr.sbin/crunch/crunchgen +.else +_bootstrap_tools_links+=crunchgen .endif # r296926 -P keymap search path, MFC to stable/10 in r298297 .if ${BOOTSTRAPPING} < 1003501 || \ (${BOOTSTRAPPING} >= 1100000 && ${BOOTSTRAPPING} < 1100103) _kbdcontrol= usr.sbin/kbdcontrol +.else +_bootstrap_tools_links+=kbdcontrol .endif _yacc= lib/liby \ @@ -2059,6 +2146,10 @@ _dtc= usr.bin/dtc _dtc= gnu/usr.bin/dtc .endif +.if ${MK_LOCALES} != "no" +_localedef= usr.bin/localedef +.endif + .if ${MK_KERBEROS} != "no" _kerberos5_bootstrap_tools= \ kerberos5/tools/make-roken \ @@ -2069,11 +2160,106 @@ _kerberos5_bootstrap_tools= \ usr.bin/compile_et .ORDER: ${_kerberos5_bootstrap_tools:C/^/${_bt}-/g} +.for _tool in ${_kerberos5_bootstrap_tools} +${_bt}-${_tool}: ${_bt}-usr.bin/yacc ${_bt_lex_depend} +.endfor .endif ${_bt}-usr.bin/mandoc: ${_bt}-lib/libopenbsd -bootstrap-tools: .PHONY +# The tools listed in _basic_bootstrap_tools will generally not be +# bootstrapped unless BOOTSTRAP_ALL_TOOL is set. However, when building on a +# Linux or MacOS host the host versions are incompatible so we need to build +# them from the source tree. Usually the link name will be the same as the subdir, +# but some directories such as grep or test install multiple binaries. In that +# case we use the _basic_bootstrap_tools_multilink variable which is a list of +# subdirectory and comma-separated list of files. +_basic_bootstrap_tools_multilink=usr.bin/grep grep,egrep,fgrep +_basic_bootstrap_tools_multilink+=bin/test test,[ +# bootstrap tools needed by buildworld: +_basic_bootstrap_tools=usr.bin/awk usr.bin/cut bin/expr usr.bin/gencat \ + usr.bin/join usr.bin/mktemp bin/rmdir usr.bin/sed usr.bin/sort \ + usr.bin/truncate usr.bin/tsort +# elf2aout is required for sparc64 build +_basic_bootstrap_tools+=usr.bin/elf2aout +# file2c is required for building usr.sbin/config: +_basic_bootstrap_tools+=usr.bin/file2c +# uuencode/uudecode required for share/tabset +_basic_bootstrap_tools+=usr.bin/uuencode usr.bin/uudecode +# xargs is required by mkioctls +_basic_bootstrap_tools+=usr.bin/xargs +# cap_mkdb is required for share/termcap: +_basic_bootstrap_tools+=usr.bin/cap_mkdb +# ldd is required for installcheck (TODO: just always use /usr/bin/ldd instead?) +_basic_bootstrap_tools+=usr.bin/ldd +# services_mkdb/pwd_mkdb are required for installworld: +_basic_bootstrap_tools+=usr.sbin/services_mkdb usr.sbin/pwd_mkdb +# sysctl/chflags are required for installkernel: +_basic_bootstrap_tools+=sbin/sysctl bin/chflags + +.if ${MK_AMD} != "no" +# unifdef is only used by usr.sbin/amd/libamu/Makefile +_basic_bootstrap_tools+=usr.bin/unifdef +.endif + +.if ${MK_BOOT} != "no" +_basic_bootstrap_tools+=bin/dd +# xz/unxz is used by EFI +_basic_bootstrap_tools_multilink+=usr.bin/xz xz,unxz +# md5 is used by boot/beri (and possibly others) +_basic_bootstrap_tools+=sbin/md5 +.if defined(BOOTSTRAP_ALL_TOOLS) +${_bt}-sbin/md5: ${_bt}-lib/libmd +.endif +.endif + +.if ${MK_ZONEINFO} != "no" +_basic_bootstrap_tools+=usr.sbin/zic usr.sbin/tzsetup +.endif + +.if defined(BOOTSTRAP_ALL_TOOLS) +_other_bootstrap_tools+=${_basic_bootstrap_tools} +.for _subdir _links in ${_basic_bootstrap_tools_multilink} +_other_bootstrap_tools+=${_subdir} +.endfor +${_bt}-usr.bin/awk: ${_bt_lex_depend} ${_bt}-usr.bin/yacc +${_bt}-bin/expr: ${_bt_lex_depend} ${_bt}-usr.bin/yacc +# If we are bootstrapping file2c, we have to build it before config: +${_bt}-usr.sbin/config: ${_bt}-usr.bin/file2c ${_bt_lex_depend} +# Note: no symlink to make/bmake in the !BOOTSTRAP_ALL_TOOLS case here since +# the links to make/bmake make links will have already have been created in the +# `make legacy` step. Not adding a link to make is important on non-FreeBSD +# since "make" will usually point to GNU make there. +_other_bootstrap_tools+=usr.bin/bmake +.else +# All tools in _basic_bootstrap_tools have the same name as the subdirectory +# so we can use :T to get the name of the symlinks that we need to create. +_bootstrap_tools_links+=${_basic_bootstrap_tools:T} +.for _subdir _links in ${_basic_bootstrap_tools_multilink} +_bootstrap_tools_links+=${_links:S/,/ /g} +.endfor +.endif # defined(BOOTSTRAP_ALL_TOOLS) + +# Link the tools that we need for building but don't need to bootstrap because +# the host version is known to be compatible into ${WORLDTMP}/legacy +# We do this before building any of the bootstrap tools in case they depend on +# the presence of any of the links (e.g. as m4/lex/awk) +${_bt}-links: .PHONY + +.for _tool in ${_bootstrap_tools_links} +${_bt}-link-${_tool}: .PHONY .MAKE + @if [ ! -e "${WORLDTMP}/legacy/bin/${_tool}" ]; then \ + source_path=`which ${_tool}`; \ + if [ ! -e "$${source_path}" ] ; then \ + echo "Cannot find host tool '${_tool}'"; false; \ + fi; \ + ln -sfnv "$${source_path}" "${WORLDTMP}/legacy/bin/${_tool}"; \ + fi +${_bt}-links: ${_bt}-link-${_tool} +.endfor + + +bootstrap-tools: ${_bt}-links .PHONY # Please document (add comment) why something is in 'bootstrap-tools'. # Try to bound the building of the bootstrap-tool to just the @@ -2086,6 +2272,7 @@ bootstrap-tools: .PHONY ${_dtc} \ ${_cat} \ ${_kbdcontrol} \ + ${_elftoolchain_libs} \ usr.bin/lorder \ lib/libopenbsd \ usr.bin/mandoc \ @@ -2093,6 +2280,7 @@ bootstrap-tools: .PHONY ${_yacc} \ ${_m4} \ ${_lex} \ + ${_other_bootstrap_tools} \ usr.bin/xinstall \ ${_gensnmptree} \ usr.sbin/config \ @@ -2101,10 +2289,13 @@ bootstrap-tools: .PHONY ${_nmtree} \ ${_vtfontcvt} \ ${_localedef} -${_bt}-${_tool}: .PHONY .MAKE +${_bt}-${_tool}: ${_bt}-links .PHONY .MAKE ${_+_}@${ECHODIR} "===> ${_tool} (obj,all,install)"; \ cd ${.CURDIR}/${_tool}; \ if [ -z "${NO_OBJWALK}" ]; then ${MAKE} DIRPRFX=${_tool}/ obj; fi; \ + if [ "${_tool}" = "usr.bin/lex" ]; then \ + ${MAKE} DIRPRFX=${_tool}/ bootstrap; \ + fi; \ ${MAKE} DIRPRFX=${_tool}/ all; \ ${MAKE} DIRPRFX=${_tool}/ DESTDIR=${WORLDTMP}/legacy install @@ -2182,7 +2373,7 @@ kernel-tools: .PHONY # we get done with the earlier stages. It is the last set of tools needed # to begin building the target binaries. # -.if ${TARGET_ARCH} != ${MACHINE_ARCH} +.if ${TARGET_ARCH} != ${MACHINE_ARCH} || ${BUILD_WITH_STRICT_TMPPATH} != 0 .if ${TARGET_ARCH} == "amd64" || ${TARGET_ARCH} == "i386" _btxld= usr.sbin/btxld .endif @@ -2235,9 +2426,14 @@ _gcc= gnu/usr.bin/cc _usb_tools= stand/usb/tools .endif +.if ${BUILD_WITH_STRICT_TMPPATH} != 0 || defined(BOOTSTRAP_ALL_TOOLS) +_ar=usr.bin/ar +.endif + cross-tools: .MAKE .PHONY .for _tool in \ ${LOCAL_XTOOL_DIRS} \ + ${_ar} \ ${_clang_libs} \ ${_clang} \ ${_lld} \ diff --git a/bin/dd/dd.c b/bin/dd/dd.c index a37a3072bcff..ef186a8186c3 100644 --- a/bin/dd/dd.c +++ b/bin/dd/dd.c @@ -157,7 +157,7 @@ setup(void) getfdtype(&in); cap_rights_init(&rights, CAP_READ, CAP_SEEK); - if (cap_rights_limit(in.fd, &rights) == -1 && errno != ENOSYS) + if (caph_rights_limit(in.fd, &rights) == -1) err(1, "unable to limit capability rights"); if (files_cnt > 1 && !(in.flags & ISTAPE)) @@ -188,10 +188,9 @@ setup(void) getfdtype(&out); - if (cap_rights_limit(out.fd, &rights) == -1 && errno != ENOSYS) + if (caph_rights_limit(out.fd, &rights) == -1) err(1, "unable to limit capability rights"); - if (cap_ioctls_limit(out.fd, cmds, nitems(cmds)) == -1 && - errno != ENOSYS) + if (caph_ioctls_limit(out.fd, cmds, nitems(cmds)) == -1) err(1, "unable to limit capability rights"); if (in.fd != STDIN_FILENO && out.fd != STDIN_FILENO) { diff --git a/bin/ed/Makefile b/bin/ed/Makefile index 40e06134e87d..1d4b7685c025 100644 --- a/bin/ed/Makefile +++ b/bin/ed/Makefile @@ -4,13 +4,8 @@ PACKAGE=runtime PROG= ed -SRCS= buf.c cbc.c glbl.c io.c main.c re.c sub.c undo.c +SRCS= buf.c glbl.c io.c main.c re.c sub.c undo.c LINKS= ${BINDIR}/ed ${BINDIR}/red MLINKS= ed.1 red.1 -.if ${MK_OPENSSL} != "no" && ${MK_ED_CRYPTO} != "no" -CFLAGS+=-DDES -LIBADD= crypto -.endif - .include diff --git a/bin/ed/POSIX b/bin/ed/POSIX index dab1a2bc90f3..53d6b5328ca5 100644 --- a/bin/ed/POSIX +++ b/bin/ed/POSIX @@ -25,29 +25,20 @@ EXTENSIONS iv) `z' for scrolling through the buffer, and v) BSD line addressing syntax (i.e., `^' and `%') is recognized. -2) If crypt(3) is available, files can be read and written using DES - encryption. The `x' command prompts the user to enter a key used for - encrypting/ decrypting subsequent reads and writes. If only a newline - is entered as the key, then encryption is disabled. Otherwise, a key - is read in the same manner as a password entry. The key remains in - effect until encryption is disabled. For more information on the - encryption algorithm, see the bdes(1) man page. Encryption/decryption - should be fully compatible with SunOS des(1). - -3) The POSIX interactive global commands `G' and `V' are extended to +2) The POSIX interactive global commands `G' and `V' are extended to support multiple commands, including `a', `i' and `c'. The command format is the same as for the global commands `g' and `v', i.e., one command per line with each line, except for the last, ending in a backslash (\). -4) An extension to the POSIX file commands `E', `e', `r', `W' and `w' is +3) An extension to the POSIX file commands `E', `e', `r', `W' and `w' is that arguments are processed for backslash escapes, i.e., any character preceded by a backslash is interpreted literally. If the first unescaped character of a argument is a bang (!), then the rest of the line is interpreted as a shell command, and no escape processing is performed by ed. -5) For SunOS ed(1) compatibility, ed runs in restricted mode if invoked +4) For SunOS ed(1) compatibility, ed runs in restricted mode if invoked as red. This limits editing of files in the local directory only and prohibits shell commands. diff --git a/bin/ed/README b/bin/ed/README index 478e7af07c70..da11f9b0f32a 100644 --- a/bin/ed/README +++ b/bin/ed/README @@ -9,7 +9,6 @@ compile with little trouble. Otherwise, the macros SPL1() and SPL0() should be redefined to disable interrupts. The following compiler directives are recognized: -DES - to add encryption support (requires crypt(3)) NO_REALLOC_NULL - if realloc(3) does not accept a NULL pointer BACKWARDS - for backwards compatibility NEED_INSQUE - if insque(3) is missing diff --git a/bin/ed/cbc.c b/bin/ed/cbc.c deleted file mode 100644 index 7e1d03c3c634..000000000000 --- a/bin/ed/cbc.c +++ /dev/null @@ -1,395 +0,0 @@ -/* cbc.c: This file contains the encryption routines for the ed line editor */ -/*- - * SPDX-License-Identifier: BSD-3-Clause - * - * Copyright (c) 1993 The Regents of the University of California. - * All rights reserved. - * - * Copyright (c) 1993 Andrew Moore, Talke Studio. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#include -__FBSDID("$FreeBSD$"); - -#include -#include -#include -#ifdef DES -#include -#include -#define ED_DES_INCLUDES -#endif - -#include "ed.h" - - -/* - * BSD and System V systems offer special library calls that do - * block move_liness and fills, so if possible we take advantage of them - */ -#define MEMCPY(dest,src,len) memcpy((dest),(src),(len)) -#define MEMZERO(dest,len) memset((dest), 0, (len)) - -/* Hide the calls to the primitive encryption routines. */ -#define DES_XFORM(buf) \ - DES_ecb_encrypt(buf, buf, &schedule, \ - inverse ? DES_DECRYPT : DES_ENCRYPT); - -/* - * read/write - no error checking - */ -#define READ(buf, n, fp) fread(buf, sizeof(char), n, fp) -#define WRITE(buf, n, fp) fwrite(buf, sizeof(char), n, fp) - -/* - * global variables and related macros - */ - -#ifdef DES -static DES_cblock ivec; /* initialization vector */ -static DES_cblock pvec; /* padding vector */ - -static char bits[] = { /* used to extract bits from a char */ - '\200', '\100', '\040', '\020', '\010', '\004', '\002', '\001' -}; - -static int pflag; /* 1 to preserve parity bits */ - -static DES_key_schedule schedule; /* expanded DES key */ - -static unsigned char des_buf[8];/* shared buffer for get_des_char/put_des_char */ -static int des_ct = 0; /* count for get_des_char/put_des_char */ -static int des_n = 0; /* index for put_des_char/get_des_char */ -#endif - -/* init_des_cipher: initialize DES */ -void -init_des_cipher(void) -{ -#ifdef DES - des_ct = des_n = 0; - - /* initialize the initialization vector */ - MEMZERO(ivec, 8); - - /* initialize the padding vector */ - arc4random_buf(pvec, sizeof(pvec)); -#endif -} - - -/* get_des_char: return next char in an encrypted file */ -int -get_des_char(FILE *fp) -{ -#ifdef DES - if (des_n >= des_ct) { - des_n = 0; - des_ct = cbc_decode(des_buf, fp); - } - return (des_ct > 0) ? des_buf[des_n++] : EOF; -#else - return (getc(fp)); -#endif -} - - -/* put_des_char: write a char to an encrypted file; return char written */ -int -put_des_char(int c, FILE *fp) -{ -#ifdef DES - if (des_n == sizeof des_buf) { - des_ct = cbc_encode(des_buf, des_n, fp); - des_n = 0; - } - return (des_ct >= 0) ? (des_buf[des_n++] = c) : EOF; -#else - return (fputc(c, fp)); -#endif -} - - -/* flush_des_file: flush an encrypted file's output; return status */ -int -flush_des_file(FILE *fp) -{ -#ifdef DES - if (des_n == sizeof des_buf) { - des_ct = cbc_encode(des_buf, des_n, fp); - des_n = 0; - } - return (des_ct >= 0 && cbc_encode(des_buf, des_n, fp) >= 0) ? 0 : EOF; -#else - return (fflush(fp)); -#endif -} - -#ifdef DES -/* - * get keyword from tty or stdin - */ -int -get_keyword(void) -{ - char *p; /* used to obtain the key */ - DES_cblock msgbuf; /* I/O buffer */ - - /* - * get the key - */ - if ((p = getpass("Enter key: ")) != NULL && *p != '\0') { - - /* - * copy it, nul-padded, into the key area - */ - expand_des_key(msgbuf, p); - MEMZERO(p, _PASSWORD_LEN); - set_des_key(&msgbuf); - MEMZERO(msgbuf, sizeof msgbuf); - return 1; - } - return 0; -} - - -/* - * print a warning message and, possibly, terminate - */ -void -des_error(const char *s) -{ - errmsg = s ? s : strerror(errno); -} - -/* - * map a hex character to an integer - */ -int -hex_to_binary(int c, int radix) -{ - switch(c) { - case '0': return(0x0); - case '1': return(0x1); - case '2': return(radix > 2 ? 0x2 : -1); - case '3': return(radix > 3 ? 0x3 : -1); - case '4': return(radix > 4 ? 0x4 : -1); - case '5': return(radix > 5 ? 0x5 : -1); - case '6': return(radix > 6 ? 0x6 : -1); - case '7': return(radix > 7 ? 0x7 : -1); - case '8': return(radix > 8 ? 0x8 : -1); - case '9': return(radix > 9 ? 0x9 : -1); - case 'A': case 'a': return(radix > 10 ? 0xa : -1); - case 'B': case 'b': return(radix > 11 ? 0xb : -1); - case 'C': case 'c': return(radix > 12 ? 0xc : -1); - case 'D': case 'd': return(radix > 13 ? 0xd : -1); - case 'E': case 'e': return(radix > 14 ? 0xe : -1); - case 'F': case 'f': return(radix > 15 ? 0xf : -1); - } - /* - * invalid character - */ - return(-1); -} - -/* - * convert the key to a bit pattern - * obuf bit pattern - * kbuf the key itself - */ -void -expand_des_key(char *obuf, char *kbuf) -{ - int i, j; /* counter in a for loop */ - int nbuf[64]; /* used for hex/key translation */ - - /* - * leading '0x' or '0X' == hex key - */ - if (kbuf[0] == '0' && (kbuf[1] == 'x' || kbuf[1] == 'X')) { - kbuf = &kbuf[2]; - /* - * now translate it, bombing on any illegal hex digit - */ - for (i = 0; i < 16 && kbuf[i]; i++) - if ((nbuf[i] = hex_to_binary((int) kbuf[i], 16)) == -1) - des_error("bad hex digit in key"); - while (i < 16) - nbuf[i++] = 0; - for (i = 0; i < 8; i++) - obuf[i] = - ((nbuf[2*i]&0xf)<<4) | (nbuf[2*i+1]&0xf); - /* preserve parity bits */ - pflag = 1; - return; - } - /* - * leading '0b' or '0B' == binary key - */ - if (kbuf[0] == '0' && (kbuf[1] == 'b' || kbuf[1] == 'B')) { - kbuf = &kbuf[2]; - /* - * now translate it, bombing on any illegal binary digit - */ - for (i = 0; i < 16 && kbuf[i]; i++) - if ((nbuf[i] = hex_to_binary((int) kbuf[i], 2)) == -1) - des_error("bad binary digit in key"); - while (i < 64) - nbuf[i++] = 0; - for (i = 0; i < 8; i++) - for (j = 0; j < 8; j++) - obuf[i] = (obuf[i]<<1)|nbuf[8*i+j]; - /* preserve parity bits */ - pflag = 1; - return; - } - /* - * no special leader -- ASCII - */ - (void)strncpy(obuf, kbuf, 8); -} - -/***************** - * DES FUNCTIONS * - *****************/ -/* - * This sets the DES key and (if you're using the deszip version) - * the direction of the transformation. This uses the Sun - * to map the 64-bit key onto the 56 bits that the key schedule - * generation routines use: the old way, which just uses the user- - * supplied 64 bits as is, and the new way, which resets the parity - * bit to be the same as the low-order bit in each character. The - * new way generates a greater variety of key schedules, since many - * systems set the parity (high) bit of each character to 0, and the - * DES ignores the low order bit of each character. - */ -void -set_des_key(DES_cblock *buf) /* key block */ -{ - int i, j; /* counter in a for loop */ - int par; /* parity counter */ - - /* - * if the parity is not preserved, flip it - */ - if (!pflag) { - for (i = 0; i < 8; i++) { - par = 0; - for (j = 1; j < 8; j++) - if ((bits[j] & (*buf)[i]) != 0) - par++; - if ((par & 0x01) == 0x01) - (*buf)[i] &= 0x7f; - else - (*buf)[i] = ((*buf)[i] & 0x7f) | 0x80; - } - } - - DES_set_odd_parity(buf); - DES_set_key(buf, &schedule); -} - - -/* - * This encrypts using the Cipher Block Chaining mode of DES - */ -int -cbc_encode(unsigned char *msgbuf, int n, FILE *fp) -{ - int inverse = 0; /* 0 to encrypt, 1 to decrypt */ - - /* - * do the transformation - */ - if (n == 8) { - for (n = 0; n < 8; n++) - msgbuf[n] ^= ivec[n]; - DES_XFORM((DES_cblock *)msgbuf); - MEMCPY(ivec, msgbuf, 8); - return WRITE(msgbuf, 8, fp); - } - /* - * at EOF or last block -- in either case, the last byte contains - * the character representation of the number of bytes in it - */ -/* - MEMZERO(msgbuf + n, 8 - n); -*/ - /* - * Pad the last block randomly - */ - (void)MEMCPY(msgbuf + n, pvec, 8 - n); - msgbuf[7] = n; - for (n = 0; n < 8; n++) - msgbuf[n] ^= ivec[n]; - DES_XFORM((DES_cblock *)msgbuf); - return WRITE(msgbuf, 8, fp); -} - -/* - * This decrypts using the Cipher Block Chaining mode of DES - * msgbuf I/O buffer - * fp input file descriptor - */ -int -cbc_decode(unsigned char *msgbuf, FILE *fp) -{ - DES_cblock tbuf; /* temp buffer for initialization vector */ - int n; /* number of bytes actually read */ - int c; /* used to test for EOF */ - int inverse = 1; /* 0 to encrypt, 1 to decrypt */ - - if ((n = READ(msgbuf, 8, fp)) == 8) { - /* - * do the transformation - */ - MEMCPY(tbuf, msgbuf, 8); - DES_XFORM((DES_cblock *)msgbuf); - for (c = 0; c < 8; c++) - msgbuf[c] ^= ivec[c]; - MEMCPY(ivec, tbuf, 8); - /* - * if the last one, handle it specially - */ - if ((c = fgetc(fp)) == EOF) { - n = msgbuf[7]; - if (n < 0 || n > 7) { - des_error("decryption failed (block corrupted)"); - return EOF; - } - } else - (void)ungetc(c, fp); - return n; - } - if (n > 0) - des_error("decryption failed (incomplete block)"); - else if (n < 0) - des_error("cannot read file"); - return EOF; -} -#endif /* DES */ diff --git a/bin/ed/ed.1 b/bin/ed/ed.1 index 6876c5cfb3f1..0cdd1b9c3e3c 100644 --- a/bin/ed/ed.1 +++ b/bin/ed/ed.1 @@ -1,5 +1,5 @@ .\" $FreeBSD$ -.Dd February 5, 2017 +.Dd November 3, 2018 .Dt ED 1 .Os .Sh NAME @@ -9,12 +9,12 @@ .Sh SYNOPSIS .Nm .Op Fl -.Op Fl sx +.Op Fl s .Op Fl p Ar string .Op Ar file .Nm red .Op Fl -.Op Fl sx +.Op Fl s .Op Fl p Ar string .Op Ar file .Sh DESCRIPTION @@ -141,11 +141,6 @@ Suppress diagnostics. This should be used if .Nm Ns 's standard input is from a script. -.It Fl x -Prompt for an encryption key to be used in subsequent reads and writes -(see the -.Em x -command). .It Fl p Ar string Specify a command prompt. This may be toggled on and off with the @@ -865,12 +860,6 @@ This is similar to the .Em w command, expect that the previous contents of file is not clobbered. The current address is unchanged. -.It x -Prompt for an encryption key which is used in subsequent reads and -writes. -If a newline alone is entered as the key, then encryption is -turned off. -Otherwise, echoing is disabled while a key is read. .It Pf (.+1)z n Scroll .Ar n diff --git a/bin/ed/ed.h b/bin/ed/ed.h index 597e3464e7fa..4dcf5eb36f37 100644 --- a/bin/ed/ed.h +++ b/bin/ed/ed.h @@ -175,17 +175,6 @@ if ((i) > (n)) { \ /* NEWLINE_TO_NUL: overwrite newlines with ASCII NULs */ #define NEWLINE_TO_NUL(s, l) translit_text(s, l, '\n', '\0') -#ifdef ED_DES_INCLUDES -void des_error(const char *); -void expand_des_key(char *, char *); -void set_des_key(DES_cblock *); -#endif - -/* Other DES support stuff */ -void init_des_cipher(void); -int flush_des_file(FILE *); -int get_des_char(FILE *); -int put_des_char(int, FILE *); /* Local Function Declarations */ void add_line_node(line_t *); @@ -280,6 +269,5 @@ extern long u_current_addr; extern long rows; extern int cols; extern int newline_added; -extern int des; extern int scripted; extern int patlock; diff --git a/bin/ed/io.c b/bin/ed/io.c index 1907e7a95472..697e0a4c7ab5 100644 --- a/bin/ed/io.c +++ b/bin/ed/io.c @@ -76,8 +76,6 @@ read_stream(FILE *fp, long n) int len; isbinary = newline_added = 0; - if (des) - init_des_cipher(); for (current_addr = n; (len = get_stream_line(fp)) > 0; size += len) { SPL1(); if (put_sbuf_line(sbuf) == NULL) { @@ -106,8 +104,6 @@ read_stream(FILE *fp, long n) newline_added = 1; newline_added = appended ? newline_added : o_newline_added; isbinary = isbinary | o_isbinary; - if (des) - size += 8 - size % 8; /* adjust DES size */ return size; } @@ -119,8 +115,8 @@ get_stream_line(FILE *fp) int c; int i = 0; - while (((c = des ? get_des_char(fp) : getc(fp)) != EOF || (!feof(fp) && - !ferror(fp))) && c != '\n') { + while (((c = getc(fp)) != EOF || (!feof(fp) && !ferror(fp))) && + c != '\n') { REALLOC(sbuf, sbufsz, i + 1, ERR); if (!(sbuf[i++] = c)) isbinary = 1; @@ -180,8 +176,6 @@ write_stream(FILE *fp, long n, long m) char *s; int len; - if (des) - init_des_cipher(); for (; n && n <= m; n++, lp = lp->q_forw) { if ((s = get_sbuf_line(lp)) == NULL) return ERR; @@ -192,10 +186,6 @@ write_stream(FILE *fp, long n, long m) return ERR; size += len; } - if (des) { - flush_des_file(fp); /* flush buffer */ - size += 8 - size % 8; /* adjust DES size */ - } return size; } @@ -205,7 +195,7 @@ int put_stream_line(FILE *fp, const char *s, int len) { while (len--) - if ((des ? put_des_char(*s++, fp) : fputc(*s++, fp)) < 0) { + if (fputc(*s++, fp) < 0) { fprintf(stderr, "%s\n", strerror(errno)); errmsg = "cannot write file"; return ERR; diff --git a/bin/ed/main.c b/bin/ed/main.c index babffa813088..82ab6d195038 100644 --- a/bin/ed/main.c +++ b/bin/ed/main.c @@ -47,10 +47,6 @@ __FBSDID("$FreeBSD$"); * The buffering algorithm is attributed to Rodney Ruddock of * the University of Guelph, Guelph, Ontario. * - * The cbc.c encryption code is adapted from - * the bdes program by Matt Bishop of Dartmouth College, - * Hanover, NH. - * */ #include @@ -81,7 +77,6 @@ int ibufsz; /* ed command-line buffer size */ char *ibufp; /* pointer to ed command-line buffer */ /* global flags */ -int des = 0; /* if set, use crypt(3) for i/o */ static int garrulous = 0; /* if set, print all error messages */ int isbinary; /* if set, buffer contains ASCII NULs */ int isglobal; /* if set, doing a global command */ @@ -121,11 +116,7 @@ main(volatile int argc, char ** volatile argv) scripted = 1; break; case 'x': /* use crypt */ -#ifdef DES - des = get_keyword(); -#else fprintf(stderr, "crypt unavailable\n?\n"); -#endif break; default: @@ -821,13 +812,8 @@ exec_command(void) return ERR; } GET_COMMAND_SUFFIX(); -#ifdef DES - des = get_keyword(); - break; -#else errmsg = "crypt unavailable"; return ERR; -#endif case 'z': #ifdef BACKWARDS if (check_addr_range(first_addr = 1, current_addr + 1) < 0) diff --git a/contrib/expat/AUTHORS b/contrib/expat/AUTHORS new file mode 100644 index 000000000000..99475bb1b2ef --- /dev/null +++ b/contrib/expat/AUTHORS @@ -0,0 +1,10 @@ +Expat is brought to you by: + +Clark Cooper +Fred L. Drake, Jr. +Greg Stein +James Clark +Karl Waclawek +Rhodri James +Sebastian Pipping +Steven Solie diff --git a/contrib/expat/COPYING b/contrib/expat/COPYING index 092c83baee13..8d288f0f28fd 100644 --- a/contrib/expat/COPYING +++ b/contrib/expat/COPYING @@ -1,5 +1,5 @@ Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper -Copyright (c) 2001-2016 Expat maintainers +Copyright (c) 2001-2017 Expat maintainers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/contrib/expat/Changes b/contrib/expat/Changes index 583c86857629..b0ee42cd36cf 100644 --- a/contrib/expat/Changes +++ b/contrib/expat/Changes @@ -1,3 +1,333 @@ +NOTE: We are looking for help with a few things: + https://github.com/libexpat/libexpat/labels/help%20wanted + If you can help, please get in touch. Thanks! + +Release 2.2.6 Sun August 12 2018 + Bug fixes: + #170 #206 Avoid doing arithmetic with NULL pointers in XML_GetBuffer + #204 #205 Fix 2.2.5 regression with suspend-resume while parsing + a document like '' + + Other changes: + #165 #168 Autotools: Fix docbook-related configure syntax error + #166 Autotools: Avoid grep option `-q` for Solaris + #167 Autotools: Support + ./configure DOCBOOK_TO_MAN="xmlto man --skip-validation" + #159 #167 Autotools: Support DOCBOOK_TO_MAN command which produces + xmlwf.1 rather than XMLWF.1; also covers case insensitive + file systems + #181 Autotools: Drop -rpath option passed to libtool + #188 Autotools: Detect and deny SGML docbook2man as ours is XML + #188 Autotools/CMake: Support command db2x_docbook2man as well + #174 CMake: Introduce option WARNINGS_AS_ERRORS, defaults to OFF + #184 #185 CMake: Introduce option MSVC_USE_STATIC_CRT, defaults to OFF + #207 #208 CMake: Introduce option XML_UNICODE and XML_UNICODE_WCHAR_T, + both defaulting to OFF + #175 CMake: Prefer check_symbol_exists over check_function_exists + #176 CMake: Create the same pkg-config file as with GNU Autotools + #178 #179 CMake: Use GNUInstallDirs module to set proper defaults for + install directories + #208 CMake: Utilize expat_config.h.cmake for XML_DEV_URANDOM + #180 Windows: Fix compilation of test suite for Visual Studio 2008 + #131 #173 #202 Address compiler warnings + #187 #190 #200 Fix miscellaneous typos + Version info bumped from 7:7:6 to 7:8:6 + + Special thanks to: + Anton Maklakov + Benjamin Peterson + Brad King + Franek Korta + Frank Rast + Joe Orton + luzpaz + Pedro Vicente + Rainer Jung + Rhodri James + Rolf Ade + Rolf Eike Beer + Thomas Beutlich + Tomasz Kłoczko + +Release 2.2.5 Tue October 31 2017 + Bug fixes: + #8 If the parser runs out of memory, make sure its internal + state reflects the memory it actually has, not the memory + it wanted to have. + #11 The default handler wasn't being called when it should for + a SYSTEM or PUBLIC doctype if an entity declaration handler + was registered. + #137 #138 Fix a case of mistakenly reported parsing success where + XML_StopParser was called from an element handler + #162 Function XML_ErrorString was returning NULL rather than + a message for code XML_ERROR_INVALID_ARGUMENT + introduced with release 2.2.1 + + Other changes: + #106 xmlwf: Add argument -N adding notation declarations + #75 #106 Test suite: Resolve expected failure cases where xmlwf + output was incomplete + #127 Windows: Fix test suite compilation + #126 #127 Windows: Fix compilation for Visual Studio 2012 + Windows: Upgrade shipped project files to Visual Studio 2017 + #33 #132 tests: Mass-fix compilation for XML_UNICODE_WCHAR_T + #129 examples: Fix compilation for XML_UNICODE_WCHAR_T + #130 benchmark: Fix compilation for XML_UNICODE_WCHAR_T + #144 xmlwf: Fix compilation for XML_UNICODE_WCHAR_T; still needs + Windows or MinGW for 2-byte wchar_t + #9 Address two Clang Static Analyzer false positives + #59 Resolve troublesome macros hiding parser struct membership + and dereferencing that pointer + #6 Resolve superfluous internal malloc/realloc switch + #153 #155 Improve docbook2x-man detection + #160 Undefine NDEBUG in the test suite (rather than rejecting it) + #161 Address compiler warnings + Version info bumped from 7:6:6 to 7:7:6 + + Special thanks to: + Benbuck Nason + Hans Wennborg + José Gutiérrez de la Concha + Pedro Monreal Gonzalez + Rhodri James + Rolf Ade + Stephen Groat + and + Core Infrastructure Initiative + +Release 2.2.4 Sat August 19 2017 + Bug fixes: + #115 Fix copying of partial characters for UTF-8 input + + Other changes: + #109 Fix "make check" for non-x86 architectures that default + to unsigned type char (-128..127 rather than 0..255) + #109 coverage.sh: Cover -funsigned-char + Autotools: Introduce --without-xmlwf argument + #65 Autotools: Replace handwritten Makefile with GNU Automake + #43 CMake: Auto-detect high quality entropy extractors, add new + option USE_libbsd=ON to use arc4random_buf of libbsd + #74 CMake: Add -fno-strict-aliasing only where supported + #114 CMake: Always honor manually set BUILD_* options + #114 CMake: Compile man page if docbook2x-man is available, only + #117 Include file tests/xmltest.log.expected in source tarball + (required for "make run-xmltest") + #117 Include (existing) Visual Studio 2013 files in source tarball + Improve test suite error output + #111 Fix some typos in documentation + Version info bumped from 7:5:6 to 7:6:6 + + Special thanks to: + Jakub Wilk + Joe Orton + Lin Tian + Rolf Eike Beer + +Release 2.2.3 Wed August 2 2017 + Security fixes: + #82 CVE-2017-11742 -- Windows: Fix DLL hijacking vulnerability + using Steve Holme's LoadLibrary wrapper for/of cURL + + Bug fixes: + #85 Fix a dangling pointer issue related to realloc + + Other changes: + Increase code coverage + #91 Linux: Allow getrandom to fail if nonblocking pool has not + yet been initialized and read /dev/urandom then, instead. + This is in line with what recent Python does. + #81 Pre-10.7/Lion macOS: Support entropy from arc4random + #86 Check that a UTF-16 encoding in an XML declaration has the + right endianness + #4 #5 #7 Recover correctly when some reallocations fail + Repair "./configure && make" for systems without any + provider of high quality entropy + and try reading /dev/urandom on those + Ensure that user-defined character encodings have converter + functions when they are needed + Fix mis-leading description of argument -c in xmlwf.1 + Rely on macro HAVE_ARC4RANDOM_BUF (rather than __CloudABI__) + for CloudABI + #100 Fix use of SIPHASH_MAIN in siphash.h + #23 Test suite: Fix memory leaks + Version info bumped from 7:4:6 to 7:5:6 + + Special thanks to: + Chanho Park + Joe Orton + Pascal Cuoq + Rhodri James + Simon McVittie + Vadim Zeitlin + Viktor Szakats + and + Core Infrastructure Initiative + +Release 2.2.2 Wed July 12 2017 + Security fixes: + #43 Protect against compilation without any source of high + quality entropy enabled, e.g. with CMake build system; + commit ff0207e6076e9828e536b8d9cd45c9c92069b895 + #60 Windows with _UNICODE: + Unintended use of LoadLibraryW with a non-wide string + resulted in failure to load advapi32.dll and degradation + in quality of used entropy when compiled with _UNICODE for + Windows; you can launch existing binaries with + EXPAT_ENTROPY_DEBUG=1 in the environment to inspect the + quality of entropy used during runtime; commits + * 95b95032f907ef1cd17ee7a9a1768010a825d61d + * 73a5a2e9c081f49f2d775cf7ced864158b68dc80 + [MOX-006] Fix non-NULL parser parameter validation in XML_Parse; + resulted in NULL dereference, previously; + commit ac256dafdffc9622ab0dc2c62fcecb0dfcfa71fe + + Bug fixes: + #69 Fix improper use of unsigned long long integer literals + + Other changes: + #73 Start requiring a C99 compiler + #49 Fix "==" Bashism in configure script + #50 Fix too eager getrandom detection for Debian GNU/kFreeBSD + #52 and macOS + #51 Address lack of stdint.h in Visual Studio 2003 to 2008 + #58 Address compile warnings + #68 Fix "./buildconf.sh && ./configure" for some versions + of Dash for /bin/sh + #72 CMake: Ease use of Expat in context of a parent project + with multiple CMakeLists.txt files + #72 CMake: Resolve mistaken executable permissions + #76 Address compile warning with -DNDEBUG (not recommended!) + #77 Address compile warning about macro redefinition + + Special thanks to: + Alexander Bluhm + Ben Boeckel + Cătălin Răceanu + Kerin Millar + László Böszörményi + S. P. Zeidler + Segev Finer + Václav Slavík + Victor Stinner + Viktor Szakats + and + Radically Open Security + +Release 2.2.1 Sat June 17 2017 + Security fixes: + CVE-2017-9233 -- External entity infinite loop DoS + Details: https://libexpat.github.io/doc/cve-2017-9233/ + Commit c4bf96bb51dd2a1b0e185374362ee136fe2c9d7f + [MOX-002] CVE-2016-9063 -- Detect integer overflow; commit + d4f735b88d9932bd5039df2335eefdd0723dbe20 + (Fixed version of existing downstream patches!) + (SF.net) #539 Fix regression from fix to CVE-2016-0718 cutting off + longer tag names; commits + * 896b6c1fd3b842f377d1b62135dccf0a579cf65d + * af507cef2c93cb8d40062a0abe43a4f4e9158fb2 + #16 * 0dbbf43fdb20f593ddf4fa1ff67288000dd4a7fd + #25 More integer overflow detection (function poolGrow); commits + * 810b74e4703dcfdd8f404e3cb177d44684775143 + * 44178553f3539ce69d34abee77a05e879a7982ac + [MOX-002] Detect overflow from len=INT_MAX call to XML_Parse; commits + * 4be2cb5afcc018d996f34bbbce6374b7befad47f + * 7e5b71b748491b6e459e5c9a1d090820f94544d8 + [MOX-005] #30 Use high quality entropy for hash initialization: + * arc4random_buf on BSD, systems with libbsd + (when configured with --with-libbsd), CloudABI + * RtlGenRandom on Windows XP / Server 2003 and later + * getrandom on Linux 3.17+ + In a way, that's still part of CVE-2016-5300. + https://github.com/libexpat/libexpat/pull/30/commits + [MOX-005] For the low quality entropy extraction fallback code, + the parser instance address can no longer leak, commit + 04ad658bd3079dd15cb60fc67087900f0ff4b083 + [MOX-003] Prevent use of uninitialised variable; commit + [MOX-004] a4dc944f37b664a3ca7199c624a98ee37babdb4b + Add missing parameter validation to public API functions + and dedicated error code XML_ERROR_INVALID_ARGUMENT: + [MOX-006] * NULL checks; commits + * d37f74b2b7149a3a95a680c4c4cd2a451a51d60a (merge/many) + * 9ed727064b675b7180c98cb3d4f75efba6966681 + * 6a747c837c50114dfa413994e07c0ba477be4534 + * Negative length (XML_Parse); commit + [MOX-002] 70db8d2538a10f4c022655d6895e4c3e78692e7f + [MOX-001] #35 Change hash algorithm to William Ahern's version of SipHash + to go further with fixing CVE-2012-0876. + https://github.com/libexpat/libexpat/pull/39/commits + + Bug fixes: + #32 Fix sharing of hash salt across parsers; + relevant where XML_ExternalEntityParserCreate is called + prior to XML_Parse, in particular (e.g. FBReader) + #28 xmlwf: Auto-disable use of memory-mapping (and parsing + as a single chunk) for files larger than ~1 GB (2^30 bytes) + rather than failing with error "out of memory" + #3 Fix double free after malloc failure in DTD code; commit + 7ae9c3d3af433cd4defe95234eae7dc8ed15637f + #17 Fix memory leak on parser error for unbound XML attribute + prefix with new namespaces defined in the same tag; + found by Google's OSS-Fuzz; commits + * 16f87daae5a16132e479e4f71862128c7a915c73 + * b47dbc9745932c160893d433220e462bd605f8cd + xmlwf on Windows: Add missing calls to CloseHandle + + New features: + #30 Introduced environment switch EXPAT_ENTROPY_DEBUG=1 + for runtime debugging of entropy extraction + + Other changes: + Increase code coverage + #33 Reject use of XML_UNICODE_WCHAR_T with sizeof(wchar_t) != 2; + XML_UNICODE_WCHAR_T was never meant to be used outside + of Windows; 4-byte wchar_t is common on Linux + (SF.net) #538 Start using -fno-strict-aliasing + (SF.net) #540 Support compilation against cloudlibc of CloudABI + Allow MinGW cross-compilation + (SF.net) #534 CMake: Introduce option "BUILD_doc" (enabled by default) + to bypass compilation of the xmlwf.1 man page + (SF.net) pr2 CMake: Introduce option "INSTALL" (enabled by default) + to bypass installation of expat files + CMake: Fix ninja support + Autotools: Add parameters --enable-xml-context [COUNT] + and --disable-xml-context; default of context of 1024 + bytes enabled unchanged + #14 Drop AmigaOS 4.x code and includes + #14 Drop ancient build systems: + * Borland C++ Builder + * OpenVMS + * Open Watcom + * Visual Studio 6.0 + * Pre-X Mac OS (MPW Makefile) + If you happen to rely on some of these, please get in + touch for joining with maintenance. + #10 Move from WIN32 to _WIN32 + #13 Fix "make run-xmltest" order instability + Address compile warnings + Bump version info from 7:2:6 to 7:3:6 + Add AUTHORS file + + Infrastructure: + #1 Migrate from SourceForge to GitHub (except downloads): + https://github.com/libexpat/ + #1 Re-create http://libexpat.org/ project website + Start utilizing Travis CI + + Special thanks to: + Andy Wang + Don Lewis + Ed Schouten + Karl Waclawek + Pascal Cuoq + Rhodri James + Sergei Nikulov + Tobias Taschner + Viktor Szakats + and + Core Infrastructure Initiative + Mozilla Foundation (MOSS Track 3: Secure Open Source) + Radically Open Security + Release 2.2.0 Tue June 21 2016 Security fixes: #537 CVE-2016-0718 -- Fix crash on malformed input @@ -63,24 +393,25 @@ Release 2.1.1 Sat March 12 2016 libtool now invoked with --verbose Release 2.1.0 Sat March 24 2012 + - Security fixes: + #2958794: CVE-2012-1148 - Memory leak in poolGrow. + #2895533: CVE-2012-1147 - Resource leak in readfilemap.c. + #3496608: CVE-2012-0876 - Hash DOS attack. + #2894085: CVE-2009-3560 - Buffer over-read and crash in big2_toUtf8(). + #1990430: CVE-2009-3720 - Parser crash with special UTF-8 sequences. - Bug Fixes: #1742315: Harmful XML_ParserCreateNS suggestion. - #2895533: CVE-2012-1147 - Resource leak in readfilemap.c. #1785430: Expat build fails on linux-amd64 with gcc version>=4.1 -O3. #1983953, 2517952, 2517962, 2649838: Build modifications using autoreconf instead of buildconf.sh. #2815947, #2884086: OBJEXT and EXEEXT support while building. - #1990430: CVE-2009-3720 - Parser crash with special UTF-8 sequences. #2517938: xmlwf should return non-zero exit status if not well-formed. #2517946: Wrong statement about XMLDecl in xmlwf.1 and xmlwf.sgml. #2855609: Dangling positionPtr after error. - #2894085: CVE-2009-3560 - Buffer over-read and crash in big2_toUtf8(). - #2958794: CVE-2012-1148 - Memory leak in poolGrow. #2990652: CMake support. #3010819: UNEXPECTED_STATE with a trailing "%" in entity value. - #3206497: Unitialized memory returned from XML_Parse. + #3206497: Uninitialized memory returned from XML_Parse. #3287849: make check fails on mingw-w64. - #3496608: CVE-2012-0876 - Hash DOS attack. - Patches: #1749198: pkg-config support. #3010222: Fix for bug #3010819. diff --git a/contrib/expat/FREEBSD-Xlist b/contrib/expat/FREEBSD-Xlist index 26bed47ba54b..d5b4f670b696 100644 --- a/contrib/expat/FREEBSD-Xlist +++ b/contrib/expat/FREEBSD-Xlist @@ -6,6 +6,7 @@ *.dsw *.m4 *.pc.in +*.vcxproj* *config.h CMake* Configure* @@ -14,6 +15,7 @@ bcb5 configure conftools doc/valid-xhtml10.png +expat.sln m4 vms win32 diff --git a/contrib/expat/MANIFEST b/contrib/expat/MANIFEST deleted file mode 100644 index afb9acacdf06..000000000000 --- a/contrib/expat/MANIFEST +++ /dev/null @@ -1,141 +0,0 @@ -amiga/launch.c -amiga/expat_68k.c -amiga/expat_68k.h -amiga/expat_68k_handler_stubs.c -amiga/expat_base.h -amiga/expat_vectors.c -amiga/expat_lib.c -amiga/expat.xml -amiga/README.txt -amiga/Makefile -amiga/include/proto/expat.h -amiga/include/libraries/expat.h -amiga/include/interfaces/expat.h -amiga/include/inline4/expat.h -bcb5/README.txt -bcb5/all_projects.bpg -bcb5/elements.bpf -bcb5/elements.bpr -bcb5/elements.mak -bcb5/expat.bpf -bcb5/expat.bpr -bcb5/expat.mak -bcb5/expat_static.bpf -bcb5/expat_static.bpr -bcb5/expat_static.mak -bcb5/expatw.bpf -bcb5/expatw.bpr -bcb5/expatw.mak -bcb5/expatw_static.bpf -bcb5/expatw_static.bpr -bcb5/expatw_static.mak -bcb5/libexpat_mtd.def -bcb5/libexpatw_mtd.def -bcb5/makefile.mak -bcb5/outline.bpf -bcb5/outline.bpr -bcb5/outline.mak -bcb5/setup.bat -bcb5/xmlwf.bpf -bcb5/xmlwf.bpr -bcb5/xmlwf.mak -doc/expat.png -doc/reference.html -doc/style.css -doc/valid-xhtml10.png -doc/xmlwf.1 -doc/xmlwf.xml -CMakeLists.txt -CMake.README -COPYING -Changes -ConfigureChecks.cmake -MANIFEST -Makefile.in -README -configure -configure.ac -expat_config.h.in -expat_config.h.cmake -expat.pc.in -expat.dsw -aclocal.m4 -conftools/PrintPath -conftools/ac_c_bigendian_cross.m4 -conftools/expat.m4 -conftools/get-version.sh -conftools/mkinstalldirs -conftools/config.guess -conftools/config.sub -conftools/install-sh -conftools/ltmain.sh -m4/libtool.m4 -m4/ltversion.m4 -m4/ltoptions.m4 -m4/ltsugar.m4 -m4/lt~obsolete.m4 -examples/elements.c -examples/elements.dsp -examples/outline.c -examples/outline.dsp -lib/Makefile.MPW -lib/amigaconfig.h -lib/ascii.h -lib/asciitab.h -lib/expat.dsp -lib/expat.h -lib/expat_external.h -lib/expat_static.dsp -lib/expatw.dsp -lib/expatw_static.dsp -lib/iasciitab.h -lib/internal.h -lib/latin1tab.h -lib/libexpat.def -lib/libexpatw.def -lib/macconfig.h -lib/nametab.h -lib/utf8tab.h -lib/winconfig.h -lib/xmlparse.c -lib/xmlrole.c -lib/xmlrole.h -lib/xmltok.c -lib/xmltok.h -lib/xmltok_impl.c -lib/xmltok_impl.h -lib/xmltok_ns.c -tests/benchmark/README.txt -tests/benchmark/benchmark.c -tests/benchmark/benchmark.dsp -tests/benchmark/benchmark.dsw -tests/README.txt -tests/chardata.c -tests/chardata.h -tests/minicheck.c -tests/minicheck.h -tests/runtests.c -tests/runtestspp.cpp -tests/xmltest.sh -vms/README.vms -vms/descrip.mms -vms/expat_config.h -win32/MANIFEST.txt -win32/README.txt -win32/expat.iss -xmlwf/codepage.c -xmlwf/codepage.h -xmlwf/ct.c -xmlwf/filemap.h -xmlwf/readfilemap.c -xmlwf/unixfilemap.c -xmlwf/win32filemap.c -xmlwf/xmlfile.c -xmlwf/xmlfile.h -xmlwf/xmlmime.c -xmlwf/xmlmime.h -xmlwf/xmltchar.h -xmlwf/xmlurl.h -xmlwf/xmlwf.c -xmlwf/xmlwf.dsp -xmlwf/xmlwin32url.cxx diff --git a/contrib/expat/Makefile.am b/contrib/expat/Makefile.am new file mode 100644 index 000000000000..5ed9ac410a42 --- /dev/null +++ b/contrib/expat/Makefile.am @@ -0,0 +1,153 @@ +# +# __ __ _ +# ___\ \/ /_ __ __ _| |_ +# / _ \\ /| '_ \ / _` | __| +# | __// \| |_) | (_| | |_ +# \___/_/\_\ .__/ \__,_|\__| +# |_| XML parser +# +# Copyright (c) 2017 Expat development team +# Licensed under the MIT license: +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the +# following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +# USE OR OTHER DEALINGS IN THE SOFTWARE. + +AUTOMAKE_OPTIONS = \ + dist-bzip2 \ + foreign \ + no-dist-gzip \ + subdir-objects + +ACLOCAL_AMFLAGS = -I m4 +LIBTOOLFLAGS = --verbose + +SUBDIRS = lib examples tests # lib goes first to build first +if WITH_XMLWF +SUBDIRS += xmlwf doc +endif + +pkgconfig_DATA = expat.pc +pkgconfigdir = $(libdir)/pkgconfig + + +_EXTRA_DIST_CMAKE = \ + CMakeLists.txt \ + CMake.README \ + ConfigureChecks.cmake \ + expat_config.h.cmake + +_EXTRA_DIST_WINDOWS = \ + examples/elements.vcxproj \ + examples/elements.vcxproj.filters \ + examples/outline.vcxproj \ + examples/outline.vcxproj.filters \ + \ + lib/expat_static.vcxproj \ + lib/expat_static.vcxproj.filters \ + lib/expat.vcxproj \ + lib/expat.vcxproj.filters \ + lib/expatw_static.vcxproj \ + lib/expatw_static.vcxproj.filters \ + lib/expatw.vcxproj \ + lib/expatw.vcxproj.filters \ + \ + tests/benchmark/benchmark.sln \ + tests/benchmark/benchmark.vcxproj \ + \ + tests/runtests.sln \ + tests/runtests.vcxproj \ + tests/runtests.vcxproj.filters \ + \ + win32/expat.iss \ + win32/MANIFEST.txt \ + win32/README.txt \ + \ + xmlwf/xmlwf.vcxproj \ + xmlwf/xmlwf.vcxproj.filters \ + \ + expat.sln + +EXTRA_DIST = \ + $(_EXTRA_DIST_CMAKE) \ + $(_EXTRA_DIST_WINDOWS) \ + \ + conftools/expat.m4 \ + conftools/get-version.sh \ + conftools/PrintPath \ + \ + Changes \ + README.md \ + test-driver-wrapper.sh + + +.PHONY: buildlib +buildlib: + @echo 'ERROR: Running "make buildlib LIBRARY=libexpatw.la"' >&2 + @echo 'ERROR: is no longer supported. INSTEAD please:' >&2 + @echo 'ERROR:' >&2 + @echo 'ERROR: * Mass-patch Makefile.am, e.g.' >&2 + @echo 'ERROR: # find -name Makefile.am -exec sed \' >&2 + @echo 'ERROR: -e "s,libexpat\.la,libexpatw.la," \' >&2 + @echo 'ERROR: -e "s,libexpat_la,libexpatw_la," \' >&2 + @echo 'ERROR: -i {} +' >&2 + @echo 'ERROR:' >&2 + @echo 'ERROR: * Run automake to re-generate Makefile.in files' >&2 + @echo 'ERROR:' >&2 + @echo 'ERROR: * Use "./configure --without-xmlwf" and/or' >&2 + @echo 'ERROR: "make -C lib all install" to bypass compilation' >&2 + @echo 'ERROR: of xmlwf (e.g. with -DXML_UNICODE)' >&2 + @echo 'ERROR:' >&2 + @false + + +.PHONY: run-benchmark +run-benchmark: + $(MAKE) -C tests/benchmark + ./run.sh tests/benchmark/benchmark@EXEEXT@ -n $(top_srcdir)/../testdata/largefiles/recset.xml 65535 3 + +tests/xmlts.zip: + if test "$(XMLTS_ZIP)" = ""; then \ + wget --output-document=tests/xmlts.zip \ + https://www.w3.org/XML/Test/xmlts20080827.zip; \ + else \ + cp $(XMLTS_ZIP) tests/xmlts.zip; \ + fi + +tests/xmlconf: tests/xmlts.zip + cd tests && unzip -q xmlts.zip + +.PHONY: run-xmltest +run-xmltest: tests/xmlconf +if WITH_XMLWF + $(MAKE) -C xmlwf + tests/xmltest.sh "$(PWD)/run.sh $(PWD)/xmlwf/xmlwf@EXEEXT@" 2>&1 | tee tests/xmltest.log + dos2unix tests/xmltest.log + diff -u tests/xmltest.log.expected tests/xmltest.log +else + @echo 'ERROR: xmlwf is needed for "make run-xmltest".' >&2 + @echo 'ERROR: Please re-configure without --without-xmlwf.' >&2 + @false +endif + +.PHONY: qa +qa: + ./qa.sh address + ./qa.sh memory + ./qa.sh undefined + ./qa.sh coverage diff --git a/contrib/expat/Makefile.in b/contrib/expat/Makefile.in index 3310aa9aae92..9560a955aa81 100644 --- a/contrib/expat/Makefile.in +++ b/contrib/expat/Makefile.in @@ -1,194 +1,1019 @@ -################################################################ -# Process this file with top-level configure script to produce Makefile -# -# Copyright 2000 Clark Cooper -# -# This file is part of EXPAT. -# -# EXPAT is free software; you can redistribute it and/or modify it -# under the terms of the License (based on the MIT/X license) contained -# in the file COPYING that comes with this distribution. -# -# EXPAT IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -# SOFTWARE OR THE USE OR OTHER DEALINGS IN EXPAT. -# +# Makefile.in generated by automake 1.15.1 from Makefile.am. +# @configure_input@ -SHELL = @SHELL@ +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# +# __ __ _ +# ___\ \/ /_ __ __ _| |_ +# / _ \\ /| '_ \ / _` | __| +# | __// \| |_) | (_| | |_ +# \___/_/\_\ .__/ \__,_|\__| +# |_| XML parser +# +# Copyright (c) 2017 Expat development team +# Licensed under the MIT license: +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the +# following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +# USE OR OTHER DEALINGS IN THE SOFTWARE. -srcdir = @srcdir@ -top_srcdir = @top_srcdir@ VPATH = @srcdir@ - -prefix = @prefix@ -exec_prefix = @exec_prefix@ - -bindir = @bindir@ -libdir = @libdir@ -includedir = @includedir@ -man1dir = @mandir@/man1 -pkgconfigdir = $(libdir)/pkgconfig - -top_builddir = . - - -INSTALL = @INSTALL@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_DATA = @INSTALL_DATA@ -mkinstalldirs = $(SHELL) $(top_srcdir)/conftools/mkinstalldirs - -MANFILE = $(srcdir)/doc/xmlwf.1 -APIHEADER = $(srcdir)/lib/expat.h $(srcdir)/lib/expat_external.h expat_config.h -LIBRARY = libexpat.la - -DESTDIR = $(INSTALL_ROOT) - -default: buildlib xmlwf/xmlwf@EXEEXT@ - -buildlib: $(LIBRARY) expat.pc - -all: $(LIBRARY) expat.pc xmlwf/xmlwf@EXEEXT@ examples/elements examples/outline $(MANFILE) - -clean: - cd lib && rm -f $(LIBRARY) *.@OBJEXT@ *.lo && rm -rf .libs _libs - cd xmlwf && rm -f xmlwf *.@OBJEXT@ *.lo && rm -rf .libs _libs - cd examples && rm -f elements outline *.@OBJEXT@ *.lo && rm -rf .libs _libs - cd tests && rm -rf .libs runtests runtests.@OBJEXT@ runtestspp runtestspp.@OBJEXT@ - cd tests && rm -f chardata.@OBJEXT@ minicheck.@OBJEXT@ - rm -rf .libs libexpat.la - rm -f examples/core tests/core xmlwf/core - -clobber: clean - -distclean: clean - rm -f expat_config.h config.status config.log config.cache libtool - rm -f Makefile expat.pc - -extraclean: distclean - rm -f expat_config.h.in configure - rm -f aclocal.m4 m4/* - rm -f conftools/ltmain.sh conftools/install-sh conftools/config.guess conftools/config.sub - -check: tests/runtests tests/runtestspp - tests/runtests - tests/runtestspp - -$(MANFILE): - $(MAKE) -C doc xmlwf.1 - -install: xmlwf/xmlwf@EXEEXT@ installlib $(MANFILE) - $(mkinstalldirs) $(DESTDIR)$(bindir) $(DESTDIR)$(man1dir) - $(LIBTOOL) --mode=install $(INSTALL_PROGRAM) xmlwf/xmlwf@EXEEXT@ $(DESTDIR)$(bindir)/xmlwf - $(INSTALL_DATA) $(MANFILE) $(DESTDIR)$(man1dir) - -installlib: $(LIBRARY) $(APIHEADER) expat.pc - $(mkinstalldirs) $(DESTDIR)$(libdir) $(DESTDIR)$(includedir) $(DESTDIR)$(pkgconfigdir) - $(LIBTOOL) --mode=install $(INSTALL) $(LIBRARY) $(DESTDIR)$(libdir)/$(LIBRARY) - for FN in $(APIHEADER) ; do $(INSTALL_DATA) $$FN $(DESTDIR)$(includedir) ; done - $(INSTALL_DATA) expat.pc $(DESTDIR)$(pkgconfigdir)/expat.pc - -uninstall: uninstalllib - $(LIBTOOL) --mode=uninstall rm -f $(DESTDIR)$(bindir)/xmlwf@EXEEXT@ - rm -f $(DESTDIR)$(man1dir)/xmlwf.1 - -uninstalllib: - $(LIBTOOL) --mode=uninstall rm -f $(DESTDIR)$(libdir)/$(LIBRARY) - rm -f $(DESTDIR)$(includedir)/expat.h - rm -f $(DESTDIR)$(includedir)/expat_external.h - rm -f $(DESTDIR)$(pkgconfigdir)/expat.pc - -# for VPATH builds (invoked by configure) -mkdir-init: - @for d in lib xmlwf examples tests ; do \ - (mkdir $$d 2> /dev/null || test 1) ; \ - done - +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +@WITH_XMLWF_TRUE@am__append_1 = xmlwf doc +subdir = . +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/conftools/ac_c_bigendian_cross.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \ + $(am__configure_deps) $(am__DIST_COMMON) +am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ + configure.lineno config.status.lineno +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = expat_config.h +CONFIG_CLEAN_FILES = expat.pc run.sh +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ + ctags-recursive dvi-recursive html-recursive info-recursive \ + install-data-recursive install-dvi-recursive \ + install-exec-recursive install-html-recursive \ + install-info-recursive install-pdf-recursive \ + install-ps-recursive install-recursive installcheck-recursive \ + installdirs-recursive pdf-recursive ps-recursive \ + tags-recursive uninstall-recursive +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(pkgconfigdir)" +DATA = $(pkgconfig_DATA) +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +am__recursive_targets = \ + $(RECURSIVE_TARGETS) \ + $(RECURSIVE_CLEAN_TARGETS) \ + $(am__extra_recursive_targets) +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ + cscope distdir dist dist-all distcheck +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ + $(LISP)expat_config.h.in +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +ETAGS = etags +CTAGS = ctags +CSCOPE = cscope +DIST_SUBDIRS = lib examples tests xmlwf doc +am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/expat.pc.in \ + $(srcdir)/expat_config.h.in $(srcdir)/run.sh.in \ + $(top_srcdir)/conftools/compile \ + $(top_srcdir)/conftools/config.guess \ + $(top_srcdir)/conftools/config.sub \ + $(top_srcdir)/conftools/install-sh \ + $(top_srcdir)/conftools/ltmain.sh \ + $(top_srcdir)/conftools/missing AUTHORS COPYING \ + conftools/compile conftools/config.guess conftools/config.sub \ + conftools/install-sh conftools/ltmain.sh conftools/missing +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +distdir = $(PACKAGE)-$(VERSION) +top_distdir = $(distdir) +am__remove_distdir = \ + if test -d "$(distdir)"; then \ + find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ + && rm -rf "$(distdir)" \ + || { sleep 5 && rm -rf "$(distdir)"; }; \ + else :; fi +am__post_remove_distdir = $(am__remove_distdir) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +GZIP_ENV = --best +DIST_ARCHIVES = $(distdir).tar.bz2 +DIST_TARGETS = dist-bzip2 +distuninstallcheck_listfiles = find . -type f -print +am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ + | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' +distcleancheck_listfiles = find . -type f -print +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ CC = @CC@ -CXX = @CXX@ -LIBTOOL = @LIBTOOL@ - -INCLUDES = -I$(srcdir)/lib -I. -LDFLAGS = @LDFLAGS@ -CPPFLAGS = @CPPFLAGS@ -DHAVE_EXPAT_CONFIG_H +CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ -VSNFLAG = -version-info @LIBCURRENT@:@LIBREVISION@:@LIBAGE@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DOCBOOK_TO_MAN = @DOCBOOK_TO_MAN@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILEMAP = @FILEMAP@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBAGE = @LIBAGE@ +LIBCURRENT = @LIBCURRENT@ +LIBOBJS = @LIBOBJS@ +LIBREVISION = @LIBREVISION@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +VERSION = @VERSION@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +AUTOMAKE_OPTIONS = \ + dist-bzip2 \ + foreign \ + no-dist-gzip \ + subdir-objects -### autoconf this? -LTFLAGS = --verbose +ACLOCAL_AMFLAGS = -I m4 +LIBTOOLFLAGS = --verbose +SUBDIRS = lib examples tests $(am__append_1) +pkgconfig_DATA = expat.pc +pkgconfigdir = $(libdir)/pkgconfig +_EXTRA_DIST_CMAKE = \ + CMakeLists.txt \ + CMake.README \ + ConfigureChecks.cmake \ + expat_config.h.cmake -COMPILE = $(CC) $(INCLUDES) $(CFLAGS) $(DEFS) $(CPPFLAGS) -CXXCOMPILE = $(CXX) $(INCLUDES) $(CXXFLAGS) $(DEFS) $(CPPFLAGS) -LTCOMPILE = $(LIBTOOL) $(LTFLAGS) --mode=compile $(COMPILE) -LINK_LIB = $(LIBTOOL) $(LTFLAGS) --mode=link $(COMPILE) -no-undefined $(VSNFLAG) -rpath $(libdir) $(LDFLAGS) -o $@ -LINK_EXE = $(LIBTOOL) $(LTFLAGS) --mode=link $(COMPILE) $(LDFLAGS) -o $@ -LINK_CXX_EXE = $(LIBTOOL) $(LTFLAGS) --mode=link $(CXXCOMPILE) $(LDFLAGS) -o $@ +_EXTRA_DIST_WINDOWS = \ + examples/elements.vcxproj \ + examples/elements.vcxproj.filters \ + examples/outline.vcxproj \ + examples/outline.vcxproj.filters \ + \ + lib/expat_static.vcxproj \ + lib/expat_static.vcxproj.filters \ + lib/expat.vcxproj \ + lib/expat.vcxproj.filters \ + lib/expatw_static.vcxproj \ + lib/expatw_static.vcxproj.filters \ + lib/expatw.vcxproj \ + lib/expatw.vcxproj.filters \ + \ + tests/benchmark/benchmark.sln \ + tests/benchmark/benchmark.vcxproj \ + \ + tests/runtests.sln \ + tests/runtests.vcxproj \ + tests/runtests.vcxproj.filters \ + \ + win32/expat.iss \ + win32/MANIFEST.txt \ + win32/README.txt \ + \ + xmlwf/xmlwf.vcxproj \ + xmlwf/xmlwf.vcxproj.filters \ + \ + expat.sln -LIB_OBJS = lib/xmlparse.lo lib/xmltok.lo lib/xmlrole.lo -$(LIBRARY): $(LIB_OBJS) - $(LINK_LIB) $(LIB_OBJS) +EXTRA_DIST = \ + $(_EXTRA_DIST_CMAKE) \ + $(_EXTRA_DIST_WINDOWS) \ + \ + conftools/expat.m4 \ + conftools/get-version.sh \ + conftools/PrintPath \ + \ + Changes \ + README.md \ + test-driver-wrapper.sh -expat.pc: $(top_builddir)/config.status +all: expat_config.h + $(MAKE) $(AM_MAKEFLAGS) all-recursive + +.SUFFIXES: +am--refresh: Makefile + @: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ + $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ + && exit 0; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + echo ' $(SHELL) ./config.status'; \ + $(SHELL) ./config.status;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + $(SHELL) ./config.status --recheck + +$(top_srcdir)/configure: $(am__configure_deps) + $(am__cd) $(srcdir) && $(AUTOCONF) +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) +$(am__aclocal_m4_deps): + +expat_config.h: stamp-h1 + @test -f $@ || rm -f stamp-h1 + @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 + +stamp-h1: $(srcdir)/expat_config.h.in $(top_builddir)/config.status + @rm -f stamp-h1 + cd $(top_builddir) && $(SHELL) ./config.status expat_config.h +$(srcdir)/expat_config.h.in: $(am__configure_deps) + ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) + rm -f stamp-h1 + touch $@ + +distclean-hdr: + -rm -f expat_config.h stamp-h1 +expat.pc: $(top_builddir)/config.status $(srcdir)/expat.pc.in + cd $(top_builddir) && $(SHELL) ./config.status $@ +run.sh: $(top_builddir)/config.status $(srcdir)/run.sh.in cd $(top_builddir) && $(SHELL) ./config.status $@ -lib/xmlparse.lo: lib/xmlparse.c lib/expat.h lib/xmlrole.h lib/xmltok.h \ - $(top_builddir)/expat_config.h lib/expat_external.h lib/internal.h +mostlyclean-libtool: + -rm -f *.lo -lib/xmlrole.lo: lib/xmlrole.c lib/ascii.h lib/xmlrole.h \ - $(top_builddir)/expat_config.h lib/expat_external.h lib/internal.h +clean-libtool: + -rm -rf .libs _libs -lib/xmltok.lo: lib/xmltok.c lib/xmltok_impl.c lib/xmltok_ns.c \ - lib/ascii.h lib/asciitab.h lib/iasciitab.h lib/latin1tab.h \ - lib/nametab.h lib/utf8tab.h lib/xmltok.h lib/xmltok_impl.h \ - $(top_builddir)/expat_config.h lib/expat_external.h lib/internal.h +distclean-libtool: + -rm -f libtool config.lt +install-pkgconfigDATA: $(pkgconfig_DATA) + @$(NORMAL_INSTALL) + @list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(pkgconfigdir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pkgconfigdir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(pkgconfigdir)" || exit $$?; \ + done + +uninstall-pkgconfigDATA: + @$(NORMAL_UNINSTALL) + @list='$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pkgconfigdir)'; $(am__uninstall_files_from_dir) + +# This directory's subdirectories are mostly independent; you can cd +# into them and run 'make' without going through this Makefile. +# To change the values of 'make' variables: instead of editing Makefiles, +# (1) if the variable is set in 'config.status', edit 'config.status' +# (which will cause the Makefiles to be regenerated when you run 'make'); +# (2) otherwise, pass the desired values on the 'make' command line. +$(am__recursive_targets): + @fail=; \ + if $(am__make_keepgoing); then \ + failcom='fail=yes'; \ + else \ + failcom='exit 1'; \ + fi; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-recursive +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-recursive + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscope: cscope.files + test ! -s cscope.files \ + || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) +clean-cscope: + -rm -f cscope.files +cscope.files: clean-cscope cscopelist +cscopelist: cscopelist-recursive + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + -rm -f cscope.out cscope.in.out cscope.po.out cscope.files + +distdir: $(DISTFILES) + $(am__remove_distdir) + test -d "$(distdir)" || mkdir "$(distdir)" + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + $(am__make_dryrun) \ + || test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done + -test -n "$(am__skip_mode_fix)" \ + || find "$(distdir)" -type d ! -perm -755 \ + -exec chmod u+rwx,go+rx {} \; -o \ + ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ + ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ + || chmod -R a+r "$(distdir)" +dist-gzip: distdir + tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz + $(am__post_remove_distdir) +dist-bzip2: distdir + tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 + $(am__post_remove_distdir) + +dist-lzip: distdir + tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz + $(am__post_remove_distdir) + +dist-xz: distdir + tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz + $(am__post_remove_distdir) + +dist-tarZ: distdir + @echo WARNING: "Support for distribution archives compressed with" \ + "legacy program 'compress' is deprecated." >&2 + @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 + tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z + $(am__post_remove_distdir) + +dist-shar: distdir + @echo WARNING: "Support for shar distribution archives is" \ + "deprecated." >&2 + @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 + shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz + $(am__post_remove_distdir) + +dist-zip: distdir + -rm -f $(distdir).zip + zip -rq $(distdir).zip $(distdir) + $(am__post_remove_distdir) + +dist dist-all: + $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' + $(am__post_remove_distdir) + +# This target untars the dist file and tries a VPATH configuration. Then +# it guarantees that the distribution is self-contained by making another +# tarfile. +distcheck: dist + case '$(DIST_ARCHIVES)' in \ + *.tar.gz*) \ + eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ + *.tar.bz2*) \ + bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ + *.tar.lz*) \ + lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ + *.tar.xz*) \ + xz -dc $(distdir).tar.xz | $(am__untar) ;;\ + *.tar.Z*) \ + uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ + *.shar.gz*) \ + eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ + *.zip*) \ + unzip $(distdir).zip ;;\ + esac + chmod -R a-w $(distdir) + chmod u+w $(distdir) + mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst + chmod a-w $(distdir) + test -d $(distdir)/_build || exit 0; \ + dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ + && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ + && am__cwd=`pwd` \ + && $(am__cd) $(distdir)/_build/sub \ + && ../../configure \ + $(AM_DISTCHECK_CONFIGURE_FLAGS) \ + $(DISTCHECK_CONFIGURE_FLAGS) \ + --srcdir=../.. --prefix="$$dc_install_base" \ + && $(MAKE) $(AM_MAKEFLAGS) \ + && $(MAKE) $(AM_MAKEFLAGS) dvi \ + && $(MAKE) $(AM_MAKEFLAGS) check \ + && $(MAKE) $(AM_MAKEFLAGS) install \ + && $(MAKE) $(AM_MAKEFLAGS) installcheck \ + && $(MAKE) $(AM_MAKEFLAGS) uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ + distuninstallcheck \ + && chmod -R a-w "$$dc_install_base" \ + && ({ \ + (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ + && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ + distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ + } || { rm -rf "$$dc_destdir"; exit 1; }) \ + && rm -rf "$$dc_destdir" \ + && $(MAKE) $(AM_MAKEFLAGS) dist \ + && rm -rf $(DIST_ARCHIVES) \ + && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ + && cd "$$am__cwd" \ + || exit 1 + $(am__post_remove_distdir) + @(echo "$(distdir) archives ready for distribution: "; \ + list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ + sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' +distuninstallcheck: + @test -n '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: trying to run $@ with an empty' \ + '$$(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + $(am__cd) '$(distuninstallcheck_dir)' || { \ + echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ + exit 1; \ + }; \ + test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left after uninstall:" ; \ + if test -n "$(DESTDIR)"; then \ + echo " (check DESTDIR support)"; \ + fi ; \ + $(distuninstallcheck_listfiles) ; \ + exit 1; } >&2 +distcleancheck: distclean + @if test '$(srcdir)' = . ; then \ + echo "ERROR: distcleancheck can only run from a VPATH build" ; \ + exit 1 ; \ + fi + @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ + || { echo "ERROR: files left in build directory after distclean:" ; \ + $(distcleancheck_listfiles) ; \ + exit 1; } >&2 +check-am: all-am +check: check-recursive +all-am: Makefile $(DATA) expat_config.h +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(pkgconfigdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-hdr \ + distclean-libtool distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-pkgconfigDATA + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f $(am__CONFIG_DISTCLEAN_FILES) + -rm -rf $(top_srcdir)/autom4te.cache + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-pkgconfigDATA + +.MAKE: $(am__recursive_targets) all install-am install-strip + +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ + am--refresh check check-am clean clean-cscope clean-generic \ + clean-libtool cscope cscopelist-am ctags ctags-am dist \ + dist-all dist-bzip2 dist-gzip dist-lzip dist-shar dist-tarZ \ + dist-xz dist-zip distcheck distclean distclean-generic \ + distclean-hdr distclean-libtool distclean-tags distcleancheck \ + distdir distuninstallcheck dvi dvi-am html html-am info \ + info-am install install-am install-data install-data-am \ + install-dvi install-dvi-am install-exec install-exec-am \ + install-html install-html-am install-info install-info-am \ + install-man install-pdf install-pdf-am install-pkgconfigDATA \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-pkgconfigDATA + +.PRECIOUS: Makefile -XMLWF_OBJS = xmlwf/xmlwf.@OBJEXT@ xmlwf/xmlfile.@OBJEXT@ xmlwf/codepage.@OBJEXT@ xmlwf/@FILEMAP@.@OBJEXT@ -xmlwf/xmlwf.@OBJEXT@: xmlwf/xmlwf.c -xmlwf/xmlfile.@OBJEXT@: xmlwf/xmlfile.c -xmlwf/codepage.@OBJEXT@: xmlwf/codepage.c -xmlwf/@FILEMAP@.@OBJEXT@: xmlwf/@FILEMAP@.c -xmlwf/xmlwf@EXEEXT@: $(XMLWF_OBJS) $(LIBRARY) - $(LINK_EXE) $(XMLWF_OBJS) $(LIBRARY) +.PHONY: buildlib +buildlib: + @echo 'ERROR: Running "make buildlib LIBRARY=libexpatw.la"' >&2 + @echo 'ERROR: is no longer supported. INSTEAD please:' >&2 + @echo 'ERROR:' >&2 + @echo 'ERROR: * Mass-patch Makefile.am, e.g.' >&2 + @echo 'ERROR: # find -name Makefile.am -exec sed \' >&2 + @echo 'ERROR: -e "s,libexpat\.la,libexpatw.la," \' >&2 + @echo 'ERROR: -e "s,libexpat_la,libexpatw_la," \' >&2 + @echo 'ERROR: -i {} +' >&2 + @echo 'ERROR:' >&2 + @echo 'ERROR: * Run automake to re-generate Makefile.in files' >&2 + @echo 'ERROR:' >&2 + @echo 'ERROR: * Use "./configure --without-xmlwf" and/or' >&2 + @echo 'ERROR: "make -C lib all install" to bypass compilation' >&2 + @echo 'ERROR: of xmlwf (e.g. with -DXML_UNICODE)' >&2 + @echo 'ERROR:' >&2 + @false -examples/elements.@OBJEXT@: examples/elements.c -examples/elements: examples/elements.@OBJEXT@ $(LIBRARY) - $(LINK_EXE) examples/elements.@OBJEXT@ $(LIBRARY) - -examples/outline.@OBJEXT@: examples/outline.c -examples/outline: examples/outline.@OBJEXT@ $(LIBRARY) - $(LINK_EXE) examples/outline.@OBJEXT@ $(LIBRARY) - -tests/chardata.@OBJEXT@: tests/chardata.c tests/chardata.h -tests/minicheck.@OBJEXT@: tests/minicheck.c tests/minicheck.h -tests/runtests.@OBJEXT@: tests/runtests.c tests/chardata.h -tests/runtests: tests/runtests.@OBJEXT@ tests/chardata.@OBJEXT@ tests/minicheck.@OBJEXT@ $(LIBRARY) - $(LINK_EXE) tests/runtests.@OBJEXT@ tests/chardata.@OBJEXT@ tests/minicheck.@OBJEXT@ $(LIBRARY) -tests/runtestspp.@OBJEXT@: tests/runtestspp.cpp tests/runtests.c tests/chardata.h -tests/runtestspp: tests/runtestspp.@OBJEXT@ tests/chardata.@OBJEXT@ tests/minicheck.@OBJEXT@ $(LIBRARY) - $(LINK_CXX_EXE) tests/runtestspp.@OBJEXT@ tests/chardata.@OBJEXT@ tests/minicheck.@OBJEXT@ $(LIBRARY) - -tests/benchmark/benchmark.@OBJEXT@: tests/benchmark/benchmark.c -tests/benchmark/benchmark: tests/benchmark/benchmark.@OBJEXT@ $(LIBRARY) - $(LINK_EXE) tests/benchmark/benchmark.@OBJEXT@ $(LIBRARY) - -run-benchmark: tests/benchmark/benchmark - tests/benchmark/benchmark@EXEEXT@ -n $(top_srcdir)/../testdata/largefiles/recset.xml 65535 3 +.PHONY: run-benchmark +run-benchmark: + $(MAKE) -C tests/benchmark + ./run.sh tests/benchmark/benchmark@EXEEXT@ -n $(top_srcdir)/../testdata/largefiles/recset.xml 65535 3 tests/xmlts.zip: - wget --output-document=tests/xmlts.zip \ - http://www.w3.org/XML/Test/xmlts20080827.zip + if test "$(XMLTS_ZIP)" = ""; then \ + wget --output-document=tests/xmlts.zip \ + https://www.w3.org/XML/Test/xmlts20080827.zip; \ + else \ + cp $(XMLTS_ZIP) tests/xmlts.zip; \ + fi tests/xmlconf: tests/xmlts.zip cd tests && unzip -q xmlts.zip -run-xmltest: xmlwf/xmlwf@EXEEXT@ tests/xmlconf - tests/xmltest.sh 2>&1 | tee tests/xmltest.log - diff -u tests/xmltest.log.expected tests/xmltest.log +.PHONY: run-xmltest +run-xmltest: tests/xmlconf +@WITH_XMLWF_TRUE@ $(MAKE) -C xmlwf +@WITH_XMLWF_TRUE@ tests/xmltest.sh "$(PWD)/run.sh $(PWD)/xmlwf/xmlwf@EXEEXT@" 2>&1 | tee tests/xmltest.log +@WITH_XMLWF_TRUE@ dos2unix tests/xmltest.log +@WITH_XMLWF_TRUE@ diff -u tests/xmltest.log.expected tests/xmltest.log +@WITH_XMLWF_FALSE@ @echo 'ERROR: xmlwf is needed for "make run-xmltest".' >&2 +@WITH_XMLWF_FALSE@ @echo 'ERROR: Please re-configure without --without-xmlwf.' >&2 +@WITH_XMLWF_FALSE@ @false .PHONY: qa qa: @@ -197,16 +1022,6 @@ qa: ./qa.sh undefined ./qa.sh coverage -.SUFFIXES: .c .cpp .lo .@OBJEXT@ - -.cpp.@OBJEXT@: - $(CXXCOMPILE) -o $@ -c $< -.c.@OBJEXT@: - $(COMPILE) -o $@ -c $< -.c.lo: - $(LTCOMPILE) -o $@ -c $< - -.PHONY: buildlib all \ - clean distclean extraclean maintainer-clean \ - dist distdir \ - install uninstall +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/contrib/expat/README b/contrib/expat/README deleted file mode 100644 index a7d28450d54f..000000000000 --- a/contrib/expat/README +++ /dev/null @@ -1,139 +0,0 @@ - - Expat, Release 2.2.0 - -This is Expat, a C library for parsing XML, written by James Clark. -Expat is a stream-oriented XML parser. This means that you register -handlers with the parser before starting the parse. These handlers -are called when the parser discovers the associated structures in the -document being parsed. A start tag is an example of the kind of -structures for which you may register handlers. - -Windows users should use the expat_win32bin package, which includes -both precompiled libraries and executables, and source code for -developers. - -Expat is free software. You may copy, distribute, and modify it under -the terms of the License contained in the file COPYING distributed -with this package. This license is the same as the MIT/X Consortium -license. - -Versions of Expat that have an odd minor version (the middle number in -the release above), are development releases and should be considered -as beta software. Releases with even minor version numbers are -intended to be production grade software. - -If you are building Expat from a check-out from the CVS repository, -you need to run a script that generates the configure script using the -GNU autoconf and libtool tools. To do this, you need to have -autoconf 2.58 or newer. Run the script like this: - - ./buildconf.sh - -Once this has been done, follow the same instructions as for building -from a source distribution. - -To build Expat from a source distribution, you first run the -configuration shell script in the top level distribution directory: - - ./configure - -There are many options which you may provide to configure (which you -can discover by running configure with the --help option). But the -one of most interest is the one that sets the installation directory. -By default, the configure script will set things up to install -libexpat into /usr/local/lib, expat.h into /usr/local/include, and -xmlwf into /usr/local/bin. If, for example, you'd prefer to install -into /home/me/mystuff/lib, /home/me/mystuff/include, and -/home/me/mystuff/bin, you can tell configure about that with: - - ./configure --prefix=/home/me/mystuff - -Another interesting option is to enable 64-bit integer support for -line and column numbers and the over-all byte index: - - ./configure CPPFLAGS=-DXML_LARGE_SIZE - -However, such a modification would be a breaking change to the ABI -and is therefore not recommended for general use - e.g. as part of -a Linux distribution - but rather for builds with special requirements. - -After running the configure script, the "make" command will build -things and "make install" will install things into their proper -location. Have a look at the "Makefile" to learn about additional -"make" options. Note that you need to have write permission into -the directories into which things will be installed. - -If you are interested in building Expat to provide document -information in UTF-16 encoding rather than the default UTF-8, follow -these instructions (after having run "make distclean"): - - 1. For UTF-16 output as unsigned short (and version/error - strings as char), run: - - ./configure CPPFLAGS=-DXML_UNICODE - - For UTF-16 output as wchar_t (incl. version/error strings), - run: - - ./configure CFLAGS="-g -O2 -fshort-wchar" \ - CPPFLAGS=-DXML_UNICODE_WCHAR_T - - 2. Edit the MakeFile, changing: - - LIBRARY = libexpat.la - - to: - - LIBRARY = libexpatw.la - - (Note the additional "w" in the library name.) - - 3. Run "make buildlib" (which builds the library only). - Or, to save step 2, run "make buildlib LIBRARY=libexpatw.la". - - 4. Run "make installlib" (which installs the library only). - Or, if step 2 was omitted, run "make installlib LIBRARY=libexpatw.la". - -Using DESTDIR or INSTALL_ROOT is enabled, with INSTALL_ROOT being the default -value for DESTDIR, and the rest of the make file using only DESTDIR. -It works as follows: - $ make install DESTDIR=/path/to/image -overrides the in-makefile set DESTDIR, while both - $ INSTALL_ROOT=/path/to/image make install - $ make install INSTALL_ROOT=/path/to/image -use DESTDIR=$(INSTALL_ROOT), even if DESTDIR eventually is defined in the -environment, because variable-setting priority is -1) commandline -2) in-makefile -3) environment - -Note: This only applies to the Expat library itself, building UTF-16 versions -of xmlwf and the tests is currently not supported. - -Note for Solaris users: The "ar" command is usually located in -"/usr/ccs/bin", which is not in the default PATH. You will need to -add this to your path for the "make" command, and probably also switch -to GNU make (the "make" found in /usr/ccs/bin does not seem to work -properly -- apparently it does not understand .PHONY directives). If -you're using ksh or bash, use this command to build: - - PATH=/usr/ccs/bin:$PATH make - -When using Expat with a project using autoconf for configuration, you -can use the probing macro in conftools/expat.m4 to determine how to -include Expat. See the comments at the top of that file for more -information. - -A reference manual is available in the file doc/reference.html in this -distribution. - -The homepage for this project is http://www.libexpat.org/. There -are links there to connect you to the bug reports page. If you need -to report a bug when you don't have access to a browser, you may also -send a bug report by email to expat-bugs@mail.libexpat.org. - -Discussion related to the direction of future expat development takes -place on expat-discuss@mail.libexpat.org. Archives of this list and -other Expat-related lists may be found at: - - http://mail.libexpat.org/mailman/listinfo/ diff --git a/contrib/expat/README.md b/contrib/expat/README.md new file mode 100644 index 000000000000..2c7e6ac40506 --- /dev/null +++ b/contrib/expat/README.md @@ -0,0 +1,126 @@ +[![Travis CI Build Status](https://travis-ci.org/libexpat/libexpat.svg?branch=master)](https://travis-ci.org/libexpat/libexpat) +[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/libexpat/libexpat?svg=true)](https://ci.appveyor.com/project/libexpat/libexpat) + + +# Expat, Release 2.2.6 + +This is Expat, a C library for parsing XML, started by +[James Clark](https://en.wikipedia.org/wiki/James_Clark_(programmer)) in 1997. +Expat is a stream-oriented XML parser. This means that you register +handlers with the parser before starting the parse. These handlers +are called when the parser discovers the associated structures in the +document being parsed. A start tag is an example of the kind of +structures for which you may register handlers. + +Windows users should use the +[`expat_win32` package](https://sourceforge.net/projects/expat/files/expat_win32/), +which includes both precompiled libraries and executables, and source code for +developers. + +Expat is [free software](https://www.gnu.org/philosophy/free-sw.en.html). +You may copy, distribute, and modify it under the terms of the License +contained in the file +[`COPYING`](https://github.com/libexpat/libexpat/blob/master/expat/COPYING) +distributed with this package. +This license is the same as the MIT/X Consortium license. + +If you are building Expat from a check-out from the +[Git repository](https://github.com/libexpat/libexpat/), +you need to run a script that generates the configure script using the +GNU autoconf and libtool tools. To do this, you need to have +autoconf 2.58 or newer. Run the script like this: + +```console +./buildconf.sh +``` + +Once this has been done, follow the same instructions as for building +from a source distribution. + +To build Expat from a source distribution, you first run the +configuration shell script in the top level distribution directory: + +```console +./configure +``` + +There are many options which you may provide to configure (which you +can discover by running configure with the `--help` option). But the +one of most interest is the one that sets the installation directory. +By default, the configure script will set things up to install +libexpat into `/usr/local/lib`, `expat.h` into `/usr/local/include`, and +`xmlwf` into `/usr/local/bin`. If, for example, you'd prefer to install +into `/home/me/mystuff/lib`, `/home/me/mystuff/include`, and +`/home/me/mystuff/bin`, you can tell `configure` about that with: + +```console +./configure --prefix=/home/me/mystuff +``` + +Another interesting option is to enable 64-bit integer support for +line and column numbers and the over-all byte index: + +```console +./configure CPPFLAGS=-DXML_LARGE_SIZE +``` + +However, such a modification would be a breaking change to the ABI +and is therefore not recommended for general use — e.g. as part of +a Linux distribution — but rather for builds with special requirements. + +After running the configure script, the `make` command will build +things and `make install` will install things into their proper +location. Have a look at the `Makefile` to learn about additional +`make` options. Note that you need to have write permission into +the directories into which things will be installed. + +If you are interested in building Expat to provide document +information in UTF-16 encoding rather than the default UTF-8, follow +these instructions (after having run `make distclean`). +Please note that we configure with `--without-xmlwf` as xmlwf does not +support this mode of compilation (yet): + +1. Mass-patch `Makefile.am` files to use `libexpatw.la` for a library name: +
+ `find -name Makefile.am -exec sed + -e 's,libexpat\.la,libexpatw.la,' + -e 's,libexpat_la,libexpatw_la,' + -i {} +` + +1. Run `automake` to re-write `Makefile.in` files:
+ `automake` + +1. For UTF-16 output as unsigned short (and version/error strings as char), + run:
+ `./configure CPPFLAGS=-DXML_UNICODE --without-xmlwf`
+ For UTF-16 output as `wchar_t` (incl. version/error strings), run:
+ `./configure CFLAGS="-g -O2 -fshort-wchar" CPPFLAGS=-DXML_UNICODE_WCHAR_T + --without-xmlwf` +
Note: The latter requires libc compiled with `-fshort-wchar`, as well. + +1. Run `make` (which excludes xmlwf). + +1. Run `make install` (again, excludes xmlwf). + +Using `DESTDIR` is supported. It works as follows: + +```console +make install DESTDIR=/path/to/image +``` + +overrides the in-makefile set `DESTDIR`, because variable-setting priority is + +1. commandline +1. in-makefile +1. environment + +Note: This only applies to the Expat library itself, building UTF-16 versions +of xmlwf and the tests is currently not supported. + +When using Expat with a project using autoconf for configuration, you +can use the probing macro in `conftools/expat.m4` to determine how to +include Expat. See the comments at the top of that file for more +information. + +A reference manual is available in the file `doc/reference.html` in this +distribution. diff --git a/contrib/expat/configure.ac b/contrib/expat/configure.ac index a06c3e49fc25..a68d9a4e3da2 100644 --- a/contrib/expat/configure.ac +++ b/contrib/expat/configure.ac @@ -31,6 +31,7 @@ undefine([expat_version]) AC_CONFIG_SRCDIR(Makefile.in) AC_CONFIG_AUX_DIR(conftools) +AM_INIT_AUTOMAKE AC_CONFIG_MACRO_DIR([m4]) @@ -46,9 +47,10 @@ dnl If the API changes incompatibly set LIBAGE back to 0 dnl LIBCURRENT=7 # sync -LIBREVISION=2 # with +LIBREVISION=8 # with LIBAGE=6 # CMakeLists.txt! +CPPFLAGS="${CPPFLAGS} -DHAVE_EXPAT_CONFIG_H" AC_CONFIG_HEADER(expat_config.h) sinclude(conftools/ac_c_bigendian_cross.m4) @@ -61,7 +63,7 @@ AC_SUBST(LIBREVISION) AC_SUBST(LIBAGE) dnl Checks for programs. -AC_PROG_CC +AC_PROG_CC_C99 AC_PROG_CXX AC_PROG_INSTALL @@ -80,6 +82,10 @@ if test "$GCC" = yes ; then if test "x$CXXFLAGS" = x ; then CXXFLAGS=`echo "$CFLAGS" | sed 's/ -Wmissing-prototypes -Wstrict-prototypes//'` fi + + CFLAGS="${CFLAGS} -fno-strict-aliasing" + CXXFLAGS="${CXXFLAGS} -fno-strict-aliasing" + LDFLAGS="${LDFLAGS} -fno-strict-aliasing" fi dnl Checks for header files. @@ -95,6 +101,96 @@ AC_C_CONST AC_TYPE_SIZE_T AC_CHECK_FUNCS(memmove bcopy) + +AC_ARG_WITH([xmlwf], [ +AS_HELP_STRING([--without-xmlwf], [do not build xmlwf])], [], [with_xmlwf=yes]) +AM_CONDITIONAL([WITH_XMLWF], [test x${with_xmlwf} = xyes]) + +AM_CONDITIONAL([MINGW], [echo -- "${host}" | ${FGREP} mingw >/dev/null]) +AM_CONDITIONAL([UNICODE], [echo -- "${CPPFLAGS}${CFLAGS}" | ${FGREP} XML_UNICODE >/dev/null]) + + +AC_ARG_WITH([libbsd], [ +AS_HELP_STRING([--with-libbsd], [utilize libbsd (for arc4random_buf)]) +], [], [with_libbsd=no]) +AS_IF([test "x${with_libbsd}" != xno], [ + AC_CHECK_LIB([bsd], [arc4random_buf], [], [ + AS_IF([test "x${with_libbsd}" = xyes], [ + AC_MSG_ERROR([Enforced use of libbsd cannot be satisfied.]) + ]) + ]) +]) +AC_MSG_CHECKING([for arc4random_buf (BSD or libbsd)]) +AC_LINK_IFELSE([AC_LANG_SOURCE([ + #include /* for arc4random_buf on BSD, for NULL */ + #if defined(HAVE_LIBBSD) + # include + #endif + int main() { + arc4random_buf(NULL, 0U); + return 0; + } +])], [ + AC_DEFINE([HAVE_ARC4RANDOM_BUF], [1], + [Define to 1 if you have the `arc4random_buf' function.]) + AC_MSG_RESULT([yes]) +], [ + AC_MSG_RESULT([no]) + + AC_MSG_CHECKING([for arc4random (BSD, macOS or libbsd)]) + AC_LINK_IFELSE([AC_LANG_SOURCE([ + #if defined(HAVE_LIBBSD) + # include + #else + # include + #endif + int main() { + arc4random(); + return 0; + } + ])], [ + AC_DEFINE([HAVE_ARC4RANDOM], [1], + [Define to 1 if you have the `arc4random' function.]) + AC_MSG_RESULT([yes]) + ], [ + AC_MSG_RESULT([no]) + ]) +]) + + +AC_MSG_CHECKING([for getrandom (Linux 3.17+, glibc 2.25+)]) +AC_LINK_IFELSE([AC_LANG_SOURCE([ + #include /* for NULL */ + #include + int main() { + return getrandom(NULL, 0U, 0U); + } +])], [ + AC_DEFINE([HAVE_GETRANDOM], [1], + [Define to 1 if you have the `getrandom' function.]) + AC_MSG_RESULT([yes]) +], [ + AC_MSG_RESULT([no]) + + AC_MSG_CHECKING([for syscall SYS_getrandom (Linux 3.17+)]) + AC_LINK_IFELSE([AC_LANG_SOURCE([ + #include /* for NULL */ + #include /* for syscall */ + #include /* for SYS_getrandom */ + int main() { + syscall(SYS_getrandom, NULL, 0, 0); + return 0; + } + ])], [ + AC_DEFINE([HAVE_SYSCALL_GETRANDOM], [1], + [Define to 1 if you have `syscall' and `SYS_getrandom'.]) + AC_MSG_RESULT([yes]) + ], [ + AC_MSG_RESULT([no]) + ]) +]) + + dnl Only needed for xmlwf: AC_CHECK_HEADERS(fcntl.h unistd.h) AC_TYPE_OFF_T @@ -107,51 +203,62 @@ else fi AC_SUBST(FILEMAP) -dnl Needed for the test support code; this was found at -dnl http://lists.gnu.org/archive/html/bug-autoconf/2002-07/msg00028.html - -# AC_CPP_FUNC -# ------------------ # -# Checks to see if ANSI C99 CPP variable __func__ works. -# If not, perhaps __FUNCTION__ works instead. -# If not, we'll just define __func__ to "". -AC_DEFUN([AC_CPP_FUNC], -[AC_REQUIRE([AC_PROG_CC_STDC])dnl -AC_CACHE_CHECK([for an ANSI C99-conforming __func__], ac_cv_cpp_func, -[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], -[[char *foo = __func__;]])], - [ac_cv_cpp_func=yes], - [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], -[[char *foo = __FUNCTION__;]])], - [ac_cv_cpp_func=__FUNCTION__], - [ac_cv_cpp_func=no])])]) -if test $ac_cv_cpp_func = __FUNCTION__; then - AC_DEFINE(__func__,__FUNCTION__, - [Define to __FUNCTION__ or "" if `__func__' does not conform to -ANSI C.]) -elif test $ac_cv_cpp_func = no; then - AC_DEFINE(__func__,"", - [Define to __FUNCTION__ or "" if `__func__' does not conform to -ANSI C.]) -fi -])# AC_CPP_FUNC - -AC_CPP_FUNC - dnl Some basic configuration: AC_DEFINE([XML_NS], 1, [Define to make XML Namespaces functionality available.]) AC_DEFINE([XML_DTD], 1, [Define to make parameter entity parsing functionality available.]) -AC_DEFINE([XML_CONTEXT_BYTES], 1024, - [Define to specify how much context to retain around the current parse point.]) +AC_DEFINE([XML_DEV_URANDOM], 1, + [Define to include code reading entropy from `/dev/urandom'.]) + +AC_ARG_ENABLE([xml-context], + AS_HELP_STRING([--enable-xml-context @<:@COUNT@:>@], + [Retain context around the current parse point; + default is enabled and a size of 1024 bytes]) +AS_HELP_STRING([--disable-xml-context], + [Do not retain context around the current parse point]), + [enable_xml_context=${enableval}]) +AS_IF([test "x${enable_xml_context}" != "xno"], [ + AS_IF([test "x${enable_xml_context}" = "xyes" \ + -o "x${enable_xml_context}" = "x"], [ + enable_xml_context=1024 + ]) + AC_DEFINE_UNQUOTED([XML_CONTEXT_BYTES], [${enable_xml_context}], + [Define to specify how much context to retain around the current parse point.]) +]) + +AC_ARG_WITH([docbook], [AS_HELP_STRING([--with-docbook], + [enforce XML to man page compilation @<:@default=check@:>@]) +AS_HELP_STRING([--without-docbook], + [skip XML to man page compilation @<:@default=check@:>@])], + [], + [with_docbook=check]) + +AC_ARG_VAR([DOCBOOK_TO_MAN], [docbook2x-man command]) +AS_IF([test "x$with_docbook" != xno], + [AC_CHECK_PROGS([DOCBOOK_TO_MAN], [docbook2x-man db2x_docbook2man docbook2man docbook-to-man])]) +AS_IF([test "x${DOCBOOK_TO_MAN}" = x -a "x$with_docbook" = xyes], + [AC_MSG_ERROR([Required program 'docbook2x-man' not found.])]) +AS_IF([test "x${DOCBOOK_TO_MAN}" != x -a "x$with_docbook" != xno], + [AS_IF([${DOCBOOK_TO_MAN} --help | grep -i -q -F sgmlbase], + [AC_MSG_ERROR([Your local ${DOCBOOK_TO_MAN} was found to work with SGML rather + than XML. Please install docbook2X and use variable DOCBOOK_TO_MAN to point + configure to command docbook2x-man of docbook2X. + Or use DOCBOOK_TO_MAN="xmlto man --skip-validation" if you have xmlto around. + You can also configure using --without-docbook if you can do without a man + page for xmlwf.])])]) + +AM_CONDITIONAL(WITH_DOCBOOK, [test "x${DOCBOOK_TO_MAN}" != x]) AC_CONFIG_FILES([Makefile expat.pc]) +AC_CONFIG_FILES([ + doc/Makefile + examples/Makefile + lib/Makefile + tests/Makefile + tests/benchmark/Makefile + xmlwf/Makefile +]) +AC_CONFIG_FILES([run.sh], [chmod +x run.sh]) AC_OUTPUT - -abs_srcdir="`cd $srcdir && pwd`" -abs_builddir="`pwd`" -if test "$abs_srcdir" != "$abs_builddir"; then - make mkdir-init -fi diff --git a/contrib/expat/doc/Makefile.am b/contrib/expat/doc/Makefile.am new file mode 100644 index 000000000000..d8a35c0da235 --- /dev/null +++ b/contrib/expat/doc/Makefile.am @@ -0,0 +1,56 @@ +# +# __ __ _ +# ___\ \/ /_ __ __ _| |_ +# / _ \\ /| '_ \ / _` | __| +# | __// \| |_) | (_| | |_ +# \___/_/\_\ .__/ \__,_|\__| +# |_| XML parser +# +# Copyright (c) 2017 Expat development team +# Licensed under the MIT license: +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the +# following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +# USE OR OTHER DEALINGS IN THE SOFTWARE. + +dist_man_MANS = xmlwf.1 + +xmlwf.1: xmlwf.xml +if WITH_DOCBOOK + -rm -f $@ + $(DOCBOOK_TO_MAN) $< + test -f $@ || mv XMLWF.1 $@ +else + @echo 'ERROR: Configure with --with-docbook for "make dist".' 1>&2 + @false +endif + +# https://www.gnu.org/software/automake/manual/automake.html#What-Gets-Cleaned +.PHONY: clean-local +clean-local: clean-local-check + +.PHONY: clean-local-check +clean-local-check: + $(RM) xmlwf.1 + +EXTRA_DIST = \ + expat.png \ + reference.html \ + style.css \ + valid-xhtml10.png \ + xmlwf.xml diff --git a/contrib/expat/doc/Makefile.in b/contrib/expat/doc/Makefile.in new file mode 100644 index 000000000000..6a206e84add9 --- /dev/null +++ b/contrib/expat/doc/Makefile.in @@ -0,0 +1,579 @@ +# Makefile.in generated by automake 1.15.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2017 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# +# __ __ _ +# ___\ \/ /_ __ __ _| |_ +# / _ \\ /| '_ \ / _` | __| +# | __// \| |_) | (_| | |_ +# \___/_/\_\ .__/ \__,_|\__| +# |_| XML parser +# +# Copyright (c) 2017 Expat development team +# Licensed under the MIT license: +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the +# following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +# USE OR OTHER DEALINGS IN THE SOFTWARE. +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = doc +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/conftools/ac_c_bigendian_cross.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/expat_config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +man1dir = $(mandir)/man1 +am__installdirs = "$(DESTDIR)$(man1dir)" +NROFF = nroff +MANS = $(dist_man_MANS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +am__DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DOCBOOK_TO_MAN = @DOCBOOK_TO_MAN@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FILEMAP = @FILEMAP@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBAGE = @LIBAGE@ +LIBCURRENT = @LIBCURRENT@ +LIBOBJS = @LIBOBJS@ +LIBREVISION = @LIBREVISION@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +VERSION = @VERSION@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +dist_man_MANS = xmlwf.1 +EXTRA_DIST = \ + expat.png \ + reference.html \ + style.css \ + valid-xhtml10.png \ + xmlwf.xml + +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu doc/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-man1: $(dist_man_MANS) + @$(NORMAL_INSTALL) + @list1=''; \ + list2='$(dist_man_MANS)'; \ + test -n "$(man1dir)" \ + && test -n "`echo $$list1$$list2`" \ + || exit 0; \ + echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ + { for i in $$list1; do echo "$$i"; done; \ + if test -n "$$list2"; then \ + for i in $$list2; do echo "$$i"; done \ + | sed -n '/\.1[a-z]*$$/p'; \ + fi; \ + } | while read p; do \ + if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; echo "$$p"; \ + done | \ + sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ + sed 'N;N;s,\n, ,g' | { \ + list=; while read file base inst; do \ + if test "$$base" = "$$inst"; then list="$$list $$file"; else \ + echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ + $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ + fi; \ + done; \ + for i in $$list; do echo "$$i"; done | $(am__base_list) | \ + while read files; do \ + test -z "$$files" || { \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ + done; } + +uninstall-man1: + @$(NORMAL_UNINSTALL) + @list=''; test -n "$(man1dir)" || exit 0; \ + files=`{ for i in $$list; do echo "$$i"; done; \ + l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ + sed -n '/\.1[a-z]*$$/p'; \ + } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ + -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ + dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) +tags TAGS: + +ctags CTAGS: + +cscope cscopelist: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(MANS) +installdirs: + for dir in "$(DESTDIR)$(man1dir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-local mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-man + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: install-man1 + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-man + +uninstall-man: uninstall-man1 + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + clean-local cscopelist-am ctags-am distclean distclean-generic \ + distclean-libtool distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-man1 install-pdf install-pdf-am install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ + ps ps-am tags-am uninstall uninstall-am uninstall-man \ + uninstall-man1 + +.PRECIOUS: Makefile + + +xmlwf.1: xmlwf.xml +@WITH_DOCBOOK_TRUE@ -rm -f $@ +@WITH_DOCBOOK_TRUE@ $(DOCBOOK_TO_MAN) $< +@WITH_DOCBOOK_TRUE@ test -f $@ || mv XMLWF.1 $@ +@WITH_DOCBOOK_FALSE@ @echo 'ERROR: Configure with --with-docbook for "make dist".' 1>&2 +@WITH_DOCBOOK_FALSE@ @false + +# https://www.gnu.org/software/automake/manual/automake.html#What-Gets-Cleaned +.PHONY: clean-local +clean-local: clean-local-check + +.PHONY: clean-local-check +clean-local-check: + $(RM) xmlwf.1 + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/contrib/expat/doc/reference.html b/contrib/expat/doc/reference.html index a4ab40530aa4..efc19f485f1e 100644 --- a/contrib/expat/doc/reference.html +++ b/contrib/expat/doc/reference.html @@ -31,7 +31,7 @@ the underlying XML parser for the open source Mozilla project, Perl's other open-source XML parsers.

This library is the creation of James Clark, who's also given us -groff (an nroff look-alike), Jade (an implemention of ISO's DSSSL +groff (an nroff look-alike), Jade (an implementation of ISO's DSSSL stylesheet language for SGML), XP (a Java XML parser package), XT (a Java XSL engine). James was also the technical lead on the XML Working Group at W3C that produced the XML specification.

@@ -277,7 +277,7 @@ directions or Unix directions below.

If you're using the GNU compiler under cygwin, follow the Unix directions in the next section. Otherwise if you have Microsoft's Developer Studio installed, then from Windows Explorer double-click on -"expat.dsp" in the lib directory and build and install in the usual +"expat.vcxproj" in the lib directory and build and install in the usual manner.

Alternatively, you may download the Win32 binary package that @@ -360,7 +360,7 @@ off by default.

The number of input bytes of markup context which the parser will ensure are available for reporting via XML_GetInputContext. This is -normally set to 1024, and must be set to a positive interger. If this +normally set to 1024, and must be set to a positive integer. If this is not defined, the input context will not be available and XML_GetInputContext will always report NULL. Without this, Expat has a smaller memory @@ -373,7 +373,7 @@ the right MSVC magic annotations correct. This is ignored on other platforms.
XML_ATTR_INFO
-
If defined, makes the the additional function If defined, makes the additional function XML_GetAttributeInfo available for reporting attribute byte offsets.
@@ -739,7 +739,7 @@ arguments:

XML_PARAM_ENTITY_PARSING_NEVER
Don't parse parameter entities or the external subset
XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE
-
Parse parameter entites and the external subset unless +
Parse parameter entities and the external subset unless standalone was set to "yes" in the XML declaration.
XML_PARAM_ENTITY_PARSING_ALWAYS
Always parse parameter entities and the external subset
@@ -767,7 +767,7 @@ include

  • Stopping parsing completely (simply free or reset the parser instead of resuming in the outer parsing loop). This can be useful - if a application-domain error is found in the XML being parsed or if + if an application-domain error is found in the XML being parsed or if the result of the parse is determined not to be useful after all.
  • @@ -1564,7 +1564,7 @@ at most once per parsed (external) entity. The optional application data pointer encodingHandlerData will be passed back to the handler.

    -

    The map array contains information for every possible possible leading +

    The map array contains information for every possible leading byte in a byte sequence. If the corresponding value is >= 0, then it's a single byte sequence and the byte encodes that Unicode value. If the value is -1, then that byte is invalid as the initial byte in a sequence. @@ -1999,7 +1999,7 @@ return NULL.

    Miscellaneous functions

    The functions in this section either obtain state information from -the parser or can be used to dynamicly set parser options.

    +the parser or can be used to dynamically set parser options.

     void XMLCALL
    diff --git a/contrib/expat/doc/xmlwf.1 b/contrib/expat/doc/xmlwf.1
    index 06bb84cf3d79..57230689ef23 100644
    --- a/contrib/expat/doc/xmlwf.1
    +++ b/contrib/expat/doc/xmlwf.1
    @@ -15,7 +15,7 @@ xmlwf \- Determines if an XML document is well-formed
     \fBxmlwf\fR \kx
     .if (\nx>(\n(.l/2)) .nr x (\n(.l/5)
     'in \n(.iu+\nxu
    -[\fB-s\fR] [\fB-n\fR] [\fB-p\fR] [\fB-x\fR] [\fB-e \fIencoding\fB\fR] [\fB-w\fR] [\fB-d \fIoutput-dir\fB\fR] [\fB-c\fR] [\fB-m\fR] [\fB-r\fR] [\fB-t\fR] [\fB-v\fR] [file ...]
    +[\fB-s\fR] [\fB-n\fR] [\fB-p\fR] [\fB-x\fR] [\fB-e \fIencoding\fB\fR] [\fB-w\fR] [\fB-d \fIoutput-dir\fB\fR] [\fB-c\fR] [\fB-m\fR] [\fB-r\fR] [\fB-t\fR] [\fB-N\fR] [\fB-v\fR] [file ...]
     'in \n(.iu-\nxu
     .ad b
     'hy
    @@ -71,15 +71,15 @@ If the input file is well-formed and \fBxmlwf\fR
     doesn't encounter any errors, the input file is simply copied to
     the output directory unchanged.
     This implies no namespaces (turns off \*(T<\fB\-n\fR\*(T>) and
    -requires \*(T<\fB\-d\fR\*(T> to specify an output file.
    +requires \*(T<\fB\-d\fR\*(T> to specify an output directory.
     .TP 
     \*(T<\fB\-d output\-dir\fR\*(T>
     Specifies a directory to contain transformed
     representations of the input files.
     By default, \*(T<\fB\-d\fR\*(T> outputs a canonical representation
     (described below).
    -You can select different output formats using \*(T<\fB\-c\fR\*(T>
    -and \*(T<\fB\-m\fR\*(T>.
    +You can select different output formats using \*(T<\fB\-c\fR\*(T>,
    +\*(T<\fB\-m\fR\*(T> and \*(T<\fB\-N\fR\*(T>.
     
     The output filenames will
     be exactly the same as the input filenames or "STDIN" if the input is
    @@ -115,6 +115,11 @@ Requires \*(T<\fB\-d\fR\*(T> to specify an output file.
     Turns on namespace processing. (describe namespaces)
     \*(T<\fB\-c\fR\*(T> disables namespaces.
     .TP 
    +\*(T<\fB\-N\fR\*(T>
    +Adds a doctype and notation declarations to canonical XML output.
    +This matches the example output used by the formal XML test cases.
    +Requires \*(T<\fB\-d\fR\*(T> to specify an output file.
    +.TP 
     \*(T<\fB\-p\fR\*(T>
     Tells xmlwf to process external DTDs and parameter
     entities.
    diff --git a/contrib/expat/doc/xmlwf.xml b/contrib/expat/doc/xmlwf.xml
    index 92ea8b592964..5e2a4ae94ab3 100644
    --- a/contrib/expat/doc/xmlwf.xml
    +++ b/contrib/expat/doc/xmlwf.xml
    @@ -58,6 +58,7 @@
     
     	  
     	  
    +          
     
     	  
     
    @@ -146,7 +147,7 @@ supports both.
       doesn't encounter any errors, the input file is simply copied to
       the output directory unchanged.
       This implies no namespaces (turns off ) and
    -  requires  to specify an output file.
    +  requires  to specify an output directory.
       		
             
           
    @@ -159,8 +160,8 @@ supports both.
       representations of the input files.
       By default,  outputs a canonical representation
       (described below).
    -  You can select different output formats using 
    -  and .
    +  You can select different output formats using ,
    +   and .
     	  
     	  
       The output filenames will
    @@ -219,6 +220,17 @@ supports both.
             
           
     
    +      
    +        
    +        
    +          
    +  Adds a doctype and notation declarations to canonical XML output.
    +  This matches the example output used by the formal XML test cases.
    +  Requires  to specify an output file.
    +          
    +        
    +      
    +
           
             
             
    diff --git a/contrib/expat/examples/Makefile.am b/contrib/expat/examples/Makefile.am
    new file mode 100644
    index 000000000000..99edf21227c9
    --- /dev/null
    +++ b/contrib/expat/examples/Makefile.am
    @@ -0,0 +1,39 @@
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +AM_CPPFLAGS = -I$(srcdir)/../lib
    +
    +noinst_PROGRAMS = elements outline
    +
    +elements_SOURCES = elements.c
    +elements_LDADD = ../lib/libexpat.la
    +
    +outline_SOURCES = outline.c
    +outline_LDADD = ../lib/libexpat.la
    diff --git a/contrib/expat/examples/Makefile.in b/contrib/expat/examples/Makefile.in
    new file mode 100644
    index 000000000000..d995eae88c8a
    --- /dev/null
    +++ b/contrib/expat/examples/Makefile.in
    @@ -0,0 +1,636 @@
    +# Makefile.in generated by automake 1.15.1 from Makefile.am.
    +# @configure_input@
    +
    +# Copyright (C) 1994-2017 Free Software Foundation, Inc.
    +
    +# This Makefile.in is free software; the Free Software Foundation
    +# gives unlimited permission to copy and/or distribute it,
    +# with or without modifications, as long as this notice is preserved.
    +
    +# This program is distributed in the hope that it will be useful,
    +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
    +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
    +# PARTICULAR PURPOSE.
    +
    +@SET_MAKE@
    +
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +VPATH = @srcdir@
    +am__is_gnu_make = { \
    +  if test -z '$(MAKELEVEL)'; then \
    +    false; \
    +  elif test -n '$(MAKE_HOST)'; then \
    +    true; \
    +  elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
    +    true; \
    +  else \
    +    false; \
    +  fi; \
    +}
    +am__make_running_with_option = \
    +  case $${target_option-} in \
    +      ?) ;; \
    +      *) echo "am__make_running_with_option: internal error: invalid" \
    +              "target option '$${target_option-}' specified" >&2; \
    +         exit 1;; \
    +  esac; \
    +  has_opt=no; \
    +  sane_makeflags=$$MAKEFLAGS; \
    +  if $(am__is_gnu_make); then \
    +    sane_makeflags=$$MFLAGS; \
    +  else \
    +    case $$MAKEFLAGS in \
    +      *\\[\ \	]*) \
    +        bs=\\; \
    +        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
    +          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
    +    esac; \
    +  fi; \
    +  skip_next=no; \
    +  strip_trailopt () \
    +  { \
    +    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
    +  }; \
    +  for flg in $$sane_makeflags; do \
    +    test $$skip_next = yes && { skip_next=no; continue; }; \
    +    case $$flg in \
    +      *=*|--*) continue;; \
    +        -*I) strip_trailopt 'I'; skip_next=yes;; \
    +      -*I?*) strip_trailopt 'I';; \
    +        -*O) strip_trailopt 'O'; skip_next=yes;; \
    +      -*O?*) strip_trailopt 'O';; \
    +        -*l) strip_trailopt 'l'; skip_next=yes;; \
    +      -*l?*) strip_trailopt 'l';; \
    +      -[dEDm]) skip_next=yes;; \
    +      -[JT]) skip_next=yes;; \
    +    esac; \
    +    case $$flg in \
    +      *$$target_option*) has_opt=yes; break;; \
    +    esac; \
    +  done; \
    +  test $$has_opt = yes
    +am__make_dryrun = (target_option=n; $(am__make_running_with_option))
    +am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
    +pkgdatadir = $(datadir)/@PACKAGE@
    +pkgincludedir = $(includedir)/@PACKAGE@
    +pkglibdir = $(libdir)/@PACKAGE@
    +pkglibexecdir = $(libexecdir)/@PACKAGE@
    +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
    +install_sh_DATA = $(install_sh) -c -m 644
    +install_sh_PROGRAM = $(install_sh) -c
    +install_sh_SCRIPT = $(install_sh) -c
    +INSTALL_HEADER = $(INSTALL_DATA)
    +transform = $(program_transform_name)
    +NORMAL_INSTALL = :
    +PRE_INSTALL = :
    +POST_INSTALL = :
    +NORMAL_UNINSTALL = :
    +PRE_UNINSTALL = :
    +POST_UNINSTALL = :
    +build_triplet = @build@
    +host_triplet = @host@
    +noinst_PROGRAMS = elements$(EXEEXT) outline$(EXEEXT)
    +subdir = examples
    +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
    +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
    +	$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
    +	$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
    +	$(top_srcdir)/conftools/ac_c_bigendian_cross.m4 \
    +	$(top_srcdir)/configure.ac
    +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
    +	$(ACLOCAL_M4)
    +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON)
    +mkinstalldirs = $(install_sh) -d
    +CONFIG_HEADER = $(top_builddir)/expat_config.h
    +CONFIG_CLEAN_FILES =
    +CONFIG_CLEAN_VPATH_FILES =
    +PROGRAMS = $(noinst_PROGRAMS)
    +am_elements_OBJECTS = elements.$(OBJEXT)
    +elements_OBJECTS = $(am_elements_OBJECTS)
    +elements_DEPENDENCIES = ../lib/libexpat.la
    +AM_V_lt = $(am__v_lt_@AM_V@)
    +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
    +am__v_lt_0 = --silent
    +am__v_lt_1 = 
    +am_outline_OBJECTS = outline.$(OBJEXT)
    +outline_OBJECTS = $(am_outline_OBJECTS)
    +outline_DEPENDENCIES = ../lib/libexpat.la
    +AM_V_P = $(am__v_P_@AM_V@)
    +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
    +am__v_P_0 = false
    +am__v_P_1 = :
    +AM_V_GEN = $(am__v_GEN_@AM_V@)
    +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
    +am__v_GEN_0 = @echo "  GEN     " $@;
    +am__v_GEN_1 = 
    +AM_V_at = $(am__v_at_@AM_V@)
    +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
    +am__v_at_0 = @
    +am__v_at_1 = 
    +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
    +depcomp = $(SHELL) $(top_srcdir)/conftools/depcomp
    +am__depfiles_maybe = depfiles
    +am__mv = mv -f
    +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
    +	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
    +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
    +	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
    +	$(AM_CFLAGS) $(CFLAGS)
    +AM_V_CC = $(am__v_CC_@AM_V@)
    +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
    +am__v_CC_0 = @echo "  CC      " $@;
    +am__v_CC_1 = 
    +CCLD = $(CC)
    +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
    +	$(AM_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_CCLD = $(am__v_CCLD_@AM_V@)
    +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
    +am__v_CCLD_0 = @echo "  CCLD    " $@;
    +am__v_CCLD_1 = 
    +SOURCES = $(elements_SOURCES) $(outline_SOURCES)
    +DIST_SOURCES = $(elements_SOURCES) $(outline_SOURCES)
    +am__can_run_installinfo = \
    +  case $$AM_UPDATE_INFO_DIR in \
    +    n|no|NO) false;; \
    +    *) (install-info --version) >/dev/null 2>&1;; \
    +  esac
    +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
    +# Read a list of newline-separated strings from the standard input,
    +# and print each of them once, without duplicates.  Input order is
    +# *not* preserved.
    +am__uniquify_input = $(AWK) '\
    +  BEGIN { nonempty = 0; } \
    +  { items[$$0] = 1; nonempty = 1; } \
    +  END { if (nonempty) { for (i in items) print i; }; } \
    +'
    +# Make sure the list of sources is unique.  This is necessary because,
    +# e.g., the same source file might be shared among _SOURCES variables
    +# for different programs/libraries.
    +am__define_uniq_tagged_files = \
    +  list='$(am__tagged_files)'; \
    +  unique=`for i in $$list; do \
    +    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
    +  done | $(am__uniquify_input)`
    +ETAGS = etags
    +CTAGS = ctags
    +am__DIST_COMMON = $(srcdir)/Makefile.in \
    +	$(top_srcdir)/conftools/depcomp
    +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
    +ACLOCAL = @ACLOCAL@
    +AMTAR = @AMTAR@
    +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
    +AR = @AR@
    +AS = @AS@
    +AUTOCONF = @AUTOCONF@
    +AUTOHEADER = @AUTOHEADER@
    +AUTOMAKE = @AUTOMAKE@
    +AWK = @AWK@
    +CC = @CC@
    +CCDEPMODE = @CCDEPMODE@
    +CFLAGS = @CFLAGS@
    +CPP = @CPP@
    +CPPFLAGS = @CPPFLAGS@
    +CXX = @CXX@
    +CXXCPP = @CXXCPP@
    +CXXDEPMODE = @CXXDEPMODE@
    +CXXFLAGS = @CXXFLAGS@
    +CYGPATH_W = @CYGPATH_W@
    +DEFS = @DEFS@
    +DEPDIR = @DEPDIR@
    +DLLTOOL = @DLLTOOL@
    +DOCBOOK_TO_MAN = @DOCBOOK_TO_MAN@
    +DSYMUTIL = @DSYMUTIL@
    +DUMPBIN = @DUMPBIN@
    +ECHO_C = @ECHO_C@
    +ECHO_N = @ECHO_N@
    +ECHO_T = @ECHO_T@
    +EGREP = @EGREP@
    +EXEEXT = @EXEEXT@
    +FGREP = @FGREP@
    +FILEMAP = @FILEMAP@
    +GREP = @GREP@
    +INSTALL = @INSTALL@
    +INSTALL_DATA = @INSTALL_DATA@
    +INSTALL_PROGRAM = @INSTALL_PROGRAM@
    +INSTALL_SCRIPT = @INSTALL_SCRIPT@
    +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
    +LD = @LD@
    +LDFLAGS = @LDFLAGS@
    +LIBAGE = @LIBAGE@
    +LIBCURRENT = @LIBCURRENT@
    +LIBOBJS = @LIBOBJS@
    +LIBREVISION = @LIBREVISION@
    +LIBS = @LIBS@
    +LIBTOOL = @LIBTOOL@
    +LIPO = @LIPO@
    +LN_S = @LN_S@
    +LTLIBOBJS = @LTLIBOBJS@
    +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
    +MAKEINFO = @MAKEINFO@
    +MANIFEST_TOOL = @MANIFEST_TOOL@
    +MKDIR_P = @MKDIR_P@
    +NM = @NM@
    +NMEDIT = @NMEDIT@
    +OBJDUMP = @OBJDUMP@
    +OBJEXT = @OBJEXT@
    +OTOOL = @OTOOL@
    +OTOOL64 = @OTOOL64@
    +PACKAGE = @PACKAGE@
    +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
    +PACKAGE_NAME = @PACKAGE_NAME@
    +PACKAGE_STRING = @PACKAGE_STRING@
    +PACKAGE_TARNAME = @PACKAGE_TARNAME@
    +PACKAGE_URL = @PACKAGE_URL@
    +PACKAGE_VERSION = @PACKAGE_VERSION@
    +PATH_SEPARATOR = @PATH_SEPARATOR@
    +RANLIB = @RANLIB@
    +SED = @SED@
    +SET_MAKE = @SET_MAKE@
    +SHELL = @SHELL@
    +STRIP = @STRIP@
    +VERSION = @VERSION@
    +abs_builddir = @abs_builddir@
    +abs_srcdir = @abs_srcdir@
    +abs_top_builddir = @abs_top_builddir@
    +abs_top_srcdir = @abs_top_srcdir@
    +ac_ct_AR = @ac_ct_AR@
    +ac_ct_CC = @ac_ct_CC@
    +ac_ct_CXX = @ac_ct_CXX@
    +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
    +am__include = @am__include@
    +am__leading_dot = @am__leading_dot@
    +am__quote = @am__quote@
    +am__tar = @am__tar@
    +am__untar = @am__untar@
    +bindir = @bindir@
    +build = @build@
    +build_alias = @build_alias@
    +build_cpu = @build_cpu@
    +build_os = @build_os@
    +build_vendor = @build_vendor@
    +builddir = @builddir@
    +datadir = @datadir@
    +datarootdir = @datarootdir@
    +docdir = @docdir@
    +dvidir = @dvidir@
    +exec_prefix = @exec_prefix@
    +host = @host@
    +host_alias = @host_alias@
    +host_cpu = @host_cpu@
    +host_os = @host_os@
    +host_vendor = @host_vendor@
    +htmldir = @htmldir@
    +includedir = @includedir@
    +infodir = @infodir@
    +install_sh = @install_sh@
    +libdir = @libdir@
    +libexecdir = @libexecdir@
    +localedir = @localedir@
    +localstatedir = @localstatedir@
    +mandir = @mandir@
    +mkdir_p = @mkdir_p@
    +oldincludedir = @oldincludedir@
    +pdfdir = @pdfdir@
    +prefix = @prefix@
    +program_transform_name = @program_transform_name@
    +psdir = @psdir@
    +sbindir = @sbindir@
    +sharedstatedir = @sharedstatedir@
    +srcdir = @srcdir@
    +sysconfdir = @sysconfdir@
    +target_alias = @target_alias@
    +top_build_prefix = @top_build_prefix@
    +top_builddir = @top_builddir@
    +top_srcdir = @top_srcdir@
    +AM_CPPFLAGS = -I$(srcdir)/../lib
    +elements_SOURCES = elements.c
    +elements_LDADD = ../lib/libexpat.la
    +outline_SOURCES = outline.c
    +outline_LDADD = ../lib/libexpat.la
    +all: all-am
    +
    +.SUFFIXES:
    +.SUFFIXES: .c .lo .o .obj
    +$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
    +	@for dep in $?; do \
    +	  case '$(am__configure_deps)' in \
    +	    *$$dep*) \
    +	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
    +	        && { if test -f $@; then exit 0; else break; fi; }; \
    +	      exit 1;; \
    +	  esac; \
    +	done; \
    +	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu examples/Makefile'; \
    +	$(am__cd) $(top_srcdir) && \
    +	  $(AUTOMAKE) --gnu examples/Makefile
    +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
    +	@case '$?' in \
    +	  *config.status*) \
    +	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
    +	  *) \
    +	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
    +	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
    +	esac;
    +
    +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +
    +$(top_srcdir)/configure:  $(am__configure_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(am__aclocal_m4_deps):
    +
    +clean-noinstPROGRAMS:
    +	@list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list || exit $$?; \
    +	test -n "$(EXEEXT)" || exit 0; \
    +	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list
    +
    +elements$(EXEEXT): $(elements_OBJECTS) $(elements_DEPENDENCIES) $(EXTRA_elements_DEPENDENCIES) 
    +	@rm -f elements$(EXEEXT)
    +	$(AM_V_CCLD)$(LINK) $(elements_OBJECTS) $(elements_LDADD) $(LIBS)
    +
    +outline$(EXEEXT): $(outline_OBJECTS) $(outline_DEPENDENCIES) $(EXTRA_outline_DEPENDENCIES) 
    +	@rm -f outline$(EXEEXT)
    +	$(AM_V_CCLD)$(LINK) $(outline_OBJECTS) $(outline_LDADD) $(LIBS)
    +
    +mostlyclean-compile:
    +	-rm -f *.$(OBJEXT)
    +
    +distclean-compile:
    +	-rm -f *.tab.c
    +
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/elements.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/outline.Po@am__quote@
    +
    +.c.o:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
    +
    +.c.obj:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
    +
    +.c.lo:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
    +
    +mostlyclean-libtool:
    +	-rm -f *.lo
    +
    +clean-libtool:
    +	-rm -rf .libs _libs
    +
    +ID: $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); mkid -fID $$unique
    +tags: tags-am
    +TAGS: tags
    +
    +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	set x; \
    +	here=`pwd`; \
    +	$(am__define_uniq_tagged_files); \
    +	shift; \
    +	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
    +	  test -n "$$unique" || unique=$$empty_fix; \
    +	  if test $$# -gt 0; then \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      "$$@" $$unique; \
    +	  else \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      $$unique; \
    +	  fi; \
    +	fi
    +ctags: ctags-am
    +
    +CTAGS: ctags
    +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); \
    +	test -z "$(CTAGS_ARGS)$$unique" \
    +	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
    +	     $$unique
    +
    +GTAGS:
    +	here=`$(am__cd) $(top_builddir) && pwd` \
    +	  && $(am__cd) $(top_srcdir) \
    +	  && gtags -i $(GTAGS_ARGS) "$$here"
    +cscopelist: cscopelist-am
    +
    +cscopelist-am: $(am__tagged_files)
    +	list='$(am__tagged_files)'; \
    +	case "$(srcdir)" in \
    +	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
    +	  *) sdir=$(subdir)/$(srcdir) ;; \
    +	esac; \
    +	for i in $$list; do \
    +	  if test -f "$$i"; then \
    +	    echo "$(subdir)/$$i"; \
    +	  else \
    +	    echo "$$sdir/$$i"; \
    +	  fi; \
    +	done >> $(top_builddir)/cscope.files
    +
    +distclean-tags:
    +	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
    +
    +distdir: $(DISTFILES)
    +	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	list='$(DISTFILES)'; \
    +	  dist_files=`for file in $$list; do echo $$file; done | \
    +	  sed -e "s|^$$srcdirstrip/||;t" \
    +	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
    +	case $$dist_files in \
    +	  */*) $(MKDIR_P) `echo "$$dist_files" | \
    +			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
    +			   sort -u` ;; \
    +	esac; \
    +	for file in $$dist_files; do \
    +	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
    +	  if test -d $$d/$$file; then \
    +	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
    +	    if test -d "$(distdir)/$$file"; then \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
    +	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
    +	  else \
    +	    test -f "$(distdir)/$$file" \
    +	    || cp -p $$d/$$file "$(distdir)/$$file" \
    +	    || exit 1; \
    +	  fi; \
    +	done
    +check-am: all-am
    +check: check-am
    +all-am: Makefile $(PROGRAMS)
    +installdirs:
    +install: install-am
    +install-exec: install-exec-am
    +install-data: install-data-am
    +uninstall: uninstall-am
    +
    +install-am: all-am
    +	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
    +
    +installcheck: installcheck-am
    +install-strip:
    +	if test -z '$(STRIP)'; then \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	      install; \
    +	else \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
    +	fi
    +mostlyclean-generic:
    +
    +clean-generic:
    +
    +distclean-generic:
    +	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
    +	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
    +
    +maintainer-clean-generic:
    +	@echo "This command is intended for maintainers to use"
    +	@echo "it deletes files that may require special tools to rebuild."
    +clean: clean-am
    +
    +clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \
    +	mostlyclean-am
    +
    +distclean: distclean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +distclean-am: clean-am distclean-compile distclean-generic \
    +	distclean-tags
    +
    +dvi: dvi-am
    +
    +dvi-am:
    +
    +html: html-am
    +
    +html-am:
    +
    +info: info-am
    +
    +info-am:
    +
    +install-data-am:
    +
    +install-dvi: install-dvi-am
    +
    +install-dvi-am:
    +
    +install-exec-am:
    +
    +install-html: install-html-am
    +
    +install-html-am:
    +
    +install-info: install-info-am
    +
    +install-info-am:
    +
    +install-man:
    +
    +install-pdf: install-pdf-am
    +
    +install-pdf-am:
    +
    +install-ps: install-ps-am
    +
    +install-ps-am:
    +
    +installcheck-am:
    +
    +maintainer-clean: maintainer-clean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +maintainer-clean-am: distclean-am maintainer-clean-generic
    +
    +mostlyclean: mostlyclean-am
    +
    +mostlyclean-am: mostlyclean-compile mostlyclean-generic \
    +	mostlyclean-libtool
    +
    +pdf: pdf-am
    +
    +pdf-am:
    +
    +ps: ps-am
    +
    +ps-am:
    +
    +uninstall-am:
    +
    +.MAKE: install-am install-strip
    +
    +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \
    +	clean-libtool clean-noinstPROGRAMS cscopelist-am ctags \
    +	ctags-am distclean distclean-compile distclean-generic \
    +	distclean-libtool distclean-tags distdir dvi dvi-am html \
    +	html-am info info-am install install-am install-data \
    +	install-data-am install-dvi install-dvi-am install-exec \
    +	install-exec-am install-html install-html-am install-info \
    +	install-info-am install-man install-pdf install-pdf-am \
    +	install-ps install-ps-am install-strip installcheck \
    +	installcheck-am installdirs maintainer-clean \
    +	maintainer-clean-generic mostlyclean mostlyclean-compile \
    +	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
    +	tags tags-am uninstall uninstall-am
    +
    +.PRECIOUS: Makefile
    +
    +
    +# Tell versions [3.59,3.63) of GNU make to not export all variables.
    +# Otherwise a system limit (for SysV at least) may be exceeded.
    +.NOEXPORT:
    diff --git a/contrib/expat/examples/elements.c b/contrib/expat/examples/elements.c
    index 0ca1abd98a39..9d2027e449c7 100644
    --- a/contrib/expat/examples/elements.c
    +++ b/contrib/expat/examples/elements.c
    @@ -3,27 +3,59 @@
        the name of each element to standard output indenting child
        elements by one tab stop more than their parent element.
        It must be used with Expat compiled for UTF-8 output.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #include 
    -#include "expat.h"
    -
    -#if defined(__amigaos__) && defined(__USE_INLINE__)
    -#include 
    -#endif
    +#include 
     
     #ifdef XML_LARGE_SIZE
    -#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
    -#define XML_FMT_INT_MOD "I64"
    +# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
    +#  define XML_FMT_INT_MOD "I64"
    +# else
    +#  define XML_FMT_INT_MOD "ll"
    +# endif
     #else
    -#define XML_FMT_INT_MOD "ll"
    +# define XML_FMT_INT_MOD "l"
     #endif
    +
    +#ifdef XML_UNICODE_WCHAR_T
    +# include 
    +# define XML_FMT_STR "ls"
     #else
    -#define XML_FMT_INT_MOD "l"
    +# define XML_FMT_STR "s"
     #endif
     
     static void XMLCALL
    -startElement(void *userData, const char *name, const char **atts)
    +startElement(void *userData, const XML_Char *name, const XML_Char **atts)
     {
       int i;
       int *depthPtr = (int *)userData;
    @@ -31,12 +63,12 @@ startElement(void *userData, const char *name, const char **atts)
     
       for (i = 0; i < *depthPtr; i++)
         putchar('\t');
    -  puts(name);
    +  printf("%" XML_FMT_STR "\n", name);
       *depthPtr += 1;
     }
     
     static void XMLCALL
    -endElement(void *userData, const char *name)
    +endElement(void *userData, const XML_Char *name)
     {
       int *depthPtr = (int *)userData;
       (void)name;
    @@ -59,9 +91,9 @@ main(int argc, char *argv[])
       do {
         size_t len = fread(buf, 1, sizeof(buf), stdin);
         done = len < sizeof(buf);
    -    if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
    +    if (XML_Parse(parser, buf, (int)len, done) == XML_STATUS_ERROR) {
           fprintf(stderr,
    -              "%s at line %" XML_FMT_INT_MOD "u\n",
    +              "%" XML_FMT_STR " at line %" XML_FMT_INT_MOD "u\n",
                   XML_ErrorString(XML_GetErrorCode(parser)),
                   XML_GetCurrentLineNumber(parser));
           return 1;
    diff --git a/contrib/expat/examples/outline.c b/contrib/expat/examples/outline.c
    index d9b091761cd4..3e0bbaa498c8 100644
    --- a/contrib/expat/examples/outline.c
    +++ b/contrib/expat/examples/outline.c
    @@ -1,42 +1,54 @@
    -/*****************************************************************
    - * outline.c
    - *
    - * Copyright 1999, Clark Cooper
    - * All rights reserved.
    - *
    - * This program is free software; you can redistribute it and/or
    - * modify it under the terms of the license contained in the
    - * COPYING file that comes with the expat distribution.
    - *
    - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    - *
    - * Read an XML document from standard input and print an element
    - * outline on standard output.
    - * Must be used with Expat compiled for UTF-8 output.
    - */
    +/* Read an XML document from standard input and print an element
    +   outline on standard output.
    +   Must be used with Expat compiled for UTF-8 output.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
     
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
     
     #include 
     #include 
     
    -#if defined(__amigaos__) && defined(__USE_INLINE__)
    -#include 
    +#ifdef XML_LARGE_SIZE
    +# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
    +#  define XML_FMT_INT_MOD "I64"
    +# else
    +#  define XML_FMT_INT_MOD "ll"
    +# endif
    +#else
    +# define XML_FMT_INT_MOD "l"
     #endif
     
    -#ifdef XML_LARGE_SIZE
    -#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
    -#define XML_FMT_INT_MOD "I64"
    +#ifdef XML_UNICODE_WCHAR_T
    +# define XML_FMT_STR "ls"
     #else
    -#define XML_FMT_INT_MOD "ll"
    -#endif
    -#else
    -#define XML_FMT_INT_MOD "l"
    +# define XML_FMT_STR "s"
     #endif
     
     #define BUFFSIZE        8192
    @@ -46,7 +58,7 @@ char Buff[BUFFSIZE];
     int Depth;
     
     static void XMLCALL
    -start(void *data, const char *el, const char **attr)
    +start(void *data, const XML_Char *el, const XML_Char **attr)
     {
       int i;
       (void)data;
    @@ -54,10 +66,10 @@ start(void *data, const char *el, const char **attr)
       for (i = 0; i < Depth; i++)
         printf("  ");
     
    -  printf("%s", el);
    +  printf("%" XML_FMT_STR, el);
     
       for (i = 0; attr[i]; i += 2) {
    -    printf(" %s='%s'", attr[i], attr[i + 1]);
    +    printf(" %" XML_FMT_STR "='%" XML_FMT_STR "'", attr[i], attr[i + 1]);
       }
     
       printf("\n");
    @@ -65,7 +77,7 @@ start(void *data, const char *el, const char **attr)
     }
     
     static void XMLCALL
    -end(void *data, const char *el)
    +end(void *data, const XML_Char *el)
     {
       (void)data;
       (void)el;
    @@ -99,7 +111,8 @@ main(int argc, char *argv[])
         done = feof(stdin);
     
         if (XML_Parse(p, Buff, len, done) == XML_STATUS_ERROR) {
    -      fprintf(stderr, "Parse error at line %" XML_FMT_INT_MOD "u:\n%s\n",
    +      fprintf(stderr,
    +              "Parse error at line %" XML_FMT_INT_MOD "u:\n%" XML_FMT_STR "\n",
                   XML_GetCurrentLineNumber(p),
                   XML_ErrorString(XML_GetErrorCode(p)));
           exit(-1);
    diff --git a/contrib/expat/expat_config.h.in b/contrib/expat/expat_config.h.in
    index 0777a7f9bda1..63c0d03eb83d 100644
    --- a/contrib/expat/expat_config.h.in
    +++ b/contrib/expat/expat_config.h.in
    @@ -3,6 +3,12 @@
     /* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */
     #undef BYTEORDER
     
    +/* Define to 1 if you have the `arc4random' function. */
    +#undef HAVE_ARC4RANDOM
    +
    +/* Define to 1 if you have the `arc4random_buf' function. */
    +#undef HAVE_ARC4RANDOM_BUF
    +
     /* Define to 1 if you have the `bcopy' function. */
     #undef HAVE_BCOPY
     
    @@ -15,9 +21,15 @@
     /* Define to 1 if you have the `getpagesize' function. */
     #undef HAVE_GETPAGESIZE
     
    +/* Define to 1 if you have the `getrandom' function. */
    +#undef HAVE_GETRANDOM
    +
     /* Define to 1 if you have the  header file. */
     #undef HAVE_INTTYPES_H
     
    +/* Define to 1 if you have the `bsd' library (-lbsd). */
    +#undef HAVE_LIBBSD
    +
     /* Define to 1 if you have the `memmove' function. */
     #undef HAVE_MEMMOVE
     
    @@ -39,6 +51,9 @@
     /* Define to 1 if you have the  header file. */
     #undef HAVE_STRING_H
     
    +/* Define to 1 if you have `syscall' and `SYS_getrandom'. */
    +#undef HAVE_SYSCALL_GETRANDOM
    +
     /* Define to 1 if you have the  header file. */
     #undef HAVE_SYS_PARAM_H
     
    @@ -54,6 +69,9 @@
     /* Define to the sub-directory where libtool stores uninstalled libraries. */
     #undef LT_OBJDIR
     
    +/* Name of package */
    +#undef PACKAGE
    +
     /* Define to the address where bug reports for this package should be sent. */
     #undef PACKAGE_BUGREPORT
     
    @@ -75,6 +93,9 @@
     /* Define to 1 if you have the ANSI C header files. */
     #undef STDC_HEADERS
     
    +/* Version number of package */
    +#undef VERSION
    +
     /* whether byteorder is bigendian */
     #undef WORDS_BIGENDIAN
     
    @@ -82,15 +103,15 @@
        point. */
     #undef XML_CONTEXT_BYTES
     
    +/* Define to include code reading entropy from `/dev/urandom'. */
    +#undef XML_DEV_URANDOM
    +
     /* Define to make parameter entity parsing functionality available. */
     #undef XML_DTD
     
     /* Define to make XML Namespaces functionality available. */
     #undef XML_NS
     
    -/* Define to __FUNCTION__ or "" if `__func__' does not conform to ANSI C. */
    -#undef __func__
    -
     /* Define to empty if `const' does not conform to ANSI C. */
     #undef const
     
    diff --git a/contrib/expat/lib/Makefile.am b/contrib/expat/lib/Makefile.am
    new file mode 100644
    index 000000000000..534369e8af20
    --- /dev/null
    +++ b/contrib/expat/lib/Makefile.am
    @@ -0,0 +1,76 @@
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +include_HEADERS = \
    +    ../expat_config.h \
    +    expat.h \
    +    expat_external.h
    +
    +lib_LTLIBRARIES = libexpat.la
    +
    +libexpat_la_LDFLAGS = \
    +    -no-undefined \
    +    -version-info @LIBCURRENT@:@LIBREVISION@:@LIBAGE@
    +
    +libexpat_la_SOURCES = \
    +    loadlibrary.c \
    +    xmlparse.c \
    +    xmltok.c \
    +    xmlrole.c
    +
    +doc_DATA = \
    +    ../AUTHORS \
    +    ../Changes
    +
    +install-data-hook:
    +	cd "$(DESTDIR)$(docdir)" && $(am__mv) Changes changelog
    +
    +uninstall-local:
    +	$(RM) "$(DESTDIR)$(docdir)/changelog"
    +
    +EXTRA_DIST = \
    +    ascii.h \
    +    asciitab.h \
    +    expat_external.h \
    +    expat.h \
    +    iasciitab.h \
    +    internal.h \
    +    latin1tab.h \
    +    libexpat.def \
    +    libexpatw.def \
    +    nametab.h \
    +    siphash.h \
    +    utf8tab.h \
    +    winconfig.h \
    +    xmlrole.h \
    +    xmltok.h \
    +    xmltok_impl.c \
    +    xmltok_impl.h \
    +    xmltok_ns.c
    diff --git a/contrib/expat/lib/Makefile.in b/contrib/expat/lib/Makefile.in
    new file mode 100644
    index 000000000000..91b27b3da63f
    --- /dev/null
    +++ b/contrib/expat/lib/Makefile.in
    @@ -0,0 +1,784 @@
    +# Makefile.in generated by automake 1.15.1 from Makefile.am.
    +# @configure_input@
    +
    +# Copyright (C) 1994-2017 Free Software Foundation, Inc.
    +
    +# This Makefile.in is free software; the Free Software Foundation
    +# gives unlimited permission to copy and/or distribute it,
    +# with or without modifications, as long as this notice is preserved.
    +
    +# This program is distributed in the hope that it will be useful,
    +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
    +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
    +# PARTICULAR PURPOSE.
    +
    +@SET_MAKE@
    +
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +
    +
    +VPATH = @srcdir@
    +am__is_gnu_make = { \
    +  if test -z '$(MAKELEVEL)'; then \
    +    false; \
    +  elif test -n '$(MAKE_HOST)'; then \
    +    true; \
    +  elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
    +    true; \
    +  else \
    +    false; \
    +  fi; \
    +}
    +am__make_running_with_option = \
    +  case $${target_option-} in \
    +      ?) ;; \
    +      *) echo "am__make_running_with_option: internal error: invalid" \
    +              "target option '$${target_option-}' specified" >&2; \
    +         exit 1;; \
    +  esac; \
    +  has_opt=no; \
    +  sane_makeflags=$$MAKEFLAGS; \
    +  if $(am__is_gnu_make); then \
    +    sane_makeflags=$$MFLAGS; \
    +  else \
    +    case $$MAKEFLAGS in \
    +      *\\[\ \	]*) \
    +        bs=\\; \
    +        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
    +          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
    +    esac; \
    +  fi; \
    +  skip_next=no; \
    +  strip_trailopt () \
    +  { \
    +    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
    +  }; \
    +  for flg in $$sane_makeflags; do \
    +    test $$skip_next = yes && { skip_next=no; continue; }; \
    +    case $$flg in \
    +      *=*|--*) continue;; \
    +        -*I) strip_trailopt 'I'; skip_next=yes;; \
    +      -*I?*) strip_trailopt 'I';; \
    +        -*O) strip_trailopt 'O'; skip_next=yes;; \
    +      -*O?*) strip_trailopt 'O';; \
    +        -*l) strip_trailopt 'l'; skip_next=yes;; \
    +      -*l?*) strip_trailopt 'l';; \
    +      -[dEDm]) skip_next=yes;; \
    +      -[JT]) skip_next=yes;; \
    +    esac; \
    +    case $$flg in \
    +      *$$target_option*) has_opt=yes; break;; \
    +    esac; \
    +  done; \
    +  test $$has_opt = yes
    +am__make_dryrun = (target_option=n; $(am__make_running_with_option))
    +am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
    +pkgdatadir = $(datadir)/@PACKAGE@
    +pkgincludedir = $(includedir)/@PACKAGE@
    +pkglibdir = $(libdir)/@PACKAGE@
    +pkglibexecdir = $(libexecdir)/@PACKAGE@
    +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
    +install_sh_DATA = $(install_sh) -c -m 644
    +install_sh_PROGRAM = $(install_sh) -c
    +install_sh_SCRIPT = $(install_sh) -c
    +INSTALL_HEADER = $(INSTALL_DATA)
    +transform = $(program_transform_name)
    +NORMAL_INSTALL = :
    +PRE_INSTALL = :
    +POST_INSTALL = :
    +NORMAL_UNINSTALL = :
    +PRE_UNINSTALL = :
    +POST_UNINSTALL = :
    +build_triplet = @build@
    +host_triplet = @host@
    +subdir = lib
    +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
    +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
    +	$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
    +	$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
    +	$(top_srcdir)/conftools/ac_c_bigendian_cross.m4 \
    +	$(top_srcdir)/configure.ac
    +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
    +	$(ACLOCAL_M4)
    +DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \
    +	$(am__DIST_COMMON)
    +mkinstalldirs = $(install_sh) -d
    +CONFIG_HEADER = $(top_builddir)/expat_config.h
    +CONFIG_CLEAN_FILES =
    +CONFIG_CLEAN_VPATH_FILES =
    +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
    +am__vpath_adj = case $$p in \
    +    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
    +    *) f=$$p;; \
    +  esac;
    +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
    +am__install_max = 40
    +am__nobase_strip_setup = \
    +  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
    +am__nobase_strip = \
    +  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
    +am__nobase_list = $(am__nobase_strip_setup); \
    +  for p in $$list; do echo "$$p $$p"; done | \
    +  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
    +  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
    +    if (++n[$$2] == $(am__install_max)) \
    +      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
    +    END { for (dir in files) print dir, files[dir] }'
    +am__base_list = \
    +  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
    +  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
    +am__uninstall_files_from_dir = { \
    +  test -z "$$files" \
    +    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
    +    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
    +         $(am__cd) "$$dir" && rm -f $$files; }; \
    +  }
    +am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(docdir)" \
    +	"$(DESTDIR)$(includedir)"
    +LTLIBRARIES = $(lib_LTLIBRARIES)
    +libexpat_la_LIBADD =
    +am_libexpat_la_OBJECTS = loadlibrary.lo xmlparse.lo xmltok.lo \
    +	xmlrole.lo
    +libexpat_la_OBJECTS = $(am_libexpat_la_OBJECTS)
    +AM_V_lt = $(am__v_lt_@AM_V@)
    +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
    +am__v_lt_0 = --silent
    +am__v_lt_1 = 
    +libexpat_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
    +	$(libexpat_la_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_P = $(am__v_P_@AM_V@)
    +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
    +am__v_P_0 = false
    +am__v_P_1 = :
    +AM_V_GEN = $(am__v_GEN_@AM_V@)
    +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
    +am__v_GEN_0 = @echo "  GEN     " $@;
    +am__v_GEN_1 = 
    +AM_V_at = $(am__v_at_@AM_V@)
    +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
    +am__v_at_0 = @
    +am__v_at_1 = 
    +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
    +depcomp = $(SHELL) $(top_srcdir)/conftools/depcomp
    +am__depfiles_maybe = depfiles
    +am__mv = mv -f
    +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
    +	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
    +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
    +	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
    +	$(AM_CFLAGS) $(CFLAGS)
    +AM_V_CC = $(am__v_CC_@AM_V@)
    +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
    +am__v_CC_0 = @echo "  CC      " $@;
    +am__v_CC_1 = 
    +CCLD = $(CC)
    +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
    +	$(AM_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_CCLD = $(am__v_CCLD_@AM_V@)
    +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
    +am__v_CCLD_0 = @echo "  CCLD    " $@;
    +am__v_CCLD_1 = 
    +SOURCES = $(libexpat_la_SOURCES)
    +DIST_SOURCES = $(libexpat_la_SOURCES)
    +am__can_run_installinfo = \
    +  case $$AM_UPDATE_INFO_DIR in \
    +    n|no|NO) false;; \
    +    *) (install-info --version) >/dev/null 2>&1;; \
    +  esac
    +DATA = $(doc_DATA)
    +HEADERS = $(include_HEADERS)
    +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
    +# Read a list of newline-separated strings from the standard input,
    +# and print each of them once, without duplicates.  Input order is
    +# *not* preserved.
    +am__uniquify_input = $(AWK) '\
    +  BEGIN { nonempty = 0; } \
    +  { items[$$0] = 1; nonempty = 1; } \
    +  END { if (nonempty) { for (i in items) print i; }; } \
    +'
    +# Make sure the list of sources is unique.  This is necessary because,
    +# e.g., the same source file might be shared among _SOURCES variables
    +# for different programs/libraries.
    +am__define_uniq_tagged_files = \
    +  list='$(am__tagged_files)'; \
    +  unique=`for i in $$list; do \
    +    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
    +  done | $(am__uniquify_input)`
    +ETAGS = etags
    +CTAGS = ctags
    +am__DIST_COMMON = $(srcdir)/Makefile.in \
    +	$(top_srcdir)/conftools/depcomp
    +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
    +ACLOCAL = @ACLOCAL@
    +AMTAR = @AMTAR@
    +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
    +AR = @AR@
    +AS = @AS@
    +AUTOCONF = @AUTOCONF@
    +AUTOHEADER = @AUTOHEADER@
    +AUTOMAKE = @AUTOMAKE@
    +AWK = @AWK@
    +CC = @CC@
    +CCDEPMODE = @CCDEPMODE@
    +CFLAGS = @CFLAGS@
    +CPP = @CPP@
    +CPPFLAGS = @CPPFLAGS@
    +CXX = @CXX@
    +CXXCPP = @CXXCPP@
    +CXXDEPMODE = @CXXDEPMODE@
    +CXXFLAGS = @CXXFLAGS@
    +CYGPATH_W = @CYGPATH_W@
    +DEFS = @DEFS@
    +DEPDIR = @DEPDIR@
    +DLLTOOL = @DLLTOOL@
    +DOCBOOK_TO_MAN = @DOCBOOK_TO_MAN@
    +DSYMUTIL = @DSYMUTIL@
    +DUMPBIN = @DUMPBIN@
    +ECHO_C = @ECHO_C@
    +ECHO_N = @ECHO_N@
    +ECHO_T = @ECHO_T@
    +EGREP = @EGREP@
    +EXEEXT = @EXEEXT@
    +FGREP = @FGREP@
    +FILEMAP = @FILEMAP@
    +GREP = @GREP@
    +INSTALL = @INSTALL@
    +INSTALL_DATA = @INSTALL_DATA@
    +INSTALL_PROGRAM = @INSTALL_PROGRAM@
    +INSTALL_SCRIPT = @INSTALL_SCRIPT@
    +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
    +LD = @LD@
    +LDFLAGS = @LDFLAGS@
    +LIBAGE = @LIBAGE@
    +LIBCURRENT = @LIBCURRENT@
    +LIBOBJS = @LIBOBJS@
    +LIBREVISION = @LIBREVISION@
    +LIBS = @LIBS@
    +LIBTOOL = @LIBTOOL@
    +LIPO = @LIPO@
    +LN_S = @LN_S@
    +LTLIBOBJS = @LTLIBOBJS@
    +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
    +MAKEINFO = @MAKEINFO@
    +MANIFEST_TOOL = @MANIFEST_TOOL@
    +MKDIR_P = @MKDIR_P@
    +NM = @NM@
    +NMEDIT = @NMEDIT@
    +OBJDUMP = @OBJDUMP@
    +OBJEXT = @OBJEXT@
    +OTOOL = @OTOOL@
    +OTOOL64 = @OTOOL64@
    +PACKAGE = @PACKAGE@
    +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
    +PACKAGE_NAME = @PACKAGE_NAME@
    +PACKAGE_STRING = @PACKAGE_STRING@
    +PACKAGE_TARNAME = @PACKAGE_TARNAME@
    +PACKAGE_URL = @PACKAGE_URL@
    +PACKAGE_VERSION = @PACKAGE_VERSION@
    +PATH_SEPARATOR = @PATH_SEPARATOR@
    +RANLIB = @RANLIB@
    +SED = @SED@
    +SET_MAKE = @SET_MAKE@
    +SHELL = @SHELL@
    +STRIP = @STRIP@
    +VERSION = @VERSION@
    +abs_builddir = @abs_builddir@
    +abs_srcdir = @abs_srcdir@
    +abs_top_builddir = @abs_top_builddir@
    +abs_top_srcdir = @abs_top_srcdir@
    +ac_ct_AR = @ac_ct_AR@
    +ac_ct_CC = @ac_ct_CC@
    +ac_ct_CXX = @ac_ct_CXX@
    +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
    +am__include = @am__include@
    +am__leading_dot = @am__leading_dot@
    +am__quote = @am__quote@
    +am__tar = @am__tar@
    +am__untar = @am__untar@
    +bindir = @bindir@
    +build = @build@
    +build_alias = @build_alias@
    +build_cpu = @build_cpu@
    +build_os = @build_os@
    +build_vendor = @build_vendor@
    +builddir = @builddir@
    +datadir = @datadir@
    +datarootdir = @datarootdir@
    +docdir = @docdir@
    +dvidir = @dvidir@
    +exec_prefix = @exec_prefix@
    +host = @host@
    +host_alias = @host_alias@
    +host_cpu = @host_cpu@
    +host_os = @host_os@
    +host_vendor = @host_vendor@
    +htmldir = @htmldir@
    +includedir = @includedir@
    +infodir = @infodir@
    +install_sh = @install_sh@
    +libdir = @libdir@
    +libexecdir = @libexecdir@
    +localedir = @localedir@
    +localstatedir = @localstatedir@
    +mandir = @mandir@
    +mkdir_p = @mkdir_p@
    +oldincludedir = @oldincludedir@
    +pdfdir = @pdfdir@
    +prefix = @prefix@
    +program_transform_name = @program_transform_name@
    +psdir = @psdir@
    +sbindir = @sbindir@
    +sharedstatedir = @sharedstatedir@
    +srcdir = @srcdir@
    +sysconfdir = @sysconfdir@
    +target_alias = @target_alias@
    +top_build_prefix = @top_build_prefix@
    +top_builddir = @top_builddir@
    +top_srcdir = @top_srcdir@
    +include_HEADERS = \
    +    ../expat_config.h \
    +    expat.h \
    +    expat_external.h
    +
    +lib_LTLIBRARIES = libexpat.la
    +libexpat_la_LDFLAGS = \
    +    -no-undefined \
    +    -version-info @LIBCURRENT@:@LIBREVISION@:@LIBAGE@
    +
    +libexpat_la_SOURCES = \
    +    loadlibrary.c \
    +    xmlparse.c \
    +    xmltok.c \
    +    xmlrole.c
    +
    +doc_DATA = \
    +    ../AUTHORS \
    +    ../Changes
    +
    +EXTRA_DIST = \
    +    ascii.h \
    +    asciitab.h \
    +    expat_external.h \
    +    expat.h \
    +    iasciitab.h \
    +    internal.h \
    +    latin1tab.h \
    +    libexpat.def \
    +    libexpatw.def \
    +    nametab.h \
    +    siphash.h \
    +    utf8tab.h \
    +    winconfig.h \
    +    xmlrole.h \
    +    xmltok.h \
    +    xmltok_impl.c \
    +    xmltok_impl.h \
    +    xmltok_ns.c
    +
    +all: all-am
    +
    +.SUFFIXES:
    +.SUFFIXES: .c .lo .o .obj
    +$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
    +	@for dep in $?; do \
    +	  case '$(am__configure_deps)' in \
    +	    *$$dep*) \
    +	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
    +	        && { if test -f $@; then exit 0; else break; fi; }; \
    +	      exit 1;; \
    +	  esac; \
    +	done; \
    +	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu lib/Makefile'; \
    +	$(am__cd) $(top_srcdir) && \
    +	  $(AUTOMAKE) --gnu lib/Makefile
    +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
    +	@case '$?' in \
    +	  *config.status*) \
    +	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
    +	  *) \
    +	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
    +	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
    +	esac;
    +
    +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +
    +$(top_srcdir)/configure:  $(am__configure_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(am__aclocal_m4_deps):
    +
    +install-libLTLIBRARIES: $(lib_LTLIBRARIES)
    +	@$(NORMAL_INSTALL)
    +	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
    +	list2=; for p in $$list; do \
    +	  if test -f $$p; then \
    +	    list2="$$list2 $$p"; \
    +	  else :; fi; \
    +	done; \
    +	test -z "$$list2" || { \
    +	  echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \
    +	  $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \
    +	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
    +	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
    +	}
    +
    +uninstall-libLTLIBRARIES:
    +	@$(NORMAL_UNINSTALL)
    +	@list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \
    +	for p in $$list; do \
    +	  $(am__strip_dir) \
    +	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \
    +	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \
    +	done
    +
    +clean-libLTLIBRARIES:
    +	-test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES)
    +	@list='$(lib_LTLIBRARIES)'; \
    +	locs=`for p in $$list; do echo $$p; done | \
    +	      sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \
    +	      sort -u`; \
    +	test -z "$$locs" || { \
    +	  echo rm -f $${locs}; \
    +	  rm -f $${locs}; \
    +	}
    +
    +libexpat.la: $(libexpat_la_OBJECTS) $(libexpat_la_DEPENDENCIES) $(EXTRA_libexpat_la_DEPENDENCIES) 
    +	$(AM_V_CCLD)$(libexpat_la_LINK) -rpath $(libdir) $(libexpat_la_OBJECTS) $(libexpat_la_LIBADD) $(LIBS)
    +
    +mostlyclean-compile:
    +	-rm -f *.$(OBJEXT)
    +
    +distclean-compile:
    +	-rm -f *.tab.c
    +
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/loadlibrary.Plo@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmlparse.Plo@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmlrole.Plo@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmltok.Plo@am__quote@
    +
    +.c.o:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
    +
    +.c.obj:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
    +
    +.c.lo:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
    +
    +mostlyclean-libtool:
    +	-rm -f *.lo
    +
    +clean-libtool:
    +	-rm -rf .libs _libs
    +install-docDATA: $(doc_DATA)
    +	@$(NORMAL_INSTALL)
    +	@list='$(doc_DATA)'; test -n "$(docdir)" || list=; \
    +	if test -n "$$list"; then \
    +	  echo " $(MKDIR_P) '$(DESTDIR)$(docdir)'"; \
    +	  $(MKDIR_P) "$(DESTDIR)$(docdir)" || exit 1; \
    +	fi; \
    +	for p in $$list; do \
    +	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
    +	  echo "$$d$$p"; \
    +	done | $(am__base_list) | \
    +	while read files; do \
    +	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(docdir)'"; \
    +	  $(INSTALL_DATA) $$files "$(DESTDIR)$(docdir)" || exit $$?; \
    +	done
    +
    +uninstall-docDATA:
    +	@$(NORMAL_UNINSTALL)
    +	@list='$(doc_DATA)'; test -n "$(docdir)" || list=; \
    +	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
    +	dir='$(DESTDIR)$(docdir)'; $(am__uninstall_files_from_dir)
    +install-includeHEADERS: $(include_HEADERS)
    +	@$(NORMAL_INSTALL)
    +	@list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
    +	if test -n "$$list"; then \
    +	  echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \
    +	  $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \
    +	fi; \
    +	for p in $$list; do \
    +	  if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
    +	  echo "$$d$$p"; \
    +	done | $(am__base_list) | \
    +	while read files; do \
    +	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
    +	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
    +	done
    +
    +uninstall-includeHEADERS:
    +	@$(NORMAL_UNINSTALL)
    +	@list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \
    +	files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
    +	dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir)
    +
    +ID: $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); mkid -fID $$unique
    +tags: tags-am
    +TAGS: tags
    +
    +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	set x; \
    +	here=`pwd`; \
    +	$(am__define_uniq_tagged_files); \
    +	shift; \
    +	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
    +	  test -n "$$unique" || unique=$$empty_fix; \
    +	  if test $$# -gt 0; then \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      "$$@" $$unique; \
    +	  else \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      $$unique; \
    +	  fi; \
    +	fi
    +ctags: ctags-am
    +
    +CTAGS: ctags
    +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); \
    +	test -z "$(CTAGS_ARGS)$$unique" \
    +	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
    +	     $$unique
    +
    +GTAGS:
    +	here=`$(am__cd) $(top_builddir) && pwd` \
    +	  && $(am__cd) $(top_srcdir) \
    +	  && gtags -i $(GTAGS_ARGS) "$$here"
    +cscopelist: cscopelist-am
    +
    +cscopelist-am: $(am__tagged_files)
    +	list='$(am__tagged_files)'; \
    +	case "$(srcdir)" in \
    +	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
    +	  *) sdir=$(subdir)/$(srcdir) ;; \
    +	esac; \
    +	for i in $$list; do \
    +	  if test -f "$$i"; then \
    +	    echo "$(subdir)/$$i"; \
    +	  else \
    +	    echo "$$sdir/$$i"; \
    +	  fi; \
    +	done >> $(top_builddir)/cscope.files
    +
    +distclean-tags:
    +	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
    +
    +distdir: $(DISTFILES)
    +	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	list='$(DISTFILES)'; \
    +	  dist_files=`for file in $$list; do echo $$file; done | \
    +	  sed -e "s|^$$srcdirstrip/||;t" \
    +	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
    +	case $$dist_files in \
    +	  */*) $(MKDIR_P) `echo "$$dist_files" | \
    +			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
    +			   sort -u` ;; \
    +	esac; \
    +	for file in $$dist_files; do \
    +	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
    +	  if test -d $$d/$$file; then \
    +	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
    +	    if test -d "$(distdir)/$$file"; then \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
    +	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
    +	  else \
    +	    test -f "$(distdir)/$$file" \
    +	    || cp -p $$d/$$file "$(distdir)/$$file" \
    +	    || exit 1; \
    +	  fi; \
    +	done
    +check-am: all-am
    +check: check-am
    +all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS)
    +installdirs:
    +	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(docdir)" "$(DESTDIR)$(includedir)"; do \
    +	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
    +	done
    +install: install-am
    +install-exec: install-exec-am
    +install-data: install-data-am
    +uninstall: uninstall-am
    +
    +install-am: all-am
    +	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
    +
    +installcheck: installcheck-am
    +install-strip:
    +	if test -z '$(STRIP)'; then \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	      install; \
    +	else \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
    +	fi
    +mostlyclean-generic:
    +
    +clean-generic:
    +
    +distclean-generic:
    +	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
    +	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
    +
    +maintainer-clean-generic:
    +	@echo "This command is intended for maintainers to use"
    +	@echo "it deletes files that may require special tools to rebuild."
    +clean: clean-am
    +
    +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \
    +	mostlyclean-am
    +
    +distclean: distclean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +distclean-am: clean-am distclean-compile distclean-generic \
    +	distclean-tags
    +
    +dvi: dvi-am
    +
    +dvi-am:
    +
    +html: html-am
    +
    +html-am:
    +
    +info: info-am
    +
    +info-am:
    +
    +install-data-am: install-docDATA install-includeHEADERS
    +	@$(NORMAL_INSTALL)
    +	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
    +install-dvi: install-dvi-am
    +
    +install-dvi-am:
    +
    +install-exec-am: install-libLTLIBRARIES
    +
    +install-html: install-html-am
    +
    +install-html-am:
    +
    +install-info: install-info-am
    +
    +install-info-am:
    +
    +install-man:
    +
    +install-pdf: install-pdf-am
    +
    +install-pdf-am:
    +
    +install-ps: install-ps-am
    +
    +install-ps-am:
    +
    +installcheck-am:
    +
    +maintainer-clean: maintainer-clean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +maintainer-clean-am: distclean-am maintainer-clean-generic
    +
    +mostlyclean: mostlyclean-am
    +
    +mostlyclean-am: mostlyclean-compile mostlyclean-generic \
    +	mostlyclean-libtool
    +
    +pdf: pdf-am
    +
    +pdf-am:
    +
    +ps: ps-am
    +
    +ps-am:
    +
    +uninstall-am: uninstall-docDATA uninstall-includeHEADERS \
    +	uninstall-libLTLIBRARIES uninstall-local
    +
    +.MAKE: install-am install-data-am install-strip
    +
    +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \
    +	clean-libLTLIBRARIES clean-libtool cscopelist-am ctags \
    +	ctags-am distclean distclean-compile distclean-generic \
    +	distclean-libtool distclean-tags distdir dvi dvi-am html \
    +	html-am info info-am install install-am install-data \
    +	install-data-am install-data-hook install-docDATA install-dvi \
    +	install-dvi-am install-exec install-exec-am install-html \
    +	install-html-am install-includeHEADERS install-info \
    +	install-info-am install-libLTLIBRARIES install-man install-pdf \
    +	install-pdf-am install-ps install-ps-am install-strip \
    +	installcheck installcheck-am installdirs maintainer-clean \
    +	maintainer-clean-generic mostlyclean mostlyclean-compile \
    +	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
    +	tags tags-am uninstall uninstall-am uninstall-docDATA \
    +	uninstall-includeHEADERS uninstall-libLTLIBRARIES \
    +	uninstall-local
    +
    +.PRECIOUS: Makefile
    +
    +
    +install-data-hook:
    +	cd "$(DESTDIR)$(docdir)" && $(am__mv) Changes changelog
    +
    +uninstall-local:
    +	$(RM) "$(DESTDIR)$(docdir)/changelog"
    +
    +# Tell versions [3.59,3.63) of GNU make to not export all variables.
    +# Otherwise a system limit (for SysV at least) may be exceeded.
    +.NOEXPORT:
    diff --git a/contrib/expat/lib/ascii.h b/contrib/expat/lib/ascii.h
    index d10530b09bde..c3587e57332b 100644
    --- a/contrib/expat/lib/ascii.h
    +++ b/contrib/expat/lib/ascii.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #define ASCII_A 0x41
    diff --git a/contrib/expat/lib/asciitab.h b/contrib/expat/lib/asciitab.h
    index 79a15c28ca14..2f59fd929065 100644
    --- a/contrib/expat/lib/asciitab.h
    +++ b/contrib/expat/lib/asciitab.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     /* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
    diff --git a/contrib/expat/lib/expat.h b/contrib/expat/lib/expat.h
    index 086e24b39c51..174c3fafda3f 100644
    --- a/contrib/expat/lib/expat.h
    +++ b/contrib/expat/lib/expat.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #ifndef Expat_INCLUDED
    @@ -24,7 +52,6 @@ extern "C" {
     struct XML_ParserStruct;
     typedef struct XML_ParserStruct *XML_Parser;
     
    -/* Should this be defined using stdbool.h when C99 is available? */
     typedef unsigned char XML_Bool;
     #define XML_TRUE   ((XML_Bool) 1)
     #define XML_FALSE  ((XML_Bool) 0)
    @@ -95,7 +122,9 @@ enum XML_Error {
       /* Added in 2.0. */
       XML_ERROR_RESERVED_PREFIX_XML,
       XML_ERROR_RESERVED_PREFIX_XMLNS,
    -  XML_ERROR_RESERVED_NAMESPACE_URI
    +  XML_ERROR_RESERVED_NAMESPACE_URI,
    +  /* Added in 2.2.1. */
    +  XML_ERROR_INVALID_ARGUMENT
     };
     
     enum XML_Content_Type {
    @@ -235,7 +264,7 @@ XML_ParserCreate_MM(const XML_Char *encoding,
                         const XML_Char *namespaceSeparator);
     
     /* Prepare a parser object to be re-used.  This is particularly
    -   valuable when memory allocation overhead is disproportionatly high,
    +   valuable when memory allocation overhead is disproportionately high,
        such as when a large number of small documnents need to be parsed.
        All handlers are cleared from the parser, except for the
        unknownEncodingHandler. The parser's external state is re-initialized
    @@ -706,6 +735,7 @@ XML_UseParserAsHandlerArg(XML_Parser parser);
          be called, despite an external subset being parsed.
        Note: If XML_DTD is not defined when Expat is compiled, returns
          XML_ERROR_FEATURE_REQUIRES_XML_DTD.
    +   Note: If parser == NULL, returns XML_ERROR_INVALID_ARGUMENT.
     */
     XMLPARSEAPI(enum XML_Error)
     XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);
    @@ -729,15 +759,16 @@ XML_GetBase(XML_Parser parser);
        to the XML_StartElementHandler that were specified in the start-tag
        rather than defaulted. Each attribute/value pair counts as 2; thus
        this correspondds to an index into the atts array passed to the
    -   XML_StartElementHandler.
    +   XML_StartElementHandler.  Returns -1 if parser == NULL.
     */
     XMLPARSEAPI(int)
     XML_GetSpecifiedAttributeCount(XML_Parser parser);
     
     /* Returns the index of the ID attribute passed in the last call to
    -   XML_StartElementHandler, or -1 if there is no ID attribute.  Each
    -   attribute/value pair counts as 2; thus this correspondds to an
    -   index into the atts array passed to the XML_StartElementHandler.
    +   XML_StartElementHandler, or -1 if there is no ID attribute or
    +   parser == NULL.  Each attribute/value pair counts as 2; thus this
    +   correspondds to an index into the atts array passed to the
    +   XML_StartElementHandler.
     */
     XMLPARSEAPI(int)
     XML_GetIdAttributeIndex(XML_Parser parser);
    @@ -901,6 +932,7 @@ enum XML_ParamEntityParsing {
        entities is requested; otherwise it will return non-zero.
        Note: If XML_SetParamEntityParsing is called after XML_Parse or
           XML_ParseBuffer, then it has no effect and will always return 0.
    +   Note: If parser == NULL, the function will do nothing and return 0.
     */
     XMLPARSEAPI(int)
     XML_SetParamEntityParsing(XML_Parser parser,
    @@ -910,6 +942,7 @@ XML_SetParamEntityParsing(XML_Parser parser,
        Helps in preventing DoS attacks based on predicting hash
        function behavior. This must be called before parsing is started.
        Returns 1 if successful, 0 when called after parsing has started.
    +   Note: If parser == NULL, the function will do nothing and return 0.
     */
     XMLPARSEAPI(int)
     XML_SetHashSalt(XML_Parser parser,
    @@ -936,6 +969,10 @@ XML_GetErrorCode(XML_Parser parser);
        the location is the location of the character at which the error
        was detected; otherwise the location is the location of the last
        parse event, as described above.
    +
    +   Note: XML_GetCurrentLineNumber and XML_GetCurrentColumnNumber
    +   return 0 to indicate an error.
    +   Note: XML_GetCurrentByteIndex returns -1 to indicate an error.
     */
     XMLPARSEAPI(XML_Size) XML_GetCurrentLineNumber(XML_Parser parser);
     XMLPARSEAPI(XML_Size) XML_GetCurrentColumnNumber(XML_Parser parser);
    @@ -1039,7 +1076,7 @@ XML_GetFeatureList(void);
     */
     #define XML_MAJOR_VERSION 2
     #define XML_MINOR_VERSION 2
    -#define XML_MICRO_VERSION 0
    +#define XML_MICRO_VERSION 6
     
     #ifdef __cplusplus
     }
    diff --git a/contrib/expat/lib/expat_external.h b/contrib/expat/lib/expat_external.h
    index aa08a2f84c07..629483a91b27 100644
    --- a/contrib/expat/lib/expat_external.h
    +++ b/contrib/expat/lib/expat_external.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #ifndef Expat_External_INCLUDED
    @@ -8,7 +36,7 @@
     /* External API definitions */
     
     #if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)
    -#define XML_USE_MSC_EXTENSIONS 1
    +# define XML_USE_MSC_EXTENSIONS 1
     #endif
     
     /* Expat tries very hard to make the API boundary very specifically
    @@ -34,11 +62,11 @@
        system headers may assume the cdecl convention.
     */
     #ifndef XMLCALL
    -#if defined(_MSC_VER)
    -#define XMLCALL __cdecl
    -#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)
    -#define XMLCALL __attribute__((cdecl))
    -#else
    +# if defined(_MSC_VER)
    +#  define XMLCALL __cdecl
    +# elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)
    +#  define XMLCALL __attribute__((cdecl))
    +# else
     /* For any platform which uses this definition and supports more than
        one calling convention, we need to extend this definition to
        declare the convention used on that platform, if it's possible to
    @@ -49,41 +77,41 @@
        pre-processor and how to specify the same calling convention as the
        platform's malloc() implementation.
     */
    -#define XMLCALL
    -#endif
    +#  define XMLCALL
    +# endif
     #endif  /* not defined XMLCALL */
     
     
     #if !defined(XML_STATIC) && !defined(XMLIMPORT)
    -#ifndef XML_BUILDING_EXPAT
    +# ifndef XML_BUILDING_EXPAT
     /* using Expat from an application */
     
    -#ifdef XML_USE_MSC_EXTENSIONS
    -#define XMLIMPORT __declspec(dllimport)
    -#endif
    +#  ifdef XML_USE_MSC_EXTENSIONS
    +#   define XMLIMPORT __declspec(dllimport)
    +#  endif
     
    -#endif
    +# endif
     #endif  /* not defined XML_STATIC */
     
     #if !defined(XMLIMPORT) && defined(__GNUC__) && (__GNUC__ >= 4)
    -#define XMLIMPORT __attribute__ ((visibility ("default")))
    +# define XMLIMPORT __attribute__ ((visibility ("default")))
     #endif
     
     /* If we didn't define it above, define it away: */
     #ifndef XMLIMPORT
    -#define XMLIMPORT
    +# define XMLIMPORT
     #endif
     
     #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96))
    -#define XML_ATTR_MALLOC __attribute__((__malloc__))
    +# define XML_ATTR_MALLOC __attribute__((__malloc__))
     #else
    -#define XML_ATTR_MALLOC
    +# define XML_ATTR_MALLOC
     #endif
     
     #if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
    -#define XML_ATTR_ALLOC_SIZE(x)  __attribute__((__alloc_size__(x)))
    +# define XML_ATTR_ALLOC_SIZE(x)  __attribute__((__alloc_size__(x)))
     #else
    -#define XML_ATTR_ALLOC_SIZE(x)
    +# define XML_ATTR_ALLOC_SIZE(x)
     #endif
     
     #define XMLPARSEAPI(type) XMLIMPORT type XMLCALL
    @@ -93,30 +121,35 @@ extern "C" {
     #endif
     
     #ifdef XML_UNICODE_WCHAR_T
    -#define XML_UNICODE
    +# ifndef XML_UNICODE
    +#  define XML_UNICODE
    +# endif
    +# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2)
    +#  error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc"
    +# endif
     #endif
     
     #ifdef XML_UNICODE     /* Information is UTF-16 encoded. */
    -#ifdef XML_UNICODE_WCHAR_T
    +# ifdef XML_UNICODE_WCHAR_T
     typedef wchar_t XML_Char;
     typedef wchar_t XML_LChar;
    -#else
    +# else
     typedef unsigned short XML_Char;
     typedef char XML_LChar;
    -#endif /* XML_UNICODE_WCHAR_T */
    +# endif /* XML_UNICODE_WCHAR_T */
     #else                  /* Information is UTF-8 encoded. */
     typedef char XML_Char;
     typedef char XML_LChar;
     #endif /* XML_UNICODE */
     
     #ifdef XML_LARGE_SIZE  /* Use large integers for file/stream positions. */
    -#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
    +# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
     typedef __int64 XML_Index; 
     typedef unsigned __int64 XML_Size;
    -#else
    +# else
     typedef long long XML_Index;
     typedef unsigned long long XML_Size;
    -#endif
    +# endif
     #else
     typedef long XML_Index;
     typedef unsigned long XML_Size;
    diff --git a/contrib/expat/lib/iasciitab.h b/contrib/expat/lib/iasciitab.h
    index 24a1d5ccc9a5..ce4a4bf7edef 100644
    --- a/contrib/expat/lib/iasciitab.h
    +++ b/contrib/expat/lib/iasciitab.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     /* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */
    diff --git a/contrib/expat/lib/internal.h b/contrib/expat/lib/internal.h
    index 94cb98e15cae..e33fdcb0238d 100644
    --- a/contrib/expat/lib/internal.h
    +++ b/contrib/expat/lib/internal.h
    @@ -18,6 +18,35 @@
     
        Note: Use of these macros is based on judgement, not hard rules,
              and therefore subject to change.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #if defined(__GNUC__) && defined(__i386__) && !defined(__MINGW32__)
    @@ -87,7 +116,7 @@ extern "C" {
     
     
     void
    -align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef);
    +_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef);
     
     
     #ifdef __cplusplus
    diff --git a/contrib/expat/lib/latin1tab.h b/contrib/expat/lib/latin1tab.h
    index 53c25d76b268..95dfa52b1fbe 100644
    --- a/contrib/expat/lib/latin1tab.h
    +++ b/contrib/expat/lib/latin1tab.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     /* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
    diff --git a/contrib/expat/lib/loadlibrary.c b/contrib/expat/lib/loadlibrary.c
    new file mode 100644
    index 000000000000..35fdf98bce6c
    --- /dev/null
    +++ b/contrib/expat/lib/loadlibrary.c
    @@ -0,0 +1,143 @@
    +/***************************************************************************
    + *                                  _   _ ____  _
    + *  Project                     ___| | | |  _ \| |
    + *                             / __| | | | |_) | |
    + *                            | (__| |_| |  _ <| |___
    + *                             \___|\___/|_| \_\_____|
    + *
    + * Copyright (C) 2016 - 2017, Steve Holme, .
    + * Copyright (C) 2017, Expat development team
    + *
    + * All rights reserved.
    + * Licensed under the MIT license:
    + *
    + * Permission to  use, copy,  modify, and distribute  this software  for any
    + * purpose with  or without fee is  hereby granted, provided that  the above
    + * copyright notice and this permission notice appear in all copies.
    + *
    + * THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    + * EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    + * MERCHANTABILITY, FITNESS FOR A  PARTICULAR PURPOSE AND NONINFRINGEMENT OF
    + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
    + * CONTRACT, TORT OR  OTHERWISE, ARISING FROM, OUT OF OR  IN CONNECTION WITH
    + * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    + *
    + * Except as contained in this notice,  the name of a copyright holder shall
    + * not be used in advertising or otherwise to promote the sale, use or other
    + * dealings  in this  Software without  prior written  authorization of  the
    + * copyright holder.
    + *
    + ***************************************************************************/
    +
    +#if defined(_WIN32)
    +
    +#include 
    +#include 
    +
    +
    +HMODULE _Expat_LoadLibrary(LPCTSTR filename);
    +
    +
    +#if !defined(LOAD_WITH_ALTERED_SEARCH_PATH)
    +#define LOAD_WITH_ALTERED_SEARCH_PATH  0x00000008
    +#endif
    +
    +#if !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
    +#define LOAD_LIBRARY_SEARCH_SYSTEM32   0x00000800
    +#endif
    +
    +/* We use our own typedef here since some headers might lack these */
    +typedef HMODULE (APIENTRY *LOADLIBRARYEX_FN)(LPCTSTR, HANDLE, DWORD);
    +
    +/* See function definitions in winbase.h */
    +#ifdef UNICODE
    +#  ifdef _WIN32_WCE
    +#    define LOADLIBARYEX  L"LoadLibraryExW"
    +#  else
    +#    define LOADLIBARYEX  "LoadLibraryExW"
    +#  endif
    +#else
    +#  define LOADLIBARYEX    "LoadLibraryExA"
    +#endif
    +
    +
    +/*
    + * _Expat_LoadLibrary()
    + *
    + * This is used to dynamically load DLLs using the most secure method available
    + * for the version of Windows that we are running on.
    + *
    + * Parameters:
    + *
    + * filename  [in] - The filename or full path of the DLL to load. If only the
    + *                  filename is passed then the DLL will be loaded from the
    + *                  Windows system directory.
    + *
    + * Returns the handle of the module on success; otherwise NULL.
    + */
    +HMODULE _Expat_LoadLibrary(LPCTSTR filename)
    +{
    +  HMODULE hModule = NULL;
    +  LOADLIBRARYEX_FN pLoadLibraryEx = NULL;
    +
    +  /* Get a handle to kernel32 so we can access it's functions at runtime */
    +  HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32"));
    +  if(!hKernel32)
    +    return NULL;  /* LCOV_EXCL_LINE */
    +
    +  /* Attempt to find LoadLibraryEx() which is only available on Windows 2000
    +     and above */
    +  pLoadLibraryEx = (LOADLIBRARYEX_FN) GetProcAddress(hKernel32, LOADLIBARYEX);
    +
    +  /* Detect if there's already a path in the filename and load the library if
    +     there is. Note: Both back slashes and forward slashes have been supported
    +     since the earlier days of DOS at an API level although they are not
    +     supported by command prompt */
    +  if(_tcspbrk(filename, TEXT("\\/"))) {
    +    /** !checksrc! disable BANNEDFUNC 1 **/
    +    hModule = pLoadLibraryEx ?
    +      pLoadLibraryEx(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
    +      LoadLibrary(filename);
    +  }
    +  /* Detect if KB2533623 is installed, as LOAD_LIBARY_SEARCH_SYSTEM32 is only
    +     supported on Windows Vista, Windows Server 2008, Windows 7 and Windows
    +     Server 2008 R2 with this patch or natively on Windows 8 and above */
    +  else if(pLoadLibraryEx && GetProcAddress(hKernel32, "AddDllDirectory")) {
    +    /* Load the DLL from the Windows system directory */
    +    hModule = pLoadLibraryEx(filename, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
    +  }
    +  else {
    +    /* Attempt to get the Windows system path */
    +    UINT systemdirlen = GetSystemDirectory(NULL, 0);
    +    if(systemdirlen) {
    +      /* Allocate space for the full DLL path (Room for the null terminator
    +         is included in systemdirlen) */
    +      size_t filenamelen = _tcslen(filename);
    +      TCHAR *path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen));
    +      if(path && GetSystemDirectory(path, systemdirlen)) {
    +        /* Calculate the full DLL path */
    +        _tcscpy(path + _tcslen(path), TEXT("\\"));
    +        _tcscpy(path + _tcslen(path), filename);
    +
    +        /* Load the DLL from the Windows system directory */
    +        /** !checksrc! disable BANNEDFUNC 1 **/
    +        hModule = pLoadLibraryEx ?
    +          pLoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
    +          LoadLibrary(path);
    +
    +      }
    +      free(path);
    +    }
    +  }
    +
    +  return hModule;
    +}
    +
    +#else /* defined(_WIN32) */
    +
    +/* ISO C requires a translation unit to contain at least one declaration
    +   [-Wempty-translation-unit] */
    +typedef int _TRANSLATION_UNIT_LOAD_LIBRARY_C_NOT_EMTPY;
    +
    +#endif /* defined(_WIN32) */
    diff --git a/contrib/expat/lib/nametab.h b/contrib/expat/lib/nametab.h
    index b05e62c77a6c..bfa2bd38cd95 100644
    --- a/contrib/expat/lib/nametab.h
    +++ b/contrib/expat/lib/nametab.h
    @@ -1,3 +1,35 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     static const unsigned namingBitmap[] = {
     0x00000000, 0x00000000, 0x00000000, 0x00000000,
     0x00000000, 0x00000000, 0x00000000, 0x00000000,
    diff --git a/contrib/expat/lib/siphash.h b/contrib/expat/lib/siphash.h
    new file mode 100644
    index 000000000000..4d6786d7839a
    --- /dev/null
    +++ b/contrib/expat/lib/siphash.h
    @@ -0,0 +1,391 @@
    +/* ==========================================================================
    + * siphash.h - SipHash-2-4 in a single header file
    + * --------------------------------------------------------------------------
    + * Derived by William Ahern from the reference implementation[1] published[2]
    + * by Jean-Philippe Aumasson and Daniel J. Berstein.
    + * Minimal changes by Sebastian Pipping and Victor Stinner on top, see below.
    + * Licensed under the CC0 Public Domain Dedication license.
    + *
    + * 1. https://www.131002.net/siphash/siphash24.c
    + * 2. https://www.131002.net/siphash/
    + * --------------------------------------------------------------------------
    + * HISTORY:
    + *
    + * 2018-07-08  (Anton Maklakov)
    + *   - Add "fall through" markers for GCC's -Wimplicit-fallthrough
    + *
    + * 2017-11-03  (Sebastian Pipping)
    + *   - Hide sip_tobin and sip_binof unless SIPHASH_TOBIN macro is defined
    + *
    + * 2017-07-25  (Vadim Zeitlin)
    + *   - Fix use of SIPHASH_MAIN macro
    + *
    + * 2017-07-05  (Sebastian Pipping)
    + *   - Use _SIP_ULL macro to not require a C++11 compiler if compiled as C++
    + *   - Add const qualifiers at two places
    + *   - Ensure <=80 characters line length (assuming tab width 4)
    + *
    + * 2017-06-23  (Victor Stinner)
    + *   - Address Win64 compile warnings
    + *
    + * 2017-06-18  (Sebastian Pipping)
    + *   - Clarify license note in the header
    + *   - Address C89 issues:
    + *     - Stop using inline keyword (and let compiler decide)
    + *     - Replace _Bool by int
    + *     - Turn macro siphash24 into a function
    + *     - Address invalid conversion (void pointer) by explicit cast
    + *   - Address lack of stdint.h for Visual Studio 2003 to 2008
    + *   - Always expose sip24_valid (for self-tests)
    + *
    + * 2012-11-04 - Born.  (William Ahern)
    + * --------------------------------------------------------------------------
    + * USAGE:
    + *
    + * SipHash-2-4 takes as input two 64-bit words as the key, some number of
    + * message bytes, and outputs a 64-bit word as the message digest. This
    + * implementation employs two data structures: a struct sipkey for
    + * representing the key, and a struct siphash for representing the hash
    + * state.
    + *
    + * For converting a 16-byte unsigned char array to a key, use either the
    + * macro sip_keyof or the routine sip_tokey. The former instantiates a
    + * compound literal key, while the latter requires a key object as a
    + * parameter.
    + *
    + * 	unsigned char secret[16];
    + * 	arc4random_buf(secret, sizeof secret);
    + * 	struct sipkey *key = sip_keyof(secret);
    + *
    + * For hashing a message, use either the convenience macro siphash24 or the
    + * routines sip24_init, sip24_update, and sip24_final.
    + *
    + * 	struct siphash state;
    + * 	void *msg;
    + * 	size_t len;
    + * 	uint64_t hash;
    + *
    + * 	sip24_init(&state, key);
    + * 	sip24_update(&state, msg, len);
    + * 	hash = sip24_final(&state);
    + *
    + * or
    + *
    + * 	hash = siphash24(msg, len, key);
    + *
    + * To convert the 64-bit hash value to a canonical 8-byte little-endian
    + * binary representation, use either the macro sip_binof or the routine
    + * sip_tobin. The former instantiates and returns a compound literal array,
    + * while the latter requires an array object as a parameter.
    + * --------------------------------------------------------------------------
    + * NOTES:
    + *
    + * o Neither sip_keyof, sip_binof, nor siphash24 will work with compilers
    + *   lacking compound literal support. Instead, you must use the lower-level
    + *   interfaces which take as parameters the temporary state objects.
    + *
    + * o Uppercase macros may evaluate parameters more than once. Lowercase
    + *   macros should not exhibit any such side effects.
    + * ==========================================================================
    + */
    +#ifndef SIPHASH_H
    +#define SIPHASH_H
    +
    +#include  /* size_t */
    +
    +#if defined(_WIN32) && defined(_MSC_VER) && (_MSC_VER < 1600)
    +  /* For vs2003/7.1 up to vs2008/9.0; _MSC_VER 1600 is vs2010/10.0 */
    +  typedef unsigned __int8   uint8_t;
    +  typedef unsigned __int32 uint32_t;
    +  typedef unsigned __int64 uint64_t;
    +#else
    + #include  /* uint64_t uint32_t uint8_t */
    +#endif
    +
    +
    +/*
    + * Workaround to not require a C++11 compiler for using ULL suffix
    + * if this code is included and compiled as C++; related GCC warning is:
    + * warning: use of C++11 long long integer constant [-Wlong-long]
    + */
    +#define _SIP_ULL(high, low)  (((uint64_t)high << 32) | low)
    +
    +
    +#define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ( (x) >> (64 - (b))))
    +
    +#define SIP_U32TO8_LE(p, v) \
    +	(p)[0] = (uint8_t)((v) >>  0); (p)[1] = (uint8_t)((v) >>  8); \
    +	(p)[2] = (uint8_t)((v) >> 16); (p)[3] = (uint8_t)((v) >> 24);
    +
    +#define SIP_U64TO8_LE(p, v) \
    +	SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >>  0)); \
    +	SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));
    +
    +#define SIP_U8TO64_LE(p) \
    +	(((uint64_t)((p)[0]) <<  0) | \
    +	 ((uint64_t)((p)[1]) <<  8) | \
    +	 ((uint64_t)((p)[2]) << 16) | \
    +	 ((uint64_t)((p)[3]) << 24) | \
    +	 ((uint64_t)((p)[4]) << 32) | \
    +	 ((uint64_t)((p)[5]) << 40) | \
    +	 ((uint64_t)((p)[6]) << 48) | \
    +	 ((uint64_t)((p)[7]) << 56))
    +
    +
    +#define SIPHASH_INITIALIZER { 0, 0, 0, 0, { 0 }, 0, 0 }
    +
    +struct siphash {
    +	uint64_t v0, v1, v2, v3;
    +
    +	unsigned char buf[8], *p;
    +	uint64_t c;
    +}; /* struct siphash */
    +
    +
    +#define SIP_KEYLEN 16
    +
    +struct sipkey {
    +	uint64_t k[2];
    +}; /* struct sipkey */
    +
    +#define sip_keyof(k) sip_tokey(&(struct sipkey){ { 0 } }, (k))
    +
    +static struct sipkey *sip_tokey(struct sipkey *key, const void *src) {
    +	key->k[0] = SIP_U8TO64_LE((const unsigned char *)src);
    +	key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8);
    +	return key;
    +} /* sip_tokey() */
    +
    +
    +#ifdef SIPHASH_TOBIN
    +
    +#define sip_binof(v) sip_tobin((unsigned char[8]){ 0 }, (v))
    +
    +static void *sip_tobin(void *dst, uint64_t u64) {
    +	SIP_U64TO8_LE((unsigned char *)dst, u64);
    +	return dst;
    +} /* sip_tobin() */
    +
    +#endif  /* SIPHASH_TOBIN */
    +
    +
    +static void sip_round(struct siphash *H, const int rounds) {
    +	int i;
    +
    +	for (i = 0; i < rounds; i++) {
    +		H->v0 += H->v1;
    +		H->v1 = SIP_ROTL(H->v1, 13);
    +		H->v1 ^= H->v0;
    +		H->v0 = SIP_ROTL(H->v0, 32);
    +
    +		H->v2 += H->v3;
    +		H->v3 = SIP_ROTL(H->v3, 16);
    +		H->v3 ^= H->v2;
    +
    +		H->v0 += H->v3;
    +		H->v3 = SIP_ROTL(H->v3, 21);
    +		H->v3 ^= H->v0;
    +
    +		H->v2 += H->v1;
    +		H->v1 = SIP_ROTL(H->v1, 17);
    +		H->v1 ^= H->v2;
    +		H->v2 = SIP_ROTL(H->v2, 32);
    +	}
    +} /* sip_round() */
    +
    +
    +static struct siphash *sip24_init(struct siphash *H,
    +		const struct sipkey *key) {
    +	H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0];
    +	H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1];
    +	H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0];
    +	H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1];
    +
    +	H->p = H->buf;
    +	H->c = 0;
    +
    +	return H;
    +} /* sip24_init() */
    +
    +
    +#define sip_endof(a) (&(a)[sizeof (a) / sizeof *(a)])
    +
    +static struct siphash *sip24_update(struct siphash *H, const void *src,
    +		size_t len) {
    +	const unsigned char *p = (const unsigned char *)src, *pe = p + len;
    +	uint64_t m;
    +
    +	do {
    +		while (p < pe && H->p < sip_endof(H->buf))
    +			*H->p++ = *p++;
    +
    +		if (H->p < sip_endof(H->buf))
    +			break;
    +
    +		m = SIP_U8TO64_LE(H->buf);
    +		H->v3 ^= m;
    +		sip_round(H, 2);
    +		H->v0 ^= m;
    +
    +		H->p = H->buf;
    +		H->c += 8;
    +	} while (p < pe);
    +
    +	return H;
    +} /* sip24_update() */
    +
    +
    +static uint64_t sip24_final(struct siphash *H) {
    +	const char left = (char)(H->p - H->buf);
    +	uint64_t b = (H->c + left) << 56;
    +
    +	switch (left) {
    +	case 7: b |= (uint64_t)H->buf[6] << 48;
    +		/* fall through */
    +	case 6: b |= (uint64_t)H->buf[5] << 40;
    +		/* fall through */
    +	case 5: b |= (uint64_t)H->buf[4] << 32;
    +		/* fall through */
    +	case 4: b |= (uint64_t)H->buf[3] << 24;
    +		/* fall through */
    +	case 3: b |= (uint64_t)H->buf[2] << 16;
    +		/* fall through */
    +	case 2: b |= (uint64_t)H->buf[1] << 8;
    +		/* fall through */
    +	case 1: b |= (uint64_t)H->buf[0] << 0;
    +		/* fall through */
    +	case 0: break;
    +	}
    +
    +	H->v3 ^= b;
    +	sip_round(H, 2);
    +	H->v0 ^= b;
    +	H->v2 ^= 0xff;
    +	sip_round(H, 4);
    +
    +	return H->v0 ^ H->v1 ^ H->v2  ^ H->v3;
    +} /* sip24_final() */
    +
    +
    +static uint64_t siphash24(const void *src, size_t len,
    +		const struct sipkey *key) {
    +	struct siphash state = SIPHASH_INITIALIZER;
    +	return sip24_final(sip24_update(sip24_init(&state, key), src, len));
    +} /* siphash24() */
    +
    +
    +/*
    + * SipHash-2-4 output with
    + * k = 00 01 02 ...
    + * and
    + * in = (empty string)
    + * in = 00 (1 byte)
    + * in = 00 01 (2 bytes)
    + * in = 00 01 02 (3 bytes)
    + * ...
    + * in = 00 01 02 ... 3e (63 bytes)
    + */
    +static int sip24_valid(void) {
    +	static const unsigned char vectors[64][8] = {
    +		{ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, },
    +		{ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, },
    +		{ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, },
    +		{ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, },
    +		{ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, },
    +		{ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, },
    +		{ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, },
    +		{ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, },
    +		{ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, },
    +		{ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, },
    +		{ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, },
    +		{ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, },
    +		{ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, },
    +		{ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, },
    +		{ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, },
    +		{ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, },
    +		{ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, },
    +		{ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, },
    +		{ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, },
    +		{ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, },
    +		{ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, },
    +		{ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, },
    +		{ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, },
    +		{ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, },
    +		{ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, },
    +		{ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, },
    +		{ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, },
    +		{ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, },
    +		{ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, },
    +		{ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, },
    +		{ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, },
    +		{ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, },
    +		{ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, },
    +		{ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, },
    +		{ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, },
    +		{ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, },
    +		{ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, },
    +		{ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, },
    +		{ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, },
    +		{ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, },
    +		{ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, },
    +		{ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, },
    +		{ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, },
    +		{ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, },
    +		{ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, },
    +		{ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, },
    +		{ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, },
    +		{ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, },
    +		{ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, },
    +		{ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, },
    +		{ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, },
    +		{ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, },
    +		{ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, },
    +		{ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, },
    +		{ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, },
    +		{ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, },
    +		{ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, },
    +		{ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, },
    +		{ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, },
    +		{ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, },
    +		{ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, },
    +		{ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, },
    +		{ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, },
    +		{ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, }
    +	};
    +	unsigned char in[64];
    +	struct sipkey k;
    +	size_t i;
    +
    +	sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011"
    +			"\012\013\014\015\016\017");
    +
    +	for (i = 0; i < sizeof in; ++i) {
    +		in[i] = (unsigned char)i;
    +
    +		if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i]))
    +			return 0;
    +	}
    +
    +	return 1;
    +} /* sip24_valid() */
    +
    +
    +#ifdef SIPHASH_MAIN
    +
    +#include 
    +
    +int main(void) {
    +	const int ok = sip24_valid();
    +
    +	if (ok)
    +		puts("OK");
    +	else
    +		puts("FAIL");
    +
    +	return !ok;
    +} /* main() */
    +
    +#endif /* SIPHASH_MAIN */
    +
    +
    +#endif /* SIPHASH_H */
    diff --git a/contrib/expat/lib/utf8tab.h b/contrib/expat/lib/utf8tab.h
    index 7bb3e77603fa..fa0bed6f5d75 100644
    --- a/contrib/expat/lib/utf8tab.h
    +++ b/contrib/expat/lib/utf8tab.h
    @@ -1,7 +1,34 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    -*/
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
     
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
     
     /* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
     /* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
    diff --git a/contrib/expat/lib/xmlparse.c b/contrib/expat/lib/xmlparse.c
    index b308e67e2d39..e4ce52816ab9 100644
    --- a/contrib/expat/lib/xmlparse.c
    +++ b/contrib/expat/lib/xmlparse.c
    @@ -1,36 +1,115 @@
    -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/* 19ac4776051591216f1874e34ee99b6a43a3784c8bd7d70efeb9258dd22b906a (2.2.6+)
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
    +#if !defined(_GNU_SOURCE)
    +# define _GNU_SOURCE 1                  /* syscall prototype */
    +#endif
    +
     #include 
     #include                      /* memset(), memcpy() */
     #include 
     #include                      /* UINT_MAX */
    +#include                       /* fprintf */
    +#include                      /* getenv */
     
    -#ifdef WIN32
    +#ifdef _WIN32
     #define getpid GetCurrentProcessId
     #else
     #include                    /* gettimeofday() */
     #include                   /* getpid() */
     #include                      /* getpid() */
    +#include                       /* O_RDONLY */
    +#include 
     #endif
     
     #define XML_BUILDING_EXPAT 1
     
    -#ifdef WIN32
    +#ifdef _WIN32
     #include "winconfig.h"
    -#elif defined(MACOS_CLASSIC)
    -#include "macconfig.h"
    -#elif defined(__amigaos__)
    -#include "amigaconfig.h"
    -#elif defined(__WATCOMC__)
    -#include "watcomconfig.h"
     #elif defined(HAVE_EXPAT_CONFIG_H)
     #include 
    -#endif /* ndef WIN32 */
    +#endif /* ndef _WIN32 */
     
     #include "ascii.h"
     #include "expat.h"
    +#include "siphash.h"
    +
    +#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
    +# if defined(HAVE_GETRANDOM)
    +#  include     /* getrandom */
    +# else
    +#  include         /* syscall */
    +#  include    /* SYS_getrandom */
    +# endif
    +# if ! defined(GRND_NONBLOCK)
    +#  define GRND_NONBLOCK  0x0001
    +# endif  /* defined(GRND_NONBLOCK) */
    +#endif  /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
    +
    +#if defined(HAVE_LIBBSD) \
    +    && (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
    +# include 
    +#endif
    +
    +#if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
    +# define LOAD_LIBRARY_SEARCH_SYSTEM32  0x00000800
    +#endif
    +
    +#if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \
    +    && !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \
    +    && !defined(XML_DEV_URANDOM) \
    +    && !defined(_WIN32) \
    +    && !defined(XML_POOR_ENTROPY)
    +# error  \
    +    You do not have support for any sources of high quality entropy \
    +    enabled.  For end user security, that is probably not what you want. \
    +    \
    +    Your options include: \
    +      * Linux + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
    +      * Linux + glibc <2.25 (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
    +      * BSD / macOS >=10.7 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
    +      * BSD / macOS <10.7 (arc4random): HAVE_ARC4RANDOM, \
    +      * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
    +      * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
    +      * Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \
    +      * Windows (RtlGenRandom): _WIN32. \
    +    \
    +    If insist on not using any of these, bypass this error by defining \
    +    XML_POOR_ENTROPY; you have been warned. \
    +    \
    +    If you have reasons to patch this detection code away or need changes \
    +    to the build system, please open a bug.  Thank you!
    +#endif
    +
     
     #ifdef XML_UNICODE
     #define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
    @@ -82,6 +161,9 @@ typedef char ICHAR;
     /* Round up n to be a multiple of sz, where sz is a power of 2. */
     #define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
     
    +/* Do safe (NULL-aware) pointer arithmetic */
    +#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
    +
     /* Handle the case where memmove() doesn't exist. */
     #ifndef HAVE_MEMMOVE
     #ifdef HAVE_BCOPY
    @@ -109,17 +191,11 @@ typedef struct {
       const XML_Memory_Handling_Suite *mem;
     } HASH_TABLE;
     
    -/* Basic character hash algorithm, taken from Python's string hash:
    -   h = h * 1000003 ^ character, the constant being a prime number.
    +static size_t
    +keylen(KEY s);
     
    -*/
    -#ifdef XML_UNICODE
    -#define CHAR_HASH(h, c) \
    -  (((h) * 0xF4243) ^ (unsigned short)(c))
    -#else
    -#define CHAR_HASH(h, c) \
    -  (((h) * 0xF4243) ^ (unsigned char)(c))
    -#endif
    +static void
    +copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key);
     
     /* For probing (after a collision) we need a step size relative prime
        to the hash table size, which is a power of 2. We use double-hashing,
    @@ -355,6 +431,8 @@ doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr,
                     const char *end, const char **nextPtr, XML_Bool haveMore);
     #endif /* XML_DTD */
     
    +static void
    +freeBindings(XML_Parser parser, BINDING *bindings);
     static enum XML_Error
     storeAtts(XML_Parser parser, const ENCODING *, const char *s,
               TAG_NAME *tagNamePtr, BINDING **bindingsPtr);
    @@ -395,7 +473,7 @@ setContext(XML_Parser parser, const XML_Char *context);
     static void FASTCALL normalizePublicId(XML_Char *s);
     
     static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms);
    -/* do not call if parentParser != NULL */
    +/* do not call if m_parentParser != NULL */
     static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
     static void
     dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms);
    @@ -439,6 +517,9 @@ static ELEMENT_TYPE *
     getElementType(XML_Parser parser, const ENCODING *enc,
                    const char *ptr, const char *end);
     
    +static XML_Char *copyString(const XML_Char *s,
    +                            const XML_Memory_Handling_Suite *memsuite);
    +
     static unsigned long generate_hash_secret_salt(XML_Parser parser);
     static XML_Bool startParsing(XML_Parser parser);
     
    @@ -464,7 +545,7 @@ parserInit(XML_Parser parser, const XML_Char *encodingName);
        : ((*((pool)->ptr)++ = c), 1))
     
     struct XML_ParserStruct {
    -  /* The first member must be userData so that the XML_GetUserData
    +  /* The first member must be m_userData so that the XML_GetUserData
          macro works. */
       void *m_userData;
       void *m_handlerArg;
    @@ -474,7 +555,7 @@ struct XML_ParserStruct {
       const char *m_bufferPtr;
       /* past last character to be parsed */
       char *m_bufferEnd;
    -  /* allocated end of buffer */
    +  /* allocated end of m_buffer */
       const char *m_bufferLim;
       XML_Index m_parseEndByteIndex;
       const char *m_parseEndPtr;
    @@ -566,113 +647,10 @@ struct XML_ParserStruct {
       unsigned long m_hash_secret_salt;
     };
     
    -#define MALLOC(s) (parser->m_mem.malloc_fcn((s)))
    -#define REALLOC(p,s) (parser->m_mem.realloc_fcn((p),(s)))
    -#define FREE(p) (parser->m_mem.free_fcn((p)))
    +#define MALLOC(parser, s)      (parser->m_mem.malloc_fcn((s)))
    +#define REALLOC(parser, p, s)  (parser->m_mem.realloc_fcn((p),(s)))
    +#define FREE(parser, p)        (parser->m_mem.free_fcn((p)))
     
    -#define userData (parser->m_userData)
    -#define handlerArg (parser->m_handlerArg)
    -#define startElementHandler (parser->m_startElementHandler)
    -#define endElementHandler (parser->m_endElementHandler)
    -#define characterDataHandler (parser->m_characterDataHandler)
    -#define processingInstructionHandler \
    -        (parser->m_processingInstructionHandler)
    -#define commentHandler (parser->m_commentHandler)
    -#define startCdataSectionHandler \
    -        (parser->m_startCdataSectionHandler)
    -#define endCdataSectionHandler (parser->m_endCdataSectionHandler)
    -#define defaultHandler (parser->m_defaultHandler)
    -#define startDoctypeDeclHandler (parser->m_startDoctypeDeclHandler)
    -#define endDoctypeDeclHandler (parser->m_endDoctypeDeclHandler)
    -#define unparsedEntityDeclHandler \
    -        (parser->m_unparsedEntityDeclHandler)
    -#define notationDeclHandler (parser->m_notationDeclHandler)
    -#define startNamespaceDeclHandler \
    -        (parser->m_startNamespaceDeclHandler)
    -#define endNamespaceDeclHandler (parser->m_endNamespaceDeclHandler)
    -#define notStandaloneHandler (parser->m_notStandaloneHandler)
    -#define externalEntityRefHandler \
    -        (parser->m_externalEntityRefHandler)
    -#define externalEntityRefHandlerArg \
    -        (parser->m_externalEntityRefHandlerArg)
    -#define internalEntityRefHandler \
    -        (parser->m_internalEntityRefHandler)
    -#define skippedEntityHandler (parser->m_skippedEntityHandler)
    -#define unknownEncodingHandler (parser->m_unknownEncodingHandler)
    -#define elementDeclHandler (parser->m_elementDeclHandler)
    -#define attlistDeclHandler (parser->m_attlistDeclHandler)
    -#define entityDeclHandler (parser->m_entityDeclHandler)
    -#define xmlDeclHandler (parser->m_xmlDeclHandler)
    -#define encoding (parser->m_encoding)
    -#define initEncoding (parser->m_initEncoding)
    -#define internalEncoding (parser->m_internalEncoding)
    -#define unknownEncodingMem (parser->m_unknownEncodingMem)
    -#define unknownEncodingData (parser->m_unknownEncodingData)
    -#define unknownEncodingHandlerData \
    -  (parser->m_unknownEncodingHandlerData)
    -#define unknownEncodingRelease (parser->m_unknownEncodingRelease)
    -#define protocolEncodingName (parser->m_protocolEncodingName)
    -#define ns (parser->m_ns)
    -#define ns_triplets (parser->m_ns_triplets)
    -#define prologState (parser->m_prologState)
    -#define processor (parser->m_processor)
    -#define errorCode (parser->m_errorCode)
    -#define eventPtr (parser->m_eventPtr)
    -#define eventEndPtr (parser->m_eventEndPtr)
    -#define positionPtr (parser->m_positionPtr)
    -#define position (parser->m_position)
    -#define openInternalEntities (parser->m_openInternalEntities)
    -#define freeInternalEntities (parser->m_freeInternalEntities)
    -#define defaultExpandInternalEntities \
    -        (parser->m_defaultExpandInternalEntities)
    -#define tagLevel (parser->m_tagLevel)
    -#define buffer (parser->m_buffer)
    -#define bufferPtr (parser->m_bufferPtr)
    -#define bufferEnd (parser->m_bufferEnd)
    -#define parseEndByteIndex (parser->m_parseEndByteIndex)
    -#define parseEndPtr (parser->m_parseEndPtr)
    -#define bufferLim (parser->m_bufferLim)
    -#define dataBuf (parser->m_dataBuf)
    -#define dataBufEnd (parser->m_dataBufEnd)
    -#define _dtd (parser->m_dtd)
    -#define curBase (parser->m_curBase)
    -#define declEntity (parser->m_declEntity)
    -#define doctypeName (parser->m_doctypeName)
    -#define doctypeSysid (parser->m_doctypeSysid)
    -#define doctypePubid (parser->m_doctypePubid)
    -#define declAttributeType (parser->m_declAttributeType)
    -#define declNotationName (parser->m_declNotationName)
    -#define declNotationPublicId (parser->m_declNotationPublicId)
    -#define declElementType (parser->m_declElementType)
    -#define declAttributeId (parser->m_declAttributeId)
    -#define declAttributeIsCdata (parser->m_declAttributeIsCdata)
    -#define declAttributeIsId (parser->m_declAttributeIsId)
    -#define freeTagList (parser->m_freeTagList)
    -#define freeBindingList (parser->m_freeBindingList)
    -#define inheritedBindings (parser->m_inheritedBindings)
    -#define tagStack (parser->m_tagStack)
    -#define atts (parser->m_atts)
    -#define attsSize (parser->m_attsSize)
    -#define nSpecifiedAtts (parser->m_nSpecifiedAtts)
    -#define idAttIndex (parser->m_idAttIndex)
    -#define nsAtts (parser->m_nsAtts)
    -#define nsAttsVersion (parser->m_nsAttsVersion)
    -#define nsAttsPower (parser->m_nsAttsPower)
    -#define attInfo (parser->m_attInfo)
    -#define tempPool (parser->m_tempPool)
    -#define temp2Pool (parser->m_temp2Pool)
    -#define groupConnector (parser->m_groupConnector)
    -#define groupSize (parser->m_groupSize)
    -#define namespaceSeparator (parser->m_namespaceSeparator)
    -#define parentParser (parser->m_parentParser)
    -#define ps_parsing (parser->m_parsingStatus.parsing)
    -#define ps_finalBuffer (parser->m_parsingStatus.finalBuffer)
    -#ifdef XML_DTD
    -#define isParamEntity (parser->m_isParamEntity)
    -#define useForeignDTD (parser->m_useForeignDTD)
    -#define paramEntityParsing (parser->m_paramEntityParsing)
    -#endif /* XML_DTD */
    -#define hash_secret_salt (parser->m_hash_secret_salt)
     
     XML_Parser XMLCALL
     XML_ParserCreate(const XML_Char *encodingName)
    @@ -697,10 +675,138 @@ static const XML_Char implicitContext[] = {
       ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0'
     };
     
    +
    +/* To avoid warnings about unused functions: */
    +#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
    +
    +#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
    +
    +/* Obtain entropy on Linux 3.17+ */
    +static int
    +writeRandomBytes_getrandom_nonblock(void * target, size_t count) {
    +  int success = 0;  /* full count bytes written? */
    +  size_t bytesWrittenTotal = 0;
    +  const unsigned int getrandomFlags = GRND_NONBLOCK;
    +
    +  do {
    +    void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
    +    const size_t bytesToWrite = count - bytesWrittenTotal;
    +
    +    const int bytesWrittenMore =
    +#if defined(HAVE_GETRANDOM)
    +        getrandom(currentTarget, bytesToWrite, getrandomFlags);
    +#else
    +        syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
    +#endif
    +
    +    if (bytesWrittenMore > 0) {
    +      bytesWrittenTotal += bytesWrittenMore;
    +      if (bytesWrittenTotal >= count)
    +        success = 1;
    +    }
    +  } while (! success && (errno == EINTR));
    +
    +  return success;
    +}
    +
    +#endif  /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
    +
    +
    +#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
    +
    +/* Extract entropy from /dev/urandom */
    +static int
    +writeRandomBytes_dev_urandom(void * target, size_t count) {
    +  int success = 0;  /* full count bytes written? */
    +  size_t bytesWrittenTotal = 0;
    +
    +  const int fd = open("/dev/urandom", O_RDONLY);
    +  if (fd < 0) {
    +    return 0;
    +  }
    +
    +  do {
    +    void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
    +    const size_t bytesToWrite = count - bytesWrittenTotal;
    +
    +    const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
    +
    +    if (bytesWrittenMore > 0) {
    +      bytesWrittenTotal += bytesWrittenMore;
    +      if (bytesWrittenTotal >= count)
    +        success = 1;
    +    }
    +  } while (! success && (errno == EINTR));
    +
    +  close(fd);
    +  return success;
    +}
    +
    +#endif  /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
    +
    +#endif  /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
    +
    +
    +#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
    +
    +static void
    +writeRandomBytes_arc4random(void * target, size_t count) {
    +  size_t bytesWrittenTotal = 0;
    +
    +  while (bytesWrittenTotal < count) {
    +    const uint32_t random32 = arc4random();
    +    size_t i = 0;
    +
    +    for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
    +        i++, bytesWrittenTotal++) {
    +      const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
    +      ((uint8_t *)target)[bytesWrittenTotal] = random8;
    +    }
    +  }
    +}
    +
    +#endif  /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
    +
    +
    +#ifdef _WIN32
    +
    +typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG);
    +HMODULE _Expat_LoadLibrary(LPCTSTR filename);  /* see loadlibrary.c */
    +
    +/* Obtain entropy on Windows XP / Windows Server 2003 and later.
    + * Hint on RtlGenRandom and the following article from libsodium.
    + *
    + * Michael Howard: Cryptographically Secure Random number on Windows without using CryptoAPI
    + * https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/
    + */
    +static int
    +writeRandomBytes_RtlGenRandom(void * target, size_t count) {
    +  int success = 0;  /* full count bytes written? */
    +  const HMODULE advapi32 = _Expat_LoadLibrary(TEXT("ADVAPI32.DLL"));
    +
    +  if (advapi32) {
    +    const RTLGENRANDOM_FUNC RtlGenRandom
    +        = (RTLGENRANDOM_FUNC)GetProcAddress(advapi32, "SystemFunction036");
    +    if (RtlGenRandom) {
    +      if (RtlGenRandom((PVOID)target, (ULONG)count) == TRUE) {
    +        success = 1;
    +      }
    +    }
    +    FreeLibrary(advapi32);
    +  }
    +
    +  return success;
    +}
    +
    +#endif /* _WIN32 */
    +
    +
    +#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
    +
     static unsigned long
     gather_time_entropy(void)
     {
    -#ifdef WIN32
    +#ifdef _WIN32
       FILETIME ft;
       GetSystemTimeAsFileTime(&ft); /* never fails */
       return ft.dwHighDateTime ^ ft.dwLowDateTime;
    @@ -709,36 +815,91 @@ gather_time_entropy(void)
       int gettimeofday_res;
     
       gettimeofday_res = gettimeofday(&tv, NULL);
    +
    +#if defined(NDEBUG)
    +  (void)gettimeofday_res;
    +#else
       assert (gettimeofday_res == 0);
    +#endif  /* defined(NDEBUG) */
     
       /* Microseconds time is <20 bits entropy */
       return tv.tv_usec;
     #endif
     }
     
    +#endif  /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
    +
    +
    +static unsigned long
    +ENTROPY_DEBUG(const char * label, unsigned long entropy) {
    +  const char * const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
    +  if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) {
    +    fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n",
    +        label,
    +        (int)sizeof(entropy) * 2, entropy,
    +        (unsigned long)sizeof(entropy));
    +  }
    +  return entropy;
    +}
    +
     static unsigned long
     generate_hash_secret_salt(XML_Parser parser)
     {
    -  /* Process ID is 0 bits entropy if attacker has local access
    -   * XML_Parser address is few bits of entropy if attacker has local access */
    -  const unsigned long entropy =
    -      gather_time_entropy() ^ getpid() ^ (unsigned long)parser;
    +  unsigned long entropy;
    +  (void)parser;
    +
    +  /* "Failproof" high quality providers: */
    +#if defined(HAVE_ARC4RANDOM_BUF)
    +  arc4random_buf(&entropy, sizeof(entropy));
    +  return ENTROPY_DEBUG("arc4random_buf", entropy);
    +#elif defined(HAVE_ARC4RANDOM)
    +  writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
    +  return ENTROPY_DEBUG("arc4random", entropy);
    +#else
    +  /* Try high quality providers first .. */
    +#ifdef _WIN32
    +  if (writeRandomBytes_RtlGenRandom((void *)&entropy, sizeof(entropy))) {
    +    return ENTROPY_DEBUG("RtlGenRandom", entropy);
    +  }
    +#elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
    +  if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
    +    return ENTROPY_DEBUG("getrandom", entropy);
    +  }
    +#endif
    +#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
    +  if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
    +    return ENTROPY_DEBUG("/dev/urandom", entropy);
    +  }
    +#endif  /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
    +  /* .. and self-made low quality for backup: */
    +
    +  /* Process ID is 0 bits entropy if attacker has local access */
    +  entropy = gather_time_entropy() ^ getpid();
     
       /* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */
       if (sizeof(unsigned long) == 4) {
    -    return entropy * 2147483647;
    +    return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
       } else {
    -    return entropy * (unsigned long)2305843009213693951;
    +    return ENTROPY_DEBUG("fallback(8)",
    +        entropy * (unsigned long)2305843009213693951ULL);
       }
    +#endif
    +}
    +
    +static unsigned long
    +get_hash_secret_salt(XML_Parser parser) {
    +  if (parser->m_parentParser != NULL)
    +    return get_hash_secret_salt(parser->m_parentParser);
    +  return parser->m_hash_secret_salt;
     }
     
     static XML_Bool  /* only valid for root parser */
     startParsing(XML_Parser parser)
     {
         /* hash functions must be initialized before setContext() is called */
    -    if (hash_secret_salt == 0)
    -      hash_secret_salt = generate_hash_secret_salt(parser);
    -    if (ns) {
    +    if (parser->m_hash_secret_salt == 0)
    +      parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
    +    if (parser->m_ns) {
           /* implicit context only set for root parser, since child
              parsers (i.e. external entity parsers) will inherit it
           */
    @@ -788,83 +949,85 @@ parserCreate(const XML_Char *encodingName,
       if (!parser)
         return parser;
     
    -  buffer = NULL;
    -  bufferLim = NULL;
    +  parser->m_buffer = NULL;
    +  parser->m_bufferLim = NULL;
     
    -  attsSize = INIT_ATTS_SIZE;
    -  atts = (ATTRIBUTE *)MALLOC(attsSize * sizeof(ATTRIBUTE));
    -  if (atts == NULL) {
    -    FREE(parser);
    +  parser->m_attsSize = INIT_ATTS_SIZE;
    +  parser->m_atts = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
    +  if (parser->m_atts == NULL) {
    +    FREE(parser, parser);
         return NULL;
       }
     #ifdef XML_ATTR_INFO
    -  attInfo = (XML_AttrInfo*)MALLOC(attsSize * sizeof(XML_AttrInfo));
    -  if (attInfo == NULL) {
    -    FREE(atts);
    -    FREE(parser);
    +  parser->m_attInfo = (XML_AttrInfo*)MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));
    +  if (parser->m_attInfo == NULL) {
    +    FREE(parser, parser->m_atts);
    +    FREE(parser, parser);
         return NULL;
       }
     #endif
    -  dataBuf = (XML_Char *)MALLOC(INIT_DATA_BUF_SIZE * sizeof(XML_Char));
    -  if (dataBuf == NULL) {
    -    FREE(atts);
    +  parser->m_dataBuf = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
    +  if (parser->m_dataBuf == NULL) {
    +    FREE(parser, parser->m_atts);
     #ifdef XML_ATTR_INFO
    -    FREE(attInfo);
    +    FREE(parser, parser->m_attInfo);
     #endif
    -    FREE(parser);
    +    FREE(parser, parser);
         return NULL;
       }
    -  dataBufEnd = dataBuf + INIT_DATA_BUF_SIZE;
    +  parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
     
       if (dtd)
    -    _dtd = dtd;
    +    parser->m_dtd = dtd;
       else {
    -    _dtd = dtdCreate(&parser->m_mem);
    -    if (_dtd == NULL) {
    -      FREE(dataBuf);
    -      FREE(atts);
    +    parser->m_dtd = dtdCreate(&parser->m_mem);
    +    if (parser->m_dtd == NULL) {
    +      FREE(parser, parser->m_dataBuf);
    +      FREE(parser, parser->m_atts);
     #ifdef XML_ATTR_INFO
    -      FREE(attInfo);
    +      FREE(parser, parser->m_attInfo);
     #endif
    -      FREE(parser);
    +      FREE(parser, parser);
           return NULL;
         }
       }
     
    -  freeBindingList = NULL;
    -  freeTagList = NULL;
    -  freeInternalEntities = NULL;
    +  parser->m_freeBindingList = NULL;
    +  parser->m_freeTagList = NULL;
    +  parser->m_freeInternalEntities = NULL;
     
    -  groupSize = 0;
    -  groupConnector = NULL;
    +  parser->m_groupSize = 0;
    +  parser->m_groupConnector = NULL;
     
    -  unknownEncodingHandler = NULL;
    -  unknownEncodingHandlerData = NULL;
    +  parser->m_unknownEncodingHandler = NULL;
    +  parser->m_unknownEncodingHandlerData = NULL;
     
    -  namespaceSeparator = ASCII_EXCL;
    -  ns = XML_FALSE;
    -  ns_triplets = XML_FALSE;
    +  parser->m_namespaceSeparator = ASCII_EXCL;
    +  parser->m_ns = XML_FALSE;
    +  parser->m_ns_triplets = XML_FALSE;
     
    -  nsAtts = NULL;
    -  nsAttsVersion = 0;
    -  nsAttsPower = 0;
    +  parser->m_nsAtts = NULL;
    +  parser->m_nsAttsVersion = 0;
    +  parser->m_nsAttsPower = 0;
     
    -  poolInit(&tempPool, &(parser->m_mem));
    -  poolInit(&temp2Pool, &(parser->m_mem));
    +  parser->m_protocolEncodingName = NULL;
    +
    +  poolInit(&parser->m_tempPool, &(parser->m_mem));
    +  poolInit(&parser->m_temp2Pool, &(parser->m_mem));
       parserInit(parser, encodingName);
     
    -  if (encodingName && !protocolEncodingName) {
    +  if (encodingName && !parser->m_protocolEncodingName) {
         XML_ParserFree(parser);
         return NULL;
       }
     
       if (nameSep) {
    -    ns = XML_TRUE;
    -    internalEncoding = XmlGetInternalEncodingNS();
    -    namespaceSeparator = *nameSep;
    +    parser->m_ns = XML_TRUE;
    +    parser->m_internalEncoding = XmlGetInternalEncodingNS();
    +    parser->m_namespaceSeparator = *nameSep;
       }
       else {
    -    internalEncoding = XmlGetInternalEncoding();
    +    parser->m_internalEncoding = XmlGetInternalEncoding();
       }
     
       return parser;
    @@ -873,85 +1036,85 @@ parserCreate(const XML_Char *encodingName,
     static void
     parserInit(XML_Parser parser, const XML_Char *encodingName)
     {
    -  processor = prologInitProcessor;
    -  XmlPrologStateInit(&prologState);
    -  protocolEncodingName = (encodingName != NULL
    -                          ? poolCopyString(&tempPool, encodingName)
    -                          : NULL);
    -  curBase = NULL;
    -  XmlInitEncoding(&initEncoding, &encoding, 0);
    -  userData = NULL;
    -  handlerArg = NULL;
    -  startElementHandler = NULL;
    -  endElementHandler = NULL;
    -  characterDataHandler = NULL;
    -  processingInstructionHandler = NULL;
    -  commentHandler = NULL;
    -  startCdataSectionHandler = NULL;
    -  endCdataSectionHandler = NULL;
    -  defaultHandler = NULL;
    -  startDoctypeDeclHandler = NULL;
    -  endDoctypeDeclHandler = NULL;
    -  unparsedEntityDeclHandler = NULL;
    -  notationDeclHandler = NULL;
    -  startNamespaceDeclHandler = NULL;
    -  endNamespaceDeclHandler = NULL;
    -  notStandaloneHandler = NULL;
    -  externalEntityRefHandler = NULL;
    -  externalEntityRefHandlerArg = parser;
    -  skippedEntityHandler = NULL;
    -  elementDeclHandler = NULL;
    -  attlistDeclHandler = NULL;
    -  entityDeclHandler = NULL;
    -  xmlDeclHandler = NULL;
    -  bufferPtr = buffer;
    -  bufferEnd = buffer;
    -  parseEndByteIndex = 0;
    -  parseEndPtr = NULL;
    -  declElementType = NULL;
    -  declAttributeId = NULL;
    -  declEntity = NULL;
    -  doctypeName = NULL;
    -  doctypeSysid = NULL;
    -  doctypePubid = NULL;
    -  declAttributeType = NULL;
    -  declNotationName = NULL;
    -  declNotationPublicId = NULL;
    -  declAttributeIsCdata = XML_FALSE;
    -  declAttributeIsId = XML_FALSE;
    -  memset(&position, 0, sizeof(POSITION));
    -  errorCode = XML_ERROR_NONE;
    -  eventPtr = NULL;
    -  eventEndPtr = NULL;
    -  positionPtr = NULL;
    -  openInternalEntities = NULL;
    -  defaultExpandInternalEntities = XML_TRUE;
    -  tagLevel = 0;
    -  tagStack = NULL;
    -  inheritedBindings = NULL;
    -  nSpecifiedAtts = 0;
    -  unknownEncodingMem = NULL;
    -  unknownEncodingRelease = NULL;
    -  unknownEncodingData = NULL;
    -  parentParser = NULL;
    -  ps_parsing = XML_INITIALIZED;
    +  parser->m_processor = prologInitProcessor;
    +  XmlPrologStateInit(&parser->m_prologState);
    +  if (encodingName != NULL) {
    +    parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
    +  }
    +  parser->m_curBase = NULL;
    +  XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
    +  parser->m_userData = NULL;
    +  parser->m_handlerArg = NULL;
    +  parser->m_startElementHandler = NULL;
    +  parser->m_endElementHandler = NULL;
    +  parser->m_characterDataHandler = NULL;
    +  parser->m_processingInstructionHandler = NULL;
    +  parser->m_commentHandler = NULL;
    +  parser->m_startCdataSectionHandler = NULL;
    +  parser->m_endCdataSectionHandler = NULL;
    +  parser->m_defaultHandler = NULL;
    +  parser->m_startDoctypeDeclHandler = NULL;
    +  parser->m_endDoctypeDeclHandler = NULL;
    +  parser->m_unparsedEntityDeclHandler = NULL;
    +  parser->m_notationDeclHandler = NULL;
    +  parser->m_startNamespaceDeclHandler = NULL;
    +  parser->m_endNamespaceDeclHandler = NULL;
    +  parser->m_notStandaloneHandler = NULL;
    +  parser->m_externalEntityRefHandler = NULL;
    +  parser->m_externalEntityRefHandlerArg = parser;
    +  parser->m_skippedEntityHandler = NULL;
    +  parser->m_elementDeclHandler = NULL;
    +  parser->m_attlistDeclHandler = NULL;
    +  parser->m_entityDeclHandler = NULL;
    +  parser->m_xmlDeclHandler = NULL;
    +  parser->m_bufferPtr = parser->m_buffer;
    +  parser->m_bufferEnd = parser->m_buffer;
    +  parser->m_parseEndByteIndex = 0;
    +  parser->m_parseEndPtr = NULL;
    +  parser->m_declElementType = NULL;
    +  parser->m_declAttributeId = NULL;
    +  parser->m_declEntity = NULL;
    +  parser->m_doctypeName = NULL;
    +  parser->m_doctypeSysid = NULL;
    +  parser->m_doctypePubid = NULL;
    +  parser->m_declAttributeType = NULL;
    +  parser->m_declNotationName = NULL;
    +  parser->m_declNotationPublicId = NULL;
    +  parser->m_declAttributeIsCdata = XML_FALSE;
    +  parser->m_declAttributeIsId = XML_FALSE;
    +  memset(&parser->m_position, 0, sizeof(POSITION));
    +  parser->m_errorCode = XML_ERROR_NONE;
    +  parser->m_eventPtr = NULL;
    +  parser->m_eventEndPtr = NULL;
    +  parser->m_positionPtr = NULL;
    +  parser->m_openInternalEntities = NULL;
    +  parser->m_defaultExpandInternalEntities = XML_TRUE;
    +  parser->m_tagLevel = 0;
    +  parser->m_tagStack = NULL;
    +  parser->m_inheritedBindings = NULL;
    +  parser->m_nSpecifiedAtts = 0;
    +  parser->m_unknownEncodingMem = NULL;
    +  parser->m_unknownEncodingRelease = NULL;
    +  parser->m_unknownEncodingData = NULL;
    +  parser->m_parentParser = NULL;
    +  parser->m_parsingStatus.parsing = XML_INITIALIZED;
     #ifdef XML_DTD
    -  isParamEntity = XML_FALSE;
    -  useForeignDTD = XML_FALSE;
    -  paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
    +  parser->m_isParamEntity = XML_FALSE;
    +  parser->m_useForeignDTD = XML_FALSE;
    +  parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
     #endif
    -  hash_secret_salt = 0;
    +  parser->m_hash_secret_salt = 0;
     }
     
    -/* moves list of bindings to freeBindingList */
    +/* moves list of bindings to m_freeBindingList */
     static void FASTCALL
     moveToFreeBindingList(XML_Parser parser, BINDING *bindings)
     {
       while (bindings) {
         BINDING *b = bindings;
         bindings = bindings->nextTagBinding;
    -    b->nextTagBinding = freeBindingList;
    -    freeBindingList = b;
    +    b->nextTagBinding = parser->m_freeBindingList;
    +    parser->m_freeBindingList = b;
       }
     }
     
    @@ -960,51 +1123,65 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName)
     {
       TAG *tStk;
       OPEN_INTERNAL_ENTITY *openEntityList;
    -  if (parentParser)
    +
    +  if (parser == NULL)
    +      return XML_FALSE;
    +
    +  if (parser->m_parentParser)
         return XML_FALSE;
    -  /* move tagStack to freeTagList */
    -  tStk = tagStack;
    +  /* move m_tagStack to m_freeTagList */
    +  tStk = parser->m_tagStack;
       while (tStk) {
         TAG *tag = tStk;
         tStk = tStk->parent;
    -    tag->parent = freeTagList;
    +    tag->parent = parser->m_freeTagList;
         moveToFreeBindingList(parser, tag->bindings);
         tag->bindings = NULL;
    -    freeTagList = tag;
    +    parser->m_freeTagList = tag;
       }
    -  /* move openInternalEntities to freeInternalEntities */
    -  openEntityList = openInternalEntities;
    +  /* move m_openInternalEntities to m_freeInternalEntities */
    +  openEntityList = parser->m_openInternalEntities;
       while (openEntityList) {
         OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
         openEntityList = openEntity->next;
    -    openEntity->next = freeInternalEntities;
    -    freeInternalEntities = openEntity;
    +    openEntity->next = parser->m_freeInternalEntities;
    +    parser->m_freeInternalEntities = openEntity;
       }
    -  moveToFreeBindingList(parser, inheritedBindings);
    -  FREE(unknownEncodingMem);
    -  if (unknownEncodingRelease)
    -    unknownEncodingRelease(unknownEncodingData);
    -  poolClear(&tempPool);
    -  poolClear(&temp2Pool);
    +  moveToFreeBindingList(parser, parser->m_inheritedBindings);
    +  FREE(parser, parser->m_unknownEncodingMem);
    +  if (parser->m_unknownEncodingRelease)
    +    parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
    +  poolClear(&parser->m_tempPool);
    +  poolClear(&parser->m_temp2Pool);
    +  FREE(parser, (void *)parser->m_protocolEncodingName);
    +  parser->m_protocolEncodingName = NULL;
       parserInit(parser, encodingName);
    -  dtdReset(_dtd, &parser->m_mem);
    +  dtdReset(parser->m_dtd, &parser->m_mem);
       return XML_TRUE;
     }
     
     enum XML_Status XMLCALL
     XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName)
     {
    +  if (parser == NULL)
    +      return XML_STATUS_ERROR;
       /* Block after XML_Parse()/XML_ParseBuffer() has been called.
          XXX There's no way for the caller to determine which of the
          XXX possible error cases caused the XML_STATUS_ERROR return.
       */
    -  if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
    +  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
         return XML_STATUS_ERROR;
    +
    +  /* Get rid of any previous encoding name */
    +  FREE(parser, (void *)parser->m_protocolEncodingName);
    +
       if (encodingName == NULL)
    -    protocolEncodingName = NULL;
    +    /* No new encoding name */
    +    parser->m_protocolEncodingName = NULL;
       else {
    -    protocolEncodingName = poolCopyString(&tempPool, encodingName);
    -    if (!protocolEncodingName)
    +    /* Copy the new encoding name into allocated memory */
    +    parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
    +    if (!parser->m_protocolEncodingName)
           return XML_STATUS_ERROR;
       }
       return XML_STATUS_OK;
    @@ -1017,52 +1194,88 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser,
     {
       XML_Parser parser = oldParser;
       DTD *newDtd = NULL;
    -  DTD *oldDtd = _dtd;
    -  XML_StartElementHandler oldStartElementHandler = startElementHandler;
    -  XML_EndElementHandler oldEndElementHandler = endElementHandler;
    -  XML_CharacterDataHandler oldCharacterDataHandler = characterDataHandler;
    -  XML_ProcessingInstructionHandler oldProcessingInstructionHandler
    -      = processingInstructionHandler;
    -  XML_CommentHandler oldCommentHandler = commentHandler;
    -  XML_StartCdataSectionHandler oldStartCdataSectionHandler
    -      = startCdataSectionHandler;
    -  XML_EndCdataSectionHandler oldEndCdataSectionHandler
    -      = endCdataSectionHandler;
    -  XML_DefaultHandler oldDefaultHandler = defaultHandler;
    -  XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler
    -      = unparsedEntityDeclHandler;
    -  XML_NotationDeclHandler oldNotationDeclHandler = notationDeclHandler;
    -  XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler
    -      = startNamespaceDeclHandler;
    -  XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler
    -      = endNamespaceDeclHandler;
    -  XML_NotStandaloneHandler oldNotStandaloneHandler = notStandaloneHandler;
    -  XML_ExternalEntityRefHandler oldExternalEntityRefHandler
    -      = externalEntityRefHandler;
    -  XML_SkippedEntityHandler oldSkippedEntityHandler = skippedEntityHandler;
    -  XML_UnknownEncodingHandler oldUnknownEncodingHandler
    -      = unknownEncodingHandler;
    -  XML_ElementDeclHandler oldElementDeclHandler = elementDeclHandler;
    -  XML_AttlistDeclHandler oldAttlistDeclHandler = attlistDeclHandler;
    -  XML_EntityDeclHandler oldEntityDeclHandler = entityDeclHandler;
    -  XML_XmlDeclHandler oldXmlDeclHandler = xmlDeclHandler;
    -  ELEMENT_TYPE * oldDeclElementType = declElementType;
    +  DTD *oldDtd;
    +  XML_StartElementHandler oldStartElementHandler;
    +  XML_EndElementHandler oldEndElementHandler;
    +  XML_CharacterDataHandler oldCharacterDataHandler;
    +  XML_ProcessingInstructionHandler oldProcessingInstructionHandler;
    +  XML_CommentHandler oldCommentHandler;
    +  XML_StartCdataSectionHandler oldStartCdataSectionHandler;
    +  XML_EndCdataSectionHandler oldEndCdataSectionHandler;
    +  XML_DefaultHandler oldDefaultHandler;
    +  XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;
    +  XML_NotationDeclHandler oldNotationDeclHandler;
    +  XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;
    +  XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;
    +  XML_NotStandaloneHandler oldNotStandaloneHandler;
    +  XML_ExternalEntityRefHandler oldExternalEntityRefHandler;
    +  XML_SkippedEntityHandler oldSkippedEntityHandler;
    +  XML_UnknownEncodingHandler oldUnknownEncodingHandler;
    +  XML_ElementDeclHandler oldElementDeclHandler;
    +  XML_AttlistDeclHandler oldAttlistDeclHandler;
    +  XML_EntityDeclHandler oldEntityDeclHandler;
    +  XML_XmlDeclHandler oldXmlDeclHandler;
    +  ELEMENT_TYPE * oldDeclElementType;
     
    -  void *oldUserData = userData;
    -  void *oldHandlerArg = handlerArg;
    -  XML_Bool oldDefaultExpandInternalEntities = defaultExpandInternalEntities;
    -  XML_Parser oldExternalEntityRefHandlerArg = externalEntityRefHandlerArg;
    +  void *oldUserData;
    +  void *oldHandlerArg;
    +  XML_Bool oldDefaultExpandInternalEntities;
    +  XML_Parser oldExternalEntityRefHandlerArg;
     #ifdef XML_DTD
    -  enum XML_ParamEntityParsing oldParamEntityParsing = paramEntityParsing;
    -  int oldInEntityValue = prologState.inEntityValue;
    +  enum XML_ParamEntityParsing oldParamEntityParsing;
    +  int oldInEntityValue;
     #endif
    -  XML_Bool oldns_triplets = ns_triplets;
    +  XML_Bool oldns_triplets;
       /* Note that the new parser shares the same hash secret as the old
          parser, so that dtdCopy and copyEntityTable can lookup values
          from hash tables associated with either parser without us having
          to worry which hash secrets each table has.
       */
    -  unsigned long oldhash_secret_salt = hash_secret_salt;
    +  unsigned long oldhash_secret_salt;
    +
    +  /* Validate the oldParser parameter before we pull everything out of it */
    +  if (oldParser == NULL)
    +    return NULL;
    +
    +  /* Stash the original parser contents on the stack */
    +  oldDtd = parser->m_dtd;
    +  oldStartElementHandler = parser->m_startElementHandler;
    +  oldEndElementHandler = parser->m_endElementHandler;
    +  oldCharacterDataHandler = parser->m_characterDataHandler;
    +  oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
    +  oldCommentHandler = parser->m_commentHandler;
    +  oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
    +  oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
    +  oldDefaultHandler = parser->m_defaultHandler;
    +  oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
    +  oldNotationDeclHandler = parser->m_notationDeclHandler;
    +  oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
    +  oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
    +  oldNotStandaloneHandler = parser->m_notStandaloneHandler;
    +  oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
    +  oldSkippedEntityHandler = parser->m_skippedEntityHandler;
    +  oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
    +  oldElementDeclHandler = parser->m_elementDeclHandler;
    +  oldAttlistDeclHandler = parser->m_attlistDeclHandler;
    +  oldEntityDeclHandler = parser->m_entityDeclHandler;
    +  oldXmlDeclHandler = parser->m_xmlDeclHandler;
    +  oldDeclElementType = parser->m_declElementType;
    +
    +  oldUserData = parser->m_userData;
    +  oldHandlerArg = parser->m_handlerArg;
    +  oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
    +  oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
    +#ifdef XML_DTD
    +  oldParamEntityParsing = parser->m_paramEntityParsing;
    +  oldInEntityValue = parser->m_prologState.inEntityValue;
    +#endif
    +  oldns_triplets = parser->m_ns_triplets;
    +  /* Note that the new parser shares the same hash secret as the old
    +     parser, so that dtdCopy and copyEntityTable can lookup values
    +     from hash tables associated with either parser without us having
    +     to worry which hash secrets each table has.
    +  */
    +  oldhash_secret_salt = parser->m_hash_secret_salt;
     
     #ifdef XML_DTD
       if (!context)
    @@ -1074,9 +1287,9 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser,
          here.  This makes this function more painful to follow than it
          would be otherwise.
       */
    -  if (ns) {
    +  if (parser->m_ns) {
         XML_Char tmp[2];
    -    *tmp = namespaceSeparator;
    +    *tmp = parser->m_namespaceSeparator;
         parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
       }
       else {
    @@ -1086,62 +1299,62 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser,
       if (!parser)
         return NULL;
     
    -  startElementHandler = oldStartElementHandler;
    -  endElementHandler = oldEndElementHandler;
    -  characterDataHandler = oldCharacterDataHandler;
    -  processingInstructionHandler = oldProcessingInstructionHandler;
    -  commentHandler = oldCommentHandler;
    -  startCdataSectionHandler = oldStartCdataSectionHandler;
    -  endCdataSectionHandler = oldEndCdataSectionHandler;
    -  defaultHandler = oldDefaultHandler;
    -  unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
    -  notationDeclHandler = oldNotationDeclHandler;
    -  startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
    -  endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
    -  notStandaloneHandler = oldNotStandaloneHandler;
    -  externalEntityRefHandler = oldExternalEntityRefHandler;
    -  skippedEntityHandler = oldSkippedEntityHandler;
    -  unknownEncodingHandler = oldUnknownEncodingHandler;
    -  elementDeclHandler = oldElementDeclHandler;
    -  attlistDeclHandler = oldAttlistDeclHandler;
    -  entityDeclHandler = oldEntityDeclHandler;
    -  xmlDeclHandler = oldXmlDeclHandler;
    -  declElementType = oldDeclElementType;
    -  userData = oldUserData;
    +  parser->m_startElementHandler = oldStartElementHandler;
    +  parser->m_endElementHandler = oldEndElementHandler;
    +  parser->m_characterDataHandler = oldCharacterDataHandler;
    +  parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
    +  parser->m_commentHandler = oldCommentHandler;
    +  parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
    +  parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
    +  parser->m_defaultHandler = oldDefaultHandler;
    +  parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
    +  parser->m_notationDeclHandler = oldNotationDeclHandler;
    +  parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
    +  parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
    +  parser->m_notStandaloneHandler = oldNotStandaloneHandler;
    +  parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
    +  parser->m_skippedEntityHandler = oldSkippedEntityHandler;
    +  parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
    +  parser->m_elementDeclHandler = oldElementDeclHandler;
    +  parser->m_attlistDeclHandler = oldAttlistDeclHandler;
    +  parser->m_entityDeclHandler = oldEntityDeclHandler;
    +  parser->m_xmlDeclHandler = oldXmlDeclHandler;
    +  parser->m_declElementType = oldDeclElementType;
    +  parser->m_userData = oldUserData;
       if (oldUserData == oldHandlerArg)
    -    handlerArg = userData;
    +    parser->m_handlerArg = parser->m_userData;
       else
    -    handlerArg = parser;
    +    parser->m_handlerArg = parser;
       if (oldExternalEntityRefHandlerArg != oldParser)
    -    externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
    -  defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
    -  ns_triplets = oldns_triplets;
    -  hash_secret_salt = oldhash_secret_salt;
    -  parentParser = oldParser;
    +    parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
    +  parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
    +  parser->m_ns_triplets = oldns_triplets;
    +  parser->m_hash_secret_salt = oldhash_secret_salt;
    +  parser->m_parentParser = oldParser;
     #ifdef XML_DTD
    -  paramEntityParsing = oldParamEntityParsing;
    -  prologState.inEntityValue = oldInEntityValue;
    +  parser->m_paramEntityParsing = oldParamEntityParsing;
    +  parser->m_prologState.inEntityValue = oldInEntityValue;
       if (context) {
     #endif /* XML_DTD */
    -    if (!dtdCopy(oldParser, _dtd, oldDtd, &parser->m_mem)
    +    if (!dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
           || !setContext(parser, context)) {
           XML_ParserFree(parser);
           return NULL;
         }
    -    processor = externalEntityInitProcessor;
    +    parser->m_processor = externalEntityInitProcessor;
     #ifdef XML_DTD
       }
       else {
    -    /* The DTD instance referenced by _dtd is shared between the document's
    +    /* The DTD instance referenced by parser->m_dtd is shared between the document's
            root parser and external PE parsers, therefore one does not need to
            call setContext. In addition, one also *must* not call setContext,
            because this would overwrite existing prefix->binding pointers in
    -       _dtd with ones that get destroyed with the external PE parser.
    +       parser->m_dtd with ones that get destroyed with the external PE parser.
            This would leave those prefixes with dangling pointers.
         */
    -    isParamEntity = XML_TRUE;
    -    XmlPrologStateInitExternalEntity(&prologState);
    -    processor = externalParEntInitProcessor;
    +    parser->m_isParamEntity = XML_TRUE;
    +    XmlPrologStateInitExternalEntity(&parser->m_prologState);
    +    parser->m_processor = externalParEntInitProcessor;
       }
     #endif /* XML_DTD */
       return parser;
    @@ -1155,8 +1368,8 @@ destroyBindings(BINDING *bindings, XML_Parser parser)
         if (!b)
           break;
         bindings = b->nextTagBinding;
    -    FREE(b->uri);
    -    FREE(b);
    +    FREE(parser, b->uri);
    +    FREE(parser, b);
       }
     }
     
    @@ -1167,78 +1380,82 @@ XML_ParserFree(XML_Parser parser)
       OPEN_INTERNAL_ENTITY *entityList;
       if (parser == NULL)
         return;
    -  /* free tagStack and freeTagList */
    -  tagList = tagStack;
    +  /* free m_tagStack and m_freeTagList */
    +  tagList = parser->m_tagStack;
       for (;;) {
         TAG *p;
         if (tagList == NULL) {
    -      if (freeTagList == NULL)
    +      if (parser->m_freeTagList == NULL)
             break;
    -      tagList = freeTagList;
    -      freeTagList = NULL;
    +      tagList = parser->m_freeTagList;
    +      parser->m_freeTagList = NULL;
         }
         p = tagList;
         tagList = tagList->parent;
    -    FREE(p->buf);
    +    FREE(parser, p->buf);
         destroyBindings(p->bindings, parser);
    -    FREE(p);
    +    FREE(parser, p);
       }
    -  /* free openInternalEntities and freeInternalEntities */
    -  entityList = openInternalEntities;
    +  /* free m_openInternalEntities and m_freeInternalEntities */
    +  entityList = parser->m_openInternalEntities;
       for (;;) {
         OPEN_INTERNAL_ENTITY *openEntity;
         if (entityList == NULL) {
    -      if (freeInternalEntities == NULL)
    +      if (parser->m_freeInternalEntities == NULL)
             break;
    -      entityList = freeInternalEntities;
    -      freeInternalEntities = NULL;
    +      entityList = parser->m_freeInternalEntities;
    +      parser->m_freeInternalEntities = NULL;
         }
         openEntity = entityList;
         entityList = entityList->next;
    -    FREE(openEntity);
    +    FREE(parser, openEntity);
       }
     
    -  destroyBindings(freeBindingList, parser);
    -  destroyBindings(inheritedBindings, parser);
    -  poolDestroy(&tempPool);
    -  poolDestroy(&temp2Pool);
    +  destroyBindings(parser->m_freeBindingList, parser);
    +  destroyBindings(parser->m_inheritedBindings, parser);
    +  poolDestroy(&parser->m_tempPool);
    +  poolDestroy(&parser->m_temp2Pool);
    +  FREE(parser, (void *)parser->m_protocolEncodingName);
     #ifdef XML_DTD
       /* external parameter entity parsers share the DTD structure
          parser->m_dtd with the root parser, so we must not destroy it
       */
    -  if (!isParamEntity && _dtd)
    +  if (!parser->m_isParamEntity && parser->m_dtd)
     #else
    -  if (_dtd)
    +  if (parser->m_dtd)
     #endif /* XML_DTD */
    -    dtdDestroy(_dtd, (XML_Bool)!parentParser, &parser->m_mem);
    -  FREE((void *)atts);
    +    dtdDestroy(parser->m_dtd, (XML_Bool)!parser->m_parentParser, &parser->m_mem);
    +  FREE(parser, (void *)parser->m_atts);
     #ifdef XML_ATTR_INFO
    -  FREE((void *)attInfo);
    +  FREE(parser, (void *)parser->m_attInfo);
     #endif
    -  FREE(groupConnector);
    -  FREE(buffer);
    -  FREE(dataBuf);
    -  FREE(nsAtts);
    -  FREE(unknownEncodingMem);
    -  if (unknownEncodingRelease)
    -    unknownEncodingRelease(unknownEncodingData);
    -  FREE(parser);
    +  FREE(parser, parser->m_groupConnector);
    +  FREE(parser, parser->m_buffer);
    +  FREE(parser, parser->m_dataBuf);
    +  FREE(parser, parser->m_nsAtts);
    +  FREE(parser, parser->m_unknownEncodingMem);
    +  if (parser->m_unknownEncodingRelease)
    +    parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
    +  FREE(parser, parser);
     }
     
     void XMLCALL
     XML_UseParserAsHandlerArg(XML_Parser parser)
     {
    -  handlerArg = parser;
    +  if (parser != NULL)
    +    parser->m_handlerArg = parser;
     }
     
     enum XML_Error XMLCALL
     XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD)
     {
    +  if (parser == NULL)
    +    return XML_ERROR_INVALID_ARGUMENT;
     #ifdef XML_DTD
       /* block after XML_Parse()/XML_ParseBuffer() has been called */
    -  if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
    +  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
         return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
    -  useForeignDTD = useDTD;
    +  parser->m_useForeignDTD = useDTD;
       return XML_ERROR_NONE;
     #else
       return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
    @@ -1248,58 +1465,72 @@ XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD)
     void XMLCALL
     XML_SetReturnNSTriplet(XML_Parser parser, int do_nst)
     {
    -  /* block after XML_Parse()/XML_ParseBuffer() has been called */
    -  if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
    +  if (parser == NULL)
         return;
    -  ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
    +  /* block after XML_Parse()/XML_ParseBuffer() has been called */
    +  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
    +    return;
    +  parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
     }
     
     void XMLCALL
     XML_SetUserData(XML_Parser parser, void *p)
     {
    -  if (handlerArg == userData)
    -    handlerArg = userData = p;
    +  if (parser == NULL)
    +    return;
    +  if (parser->m_handlerArg == parser->m_userData)
    +    parser->m_handlerArg = parser->m_userData = p;
       else
    -    userData = p;
    +    parser->m_userData = p;
     }
     
     enum XML_Status XMLCALL
     XML_SetBase(XML_Parser parser, const XML_Char *p)
     {
    +  if (parser == NULL)
    +    return XML_STATUS_ERROR;
       if (p) {
    -    p = poolCopyString(&_dtd->pool, p);
    +    p = poolCopyString(&parser->m_dtd->pool, p);
         if (!p)
           return XML_STATUS_ERROR;
    -    curBase = p;
    +    parser->m_curBase = p;
       }
       else
    -    curBase = NULL;
    +    parser->m_curBase = NULL;
       return XML_STATUS_OK;
     }
     
     const XML_Char * XMLCALL
     XML_GetBase(XML_Parser parser)
     {
    -  return curBase;
    +  if (parser == NULL)
    +    return NULL;
    +  return parser->m_curBase;
     }
     
     int XMLCALL
     XML_GetSpecifiedAttributeCount(XML_Parser parser)
     {
    -  return nSpecifiedAtts;
    +  if (parser == NULL)
    +    return -1;
    +  return parser->m_nSpecifiedAtts;
     }
     
     int XMLCALL
     XML_GetIdAttributeIndex(XML_Parser parser)
     {
    -  return idAttIndex;
    +  if (parser == NULL)
    +    return -1;
    +  return parser->m_idAttIndex;
     }
     
     #ifdef XML_ATTR_INFO
     const XML_AttrInfo * XMLCALL
     XML_GetAttributeInfo(XML_Parser parser)
     {
    -  return attInfo;
    +  if (parser == NULL)
    +    return NULL;
    +  return parser->m_attInfo;
     }
     #endif
     
    @@ -1308,41 +1539,48 @@ XML_SetElementHandler(XML_Parser parser,
                           XML_StartElementHandler start,
                           XML_EndElementHandler end)
     {
    -  startElementHandler = start;
    -  endElementHandler = end;
    +  if (parser == NULL)
    +    return;
    +  parser->m_startElementHandler = start;
    +  parser->m_endElementHandler = end;
     }
     
     void XMLCALL
     XML_SetStartElementHandler(XML_Parser parser,
                                XML_StartElementHandler start) {
    -  startElementHandler = start;
    +  if (parser != NULL)
    +    parser->m_startElementHandler = start;
     }
     
     void XMLCALL
     XML_SetEndElementHandler(XML_Parser parser,
                              XML_EndElementHandler end) {
    -  endElementHandler = end;
    +  if (parser != NULL)
    +    parser->m_endElementHandler = end;
     }
     
     void XMLCALL
     XML_SetCharacterDataHandler(XML_Parser parser,
                                 XML_CharacterDataHandler handler)
     {
    -  characterDataHandler = handler;
    +  if (parser != NULL)
    +    parser->m_characterDataHandler = handler;
     }
     
     void XMLCALL
     XML_SetProcessingInstructionHandler(XML_Parser parser,
                                         XML_ProcessingInstructionHandler handler)
     {
    -  processingInstructionHandler = handler;
    +  if (parser != NULL)
    +    parser->m_processingInstructionHandler = handler;
     }
     
     void XMLCALL
     XML_SetCommentHandler(XML_Parser parser,
                           XML_CommentHandler handler)
     {
    -  commentHandler = handler;
    +  if (parser != NULL)
    +    parser->m_commentHandler = handler;
     }
     
     void XMLCALL
    @@ -1350,36 +1588,44 @@ XML_SetCdataSectionHandler(XML_Parser parser,
                                XML_StartCdataSectionHandler start,
                                XML_EndCdataSectionHandler end)
     {
    -  startCdataSectionHandler = start;
    -  endCdataSectionHandler = end;
    +  if (parser == NULL)
    +    return;
    +  parser->m_startCdataSectionHandler = start;
    +  parser->m_endCdataSectionHandler = end;
     }
     
     void XMLCALL
     XML_SetStartCdataSectionHandler(XML_Parser parser,
                                     XML_StartCdataSectionHandler start) {
    -  startCdataSectionHandler = start;
    +  if (parser != NULL)
    +    parser->m_startCdataSectionHandler = start;
     }
     
     void XMLCALL
     XML_SetEndCdataSectionHandler(XML_Parser parser,
                                   XML_EndCdataSectionHandler end) {
    -  endCdataSectionHandler = end;
    +  if (parser != NULL)
    +    parser->m_endCdataSectionHandler = end;
     }
     
     void XMLCALL
     XML_SetDefaultHandler(XML_Parser parser,
                           XML_DefaultHandler handler)
     {
    -  defaultHandler = handler;
    -  defaultExpandInternalEntities = XML_FALSE;
    +  if (parser == NULL)
    +    return;
    +  parser->m_defaultHandler = handler;
    +  parser->m_defaultExpandInternalEntities = XML_FALSE;
     }
     
     void XMLCALL
     XML_SetDefaultHandlerExpand(XML_Parser parser,
                                 XML_DefaultHandler handler)
     {
    -  defaultHandler = handler;
    -  defaultExpandInternalEntities = XML_TRUE;
    +  if (parser == NULL)
    +    return;
    +  parser->m_defaultHandler = handler;
    +  parser->m_defaultExpandInternalEntities = XML_TRUE;
     }
     
     void XMLCALL
    @@ -1387,34 +1633,40 @@ XML_SetDoctypeDeclHandler(XML_Parser parser,
                               XML_StartDoctypeDeclHandler start,
                               XML_EndDoctypeDeclHandler end)
     {
    -  startDoctypeDeclHandler = start;
    -  endDoctypeDeclHandler = end;
    +  if (parser == NULL)
    +    return;
    +  parser->m_startDoctypeDeclHandler = start;
    +  parser->m_endDoctypeDeclHandler = end;
     }
     
     void XMLCALL
     XML_SetStartDoctypeDeclHandler(XML_Parser parser,
                                    XML_StartDoctypeDeclHandler start) {
    -  startDoctypeDeclHandler = start;
    +  if (parser != NULL)
    +    parser->m_startDoctypeDeclHandler = start;
     }
     
     void XMLCALL
     XML_SetEndDoctypeDeclHandler(XML_Parser parser,
                                  XML_EndDoctypeDeclHandler end) {
    -  endDoctypeDeclHandler = end;
    +  if (parser != NULL)
    +    parser->m_endDoctypeDeclHandler = end;
     }
     
     void XMLCALL
     XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
                                      XML_UnparsedEntityDeclHandler handler)
     {
    -  unparsedEntityDeclHandler = handler;
    +  if (parser != NULL)
    +    parser->m_unparsedEntityDeclHandler = handler;
     }
     
     void XMLCALL
     XML_SetNotationDeclHandler(XML_Parser parser,
                                XML_NotationDeclHandler handler)
     {
    -  notationDeclHandler = handler;
    +  if (parser != NULL)
    +    parser->m_notationDeclHandler = handler;
     }
     
     void XMLCALL
    @@ -1422,50 +1674,59 @@ XML_SetNamespaceDeclHandler(XML_Parser parser,
                                 XML_StartNamespaceDeclHandler start,
                                 XML_EndNamespaceDeclHandler end)
     {
    -  startNamespaceDeclHandler = start;
    -  endNamespaceDeclHandler = end;
    +  if (parser == NULL)
    +    return;
    +  parser->m_startNamespaceDeclHandler = start;
    +  parser->m_endNamespaceDeclHandler = end;
     }
     
     void XMLCALL
     XML_SetStartNamespaceDeclHandler(XML_Parser parser,
                                      XML_StartNamespaceDeclHandler start) {
    -  startNamespaceDeclHandler = start;
    +  if (parser != NULL)
    +    parser->m_startNamespaceDeclHandler = start;
     }
     
     void XMLCALL
     XML_SetEndNamespaceDeclHandler(XML_Parser parser,
                                    XML_EndNamespaceDeclHandler end) {
    -  endNamespaceDeclHandler = end;
    +  if (parser != NULL)
    +    parser->m_endNamespaceDeclHandler = end;
     }
     
     void XMLCALL
     XML_SetNotStandaloneHandler(XML_Parser parser,
                                 XML_NotStandaloneHandler handler)
     {
    -  notStandaloneHandler = handler;
    +  if (parser != NULL)
    +    parser->m_notStandaloneHandler = handler;
     }
     
     void XMLCALL
     XML_SetExternalEntityRefHandler(XML_Parser parser,
                                     XML_ExternalEntityRefHandler handler)
     {
    -  externalEntityRefHandler = handler;
    +  if (parser != NULL)
    +    parser->m_externalEntityRefHandler = handler;
     }
     
     void XMLCALL
     XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg)
     {
    +  if (parser == NULL)
    +    return;
       if (arg)
    -    externalEntityRefHandlerArg = (XML_Parser)arg;
    +    parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
       else
    -    externalEntityRefHandlerArg = parser;
    +    parser->m_externalEntityRefHandlerArg = parser;
     }
     
     void XMLCALL
     XML_SetSkippedEntityHandler(XML_Parser parser,
                                 XML_SkippedEntityHandler handler)
     {
    -  skippedEntityHandler = handler;
    +  if (parser != NULL)
    +    parser->m_skippedEntityHandler = handler;
     }
     
     void XMLCALL
    @@ -1473,46 +1734,54 @@ XML_SetUnknownEncodingHandler(XML_Parser parser,
                                   XML_UnknownEncodingHandler handler,
                                   void *data)
     {
    -  unknownEncodingHandler = handler;
    -  unknownEncodingHandlerData = data;
    +  if (parser == NULL)
    +    return;
    +  parser->m_unknownEncodingHandler = handler;
    +  parser->m_unknownEncodingHandlerData = data;
     }
     
     void XMLCALL
     XML_SetElementDeclHandler(XML_Parser parser,
                               XML_ElementDeclHandler eldecl)
     {
    -  elementDeclHandler = eldecl;
    +  if (parser != NULL)
    +    parser->m_elementDeclHandler = eldecl;
     }
     
     void XMLCALL
     XML_SetAttlistDeclHandler(XML_Parser parser,
                               XML_AttlistDeclHandler attdecl)
     {
    -  attlistDeclHandler = attdecl;
    +  if (parser != NULL)
    +    parser->m_attlistDeclHandler = attdecl;
     }
     
     void XMLCALL
     XML_SetEntityDeclHandler(XML_Parser parser,
                              XML_EntityDeclHandler handler)
     {
    -  entityDeclHandler = handler;
    +  if (parser != NULL)
    +    parser->m_entityDeclHandler = handler;
     }
     
     void XMLCALL
     XML_SetXmlDeclHandler(XML_Parser parser,
                           XML_XmlDeclHandler handler) {
    -  xmlDeclHandler = handler;
    +  if (parser != NULL)
    +    parser->m_xmlDeclHandler = handler;
     }
     
     int XMLCALL
     XML_SetParamEntityParsing(XML_Parser parser,
                               enum XML_ParamEntityParsing peParsing)
     {
    +  if (parser == NULL)
    +    return 0;
       /* block after XML_Parse()/XML_ParseBuffer() has been called */
    -  if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
    +  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
         return 0;
     #ifdef XML_DTD
    -  paramEntityParsing = peParsing;
    +  parser->m_paramEntityParsing = peParsing;
       return 1;
     #else
       return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
    @@ -1523,88 +1792,118 @@ int XMLCALL
     XML_SetHashSalt(XML_Parser parser,
                     unsigned long hash_salt)
     {
    -  /* block after XML_Parse()/XML_ParseBuffer() has been called */
    -  if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
    +  if (parser == NULL)
         return 0;
    -  hash_secret_salt = hash_salt;
    +  if (parser->m_parentParser)
    +    return XML_SetHashSalt(parser->m_parentParser, hash_salt);
    +  /* block after XML_Parse()/XML_ParseBuffer() has been called */
    +  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
    +    return 0;
    +  parser->m_hash_secret_salt = hash_salt;
       return 1;
     }
     
     enum XML_Status XMLCALL
     XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
     {
    -  switch (ps_parsing) {
    +  if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
    +    if (parser != NULL)
    +      parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
    +    return XML_STATUS_ERROR;
    +  }
    +  switch (parser->m_parsingStatus.parsing) {
       case XML_SUSPENDED:
    -    errorCode = XML_ERROR_SUSPENDED;
    +    parser->m_errorCode = XML_ERROR_SUSPENDED;
         return XML_STATUS_ERROR;
       case XML_FINISHED:
    -    errorCode = XML_ERROR_FINISHED;
    +    parser->m_errorCode = XML_ERROR_FINISHED;
         return XML_STATUS_ERROR;
       case XML_INITIALIZED:
    -    if (parentParser == NULL && !startParsing(parser)) {
    -      errorCode = XML_ERROR_NO_MEMORY;
    +    if (parser->m_parentParser == NULL && !startParsing(parser)) {
    +      parser->m_errorCode = XML_ERROR_NO_MEMORY;
           return XML_STATUS_ERROR;
         }
    +    /* fall through */
       default:
    -    ps_parsing = XML_PARSING;
    +    parser->m_parsingStatus.parsing = XML_PARSING;
       }
     
       if (len == 0) {
    -    ps_finalBuffer = (XML_Bool)isFinal;
    +    parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
         if (!isFinal)
           return XML_STATUS_OK;
    -    positionPtr = bufferPtr;
    -    parseEndPtr = bufferEnd;
    +    parser->m_positionPtr = parser->m_bufferPtr;
    +    parser->m_parseEndPtr = parser->m_bufferEnd;
     
         /* If data are left over from last buffer, and we now know that these
            data are the final chunk of input, then we have to check them again
            to detect errors based on that fact.
         */
    -    errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr);
    +    parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
     
    -    if (errorCode == XML_ERROR_NONE) {
    -      switch (ps_parsing) {
    +    if (parser->m_errorCode == XML_ERROR_NONE) {
    +      switch (parser->m_parsingStatus.parsing) {
           case XML_SUSPENDED:
    -        XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
    -        positionPtr = bufferPtr;
    +        /* It is hard to be certain, but it seems that this case
    +         * cannot occur.  This code is cleaning up a previous parse
    +         * with no new data (since len == 0).  Changing the parsing
    +         * state requires getting to execute a handler function, and
    +         * there doesn't seem to be an opportunity for that while in
    +         * this circumstance.
    +         *
    +         * Given the uncertainty, we retain the code but exclude it
    +         * from coverage tests.
    +         *
    +         * LCOV_EXCL_START
    +         */
    +        XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
    +        parser->m_positionPtr = parser->m_bufferPtr;
             return XML_STATUS_SUSPENDED;
    +        /* LCOV_EXCL_STOP */
           case XML_INITIALIZED:
           case XML_PARSING:
    -        ps_parsing = XML_FINISHED;
    +        parser->m_parsingStatus.parsing = XML_FINISHED;
             /* fall through */
           default:
             return XML_STATUS_OK;
           }
         }
    -    eventEndPtr = eventPtr;
    -    processor = errorProcessor;
    +    parser->m_eventEndPtr = parser->m_eventPtr;
    +    parser->m_processor = errorProcessor;
         return XML_STATUS_ERROR;
       }
     #ifndef XML_CONTEXT_BYTES
    -  else if (bufferPtr == bufferEnd) {
    +  else if (parser->m_bufferPtr == parser->m_bufferEnd) {
         const char *end;
         int nLeftOver;
         enum XML_Status result;
    -    parseEndByteIndex += len;
    -    positionPtr = s;
    -    ps_finalBuffer = (XML_Bool)isFinal;
    +    /* Detect overflow (a+b > MAX <==> b > MAX-a) */
    +    if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
    +       parser->m_errorCode = XML_ERROR_NO_MEMORY;
    +       parser->m_eventPtr = parser->m_eventEndPtr = NULL;
    +       parser->m_processor = errorProcessor;
    +       return XML_STATUS_ERROR;
    +    }
    +    parser->m_parseEndByteIndex += len;
    +    parser->m_positionPtr = s;
    +    parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
     
    -    errorCode = processor(parser, s, parseEndPtr = s + len, &end);
    +    parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
     
    -    if (errorCode != XML_ERROR_NONE) {
    -      eventEndPtr = eventPtr;
    -      processor = errorProcessor;
    +    if (parser->m_errorCode != XML_ERROR_NONE) {
    +      parser->m_eventEndPtr = parser->m_eventPtr;
    +      parser->m_processor = errorProcessor;
           return XML_STATUS_ERROR;
         }
         else {
    -      switch (ps_parsing) {
    +      switch (parser->m_parsingStatus.parsing) {
           case XML_SUSPENDED:
             result = XML_STATUS_SUSPENDED;
             break;
           case XML_INITIALIZED:
           case XML_PARSING:
             if (isFinal) {
    -          ps_parsing = XML_FINISHED;
    +          parser->m_parsingStatus.parsing = XML_FINISHED;
               return XML_STATUS_OK;
             }
           /* fall through */
    @@ -1613,32 +1912,33 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
           }
         }
     
    -    XmlUpdatePosition(encoding, positionPtr, end, &position);
    +    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position);
         nLeftOver = s + len - end;
         if (nLeftOver) {
    -      if (buffer == NULL || nLeftOver > bufferLim - buffer) {
    -        /* FIXME avoid integer overflow */
    -        char *temp;
    -        temp = (buffer == NULL
    -                ? (char *)MALLOC(len * 2)
    -                : (char *)REALLOC(buffer, len * 2));
    +      if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) {
    +        /* avoid _signed_ integer overflow */
    +        char *temp = NULL;
    +        const int bytesToAllocate = (int)((unsigned)len * 2U);
    +        if (bytesToAllocate > 0) {
    +          temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate);
    +        }
             if (temp == NULL) {
    -          errorCode = XML_ERROR_NO_MEMORY;
    -          eventPtr = eventEndPtr = NULL;
    -          processor = errorProcessor;
    +          parser->m_errorCode = XML_ERROR_NO_MEMORY;
    +          parser->m_eventPtr = parser->m_eventEndPtr = NULL;
    +          parser->m_processor = errorProcessor;
               return XML_STATUS_ERROR;
             }
    -        buffer = temp;
    -        bufferLim = buffer + len * 2;
    +        parser->m_buffer = temp;
    +        parser->m_bufferLim = parser->m_buffer + bytesToAllocate;
           }
    -      memcpy(buffer, end, nLeftOver);
    +      memcpy(parser->m_buffer, end, nLeftOver);
         }
    -    bufferPtr = buffer;
    -    bufferEnd = buffer + nLeftOver;
    -    positionPtr = bufferPtr;
    -    parseEndPtr = bufferEnd;
    -    eventPtr = bufferPtr;
    -    eventEndPtr = bufferPtr;
    +    parser->m_bufferPtr = parser->m_buffer;
    +    parser->m_bufferEnd = parser->m_buffer + nLeftOver;
    +    parser->m_positionPtr = parser->m_bufferPtr;
    +    parser->m_parseEndPtr = parser->m_bufferEnd;
    +    parser->m_eventPtr = parser->m_bufferPtr;
    +    parser->m_eventEndPtr = parser->m_bufferPtr;
         return result;
       }
     #endif  /* not defined XML_CONTEXT_BYTES */
    @@ -1659,106 +1959,118 @@ XML_ParseBuffer(XML_Parser parser, int len, int isFinal)
       const char *start;
       enum XML_Status result = XML_STATUS_OK;
     
    -  switch (ps_parsing) {
    +  if (parser == NULL)
    +    return XML_STATUS_ERROR;
    +  switch (parser->m_parsingStatus.parsing) {
       case XML_SUSPENDED:
    -    errorCode = XML_ERROR_SUSPENDED;
    +    parser->m_errorCode = XML_ERROR_SUSPENDED;
         return XML_STATUS_ERROR;
       case XML_FINISHED:
    -    errorCode = XML_ERROR_FINISHED;
    +    parser->m_errorCode = XML_ERROR_FINISHED;
         return XML_STATUS_ERROR;
       case XML_INITIALIZED:
    -    if (parentParser == NULL && !startParsing(parser)) {
    -      errorCode = XML_ERROR_NO_MEMORY;
    +    if (parser->m_parentParser == NULL && !startParsing(parser)) {
    +      parser->m_errorCode = XML_ERROR_NO_MEMORY;
           return XML_STATUS_ERROR;
         }
    +    /* fall through */
       default:
    -    ps_parsing = XML_PARSING;
    +    parser->m_parsingStatus.parsing = XML_PARSING;
       }
     
    -  start = bufferPtr;
    -  positionPtr = start;
    -  bufferEnd += len;
    -  parseEndPtr = bufferEnd;
    -  parseEndByteIndex += len;
    -  ps_finalBuffer = (XML_Bool)isFinal;
    +  start = parser->m_bufferPtr;
    +  parser->m_positionPtr = start;
    +  parser->m_bufferEnd += len;
    +  parser->m_parseEndPtr = parser->m_bufferEnd;
    +  parser->m_parseEndByteIndex += len;
    +  parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
     
    -  errorCode = processor(parser, start, parseEndPtr, &bufferPtr);
    +  parser->m_errorCode = parser->m_processor(parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
     
    -  if (errorCode != XML_ERROR_NONE) {
    -    eventEndPtr = eventPtr;
    -    processor = errorProcessor;
    +  if (parser->m_errorCode != XML_ERROR_NONE) {
    +    parser->m_eventEndPtr = parser->m_eventPtr;
    +    parser->m_processor = errorProcessor;
         return XML_STATUS_ERROR;
       }
       else {
    -    switch (ps_parsing) {
    +    switch (parser->m_parsingStatus.parsing) {
         case XML_SUSPENDED:
           result = XML_STATUS_SUSPENDED;
           break;
         case XML_INITIALIZED:
         case XML_PARSING:
           if (isFinal) {
    -        ps_parsing = XML_FINISHED;
    +        parser->m_parsingStatus.parsing = XML_FINISHED;
             return result;
           }
         default: ;  /* should not happen */
         }
       }
     
    -  XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
    -  positionPtr = bufferPtr;
    +  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
    +  parser->m_positionPtr = parser->m_bufferPtr;
       return result;
     }
     
     void * XMLCALL
     XML_GetBuffer(XML_Parser parser, int len)
     {
    +  if (parser == NULL)
    +    return NULL;
       if (len < 0) {
    -    errorCode = XML_ERROR_NO_MEMORY;
    +    parser->m_errorCode = XML_ERROR_NO_MEMORY;
         return NULL;
       }
    -  switch (ps_parsing) {
    +  switch (parser->m_parsingStatus.parsing) {
       case XML_SUSPENDED:
    -    errorCode = XML_ERROR_SUSPENDED;
    +    parser->m_errorCode = XML_ERROR_SUSPENDED;
         return NULL;
       case XML_FINISHED:
    -    errorCode = XML_ERROR_FINISHED;
    +    parser->m_errorCode = XML_ERROR_FINISHED;
         return NULL;
       default: ;
       }
     
    -  if (len > bufferLim - bufferEnd) {
    +  if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) {
     #ifdef XML_CONTEXT_BYTES
         int keep;
     #endif  /* defined XML_CONTEXT_BYTES */
         /* Do not invoke signed arithmetic overflow: */
    -    int neededSize = (int) ((unsigned)len + (unsigned)(bufferEnd - bufferPtr));
    +    int neededSize = (int) ((unsigned)len +
    +                            (unsigned)EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd,
    +                                                          parser->m_bufferPtr));
         if (neededSize < 0) {
    -      errorCode = XML_ERROR_NO_MEMORY;
    +      parser->m_errorCode = XML_ERROR_NO_MEMORY;
           return NULL;
         }
     #ifdef XML_CONTEXT_BYTES
    -    keep = (int)(bufferPtr - buffer);
    +    keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
         if (keep > XML_CONTEXT_BYTES)
           keep = XML_CONTEXT_BYTES;
         neededSize += keep;
     #endif  /* defined XML_CONTEXT_BYTES */
    -    if (neededSize  <= bufferLim - buffer) {
    +    if (neededSize <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
     #ifdef XML_CONTEXT_BYTES
    -      if (keep < bufferPtr - buffer) {
    -        int offset = (int)(bufferPtr - buffer) - keep;
    -        memmove(buffer, &buffer[offset], bufferEnd - bufferPtr + keep);
    -        bufferEnd -= offset;
    -        bufferPtr -= offset;
    +      if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
    +          int offset = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer) - keep;
    +        /* The buffer pointers cannot be NULL here; we have at least some bytes in the buffer */
    +        memmove(parser->m_buffer, &parser->m_buffer[offset], parser->m_bufferEnd - parser->m_bufferPtr + keep);
    +        parser->m_bufferEnd -= offset;
    +        parser->m_bufferPtr -= offset;
           }
     #else
    -      memmove(buffer, bufferPtr, bufferEnd - bufferPtr);
    -      bufferEnd = buffer + (bufferEnd - bufferPtr);
    -      bufferPtr = buffer;
    +      if (parser->m_buffer && parser->m_bufferPtr) {
    +        memmove(parser->m_buffer, parser->m_bufferPtr,
    +                EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
    +        parser->m_bufferEnd = parser->m_buffer +
    +            EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
    +        parser->m_bufferPtr = parser->m_buffer;
    +      }
     #endif  /* not defined XML_CONTEXT_BYTES */
         }
         else {
           char *newBuf;
    -      int bufferSize = (int)(bufferLim - bufferPtr);
    +      int bufferSize = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
           if (bufferSize == 0)
             bufferSize = INIT_BUFFER_SIZE;
           do {
    @@ -1766,71 +2078,82 @@ XML_GetBuffer(XML_Parser parser, int len)
             bufferSize = (int) (2U * (unsigned) bufferSize);
           } while (bufferSize < neededSize && bufferSize > 0);
           if (bufferSize <= 0) {
    -        errorCode = XML_ERROR_NO_MEMORY;
    +        parser->m_errorCode = XML_ERROR_NO_MEMORY;
             return NULL;
           }
    -      newBuf = (char *)MALLOC(bufferSize);
    +      newBuf = (char *)MALLOC(parser, bufferSize);
           if (newBuf == 0) {
    -        errorCode = XML_ERROR_NO_MEMORY;
    +        parser->m_errorCode = XML_ERROR_NO_MEMORY;
             return NULL;
           }
    -      bufferLim = newBuf + bufferSize;
    +      parser->m_bufferLim = newBuf + bufferSize;
     #ifdef XML_CONTEXT_BYTES
    -      if (bufferPtr) {
    -        int keep = (int)(bufferPtr - buffer);
    +      if (parser->m_bufferPtr) {
    +        int keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
             if (keep > XML_CONTEXT_BYTES)
               keep = XML_CONTEXT_BYTES;
    -        memcpy(newBuf, &bufferPtr[-keep], bufferEnd - bufferPtr + keep);
    -        FREE(buffer);
    -        buffer = newBuf;
    -        bufferEnd = buffer + (bufferEnd - bufferPtr) + keep;
    -        bufferPtr = buffer + keep;
    +        memcpy(newBuf, &parser->m_bufferPtr[-keep],
    +               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep);
    +        FREE(parser, parser->m_buffer);
    +        parser->m_buffer = newBuf;
    +        parser->m_bufferEnd = parser->m_buffer +
    +            EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep;
    +        parser->m_bufferPtr = parser->m_buffer + keep;
           }
           else {
    -        bufferEnd = newBuf + (bufferEnd - bufferPtr);
    -        bufferPtr = buffer = newBuf;
    +        /* This must be a brand new buffer with no data in it yet */
    +        parser->m_bufferEnd = newBuf;
    +        parser->m_bufferPtr = parser->m_buffer = newBuf;
           }
     #else
    -      if (bufferPtr) {
    -        memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr);
    -        FREE(buffer);
    +      if (parser->m_bufferPtr) {
    +        memcpy(newBuf, parser->m_bufferPtr,
    +               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
    +        FREE(parser, parser->m_buffer);
    +        parser->m_bufferEnd = newBuf +
    +            EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
           }
    -      bufferEnd = newBuf + (bufferEnd - bufferPtr);
    -      bufferPtr = buffer = newBuf;
    +      else {
    +        /* This must be a brand new buffer with no data in it yet */
    +        parser->m_bufferEnd = newBuf;
    +      }
    +      parser->m_bufferPtr = parser->m_buffer = newBuf;
     #endif  /* not defined XML_CONTEXT_BYTES */
         }
    -    eventPtr = eventEndPtr = NULL;
    -    positionPtr = NULL;
    +    parser->m_eventPtr = parser->m_eventEndPtr = NULL;
    +    parser->m_positionPtr = NULL;
       }
    -  return bufferEnd;
    +  return parser->m_bufferEnd;
     }
     
     enum XML_Status XMLCALL
     XML_StopParser(XML_Parser parser, XML_Bool resumable)
     {
    -  switch (ps_parsing) {
    +  if (parser == NULL)
    +    return XML_STATUS_ERROR;
    +  switch (parser->m_parsingStatus.parsing) {
       case XML_SUSPENDED:
         if (resumable) {
    -      errorCode = XML_ERROR_SUSPENDED;
    +      parser->m_errorCode = XML_ERROR_SUSPENDED;
           return XML_STATUS_ERROR;
         }
    -    ps_parsing = XML_FINISHED;
    +    parser->m_parsingStatus.parsing = XML_FINISHED;
         break;
       case XML_FINISHED:
    -    errorCode = XML_ERROR_FINISHED;
    +    parser->m_errorCode = XML_ERROR_FINISHED;
         return XML_STATUS_ERROR;
       default:
         if (resumable) {
     #ifdef XML_DTD
    -      if (isParamEntity) {
    -        errorCode = XML_ERROR_SUSPEND_PE;
    +      if (parser->m_isParamEntity) {
    +        parser->m_errorCode = XML_ERROR_SUSPEND_PE;
             return XML_STATUS_ERROR;
           }
     #endif
    -      ps_parsing = XML_SUSPENDED;
    +      parser->m_parsingStatus.parsing = XML_SUSPENDED;
         }
         else
    -      ps_parsing = XML_FINISHED;
    +      parser->m_parsingStatus.parsing = XML_FINISHED;
       }
       return XML_STATUS_OK;
     }
    @@ -1840,42 +2163,46 @@ XML_ResumeParser(XML_Parser parser)
     {
       enum XML_Status result = XML_STATUS_OK;
     
    -  if (ps_parsing != XML_SUSPENDED) {
    -    errorCode = XML_ERROR_NOT_SUSPENDED;
    +  if (parser == NULL)
    +    return XML_STATUS_ERROR;
    +  if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
    +    parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
         return XML_STATUS_ERROR;
       }
    -  ps_parsing = XML_PARSING;
    +  parser->m_parsingStatus.parsing = XML_PARSING;
     
    -  errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr);
    +  parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
     
    -  if (errorCode != XML_ERROR_NONE) {
    -    eventEndPtr = eventPtr;
    -    processor = errorProcessor;
    +  if (parser->m_errorCode != XML_ERROR_NONE) {
    +    parser->m_eventEndPtr = parser->m_eventPtr;
    +    parser->m_processor = errorProcessor;
         return XML_STATUS_ERROR;
       }
       else {
    -    switch (ps_parsing) {
    +    switch (parser->m_parsingStatus.parsing) {
         case XML_SUSPENDED:
           result = XML_STATUS_SUSPENDED;
           break;
         case XML_INITIALIZED:
         case XML_PARSING:
    -      if (ps_finalBuffer) {
    -        ps_parsing = XML_FINISHED;
    +      if (parser->m_parsingStatus.finalBuffer) {
    +        parser->m_parsingStatus.parsing = XML_FINISHED;
             return result;
           }
         default: ;
         }
       }
     
    -  XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
    -  positionPtr = bufferPtr;
    +  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
    +  parser->m_positionPtr = parser->m_bufferPtr;
       return result;
     }
     
     void XMLCALL
     XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status)
     {
    +  if (parser == NULL)
    +    return;
       assert(status != NULL);
       *status = parser->m_parsingStatus;
     }
    @@ -1883,22 +2210,28 @@ XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status)
     enum XML_Error XMLCALL
     XML_GetErrorCode(XML_Parser parser)
     {
    -  return errorCode;
    +  if (parser == NULL)
    +    return XML_ERROR_INVALID_ARGUMENT;
    +  return parser->m_errorCode;
     }
     
     XML_Index XMLCALL
     XML_GetCurrentByteIndex(XML_Parser parser)
     {
    -  if (eventPtr)
    -    return (XML_Index)(parseEndByteIndex - (parseEndPtr - eventPtr));
    +  if (parser == NULL)
    +    return -1;
    +  if (parser->m_eventPtr)
    +    return (XML_Index)(parser->m_parseEndByteIndex - (parser->m_parseEndPtr - parser->m_eventPtr));
       return -1;
     }
     
     int XMLCALL
     XML_GetCurrentByteCount(XML_Parser parser)
     {
    -  if (eventEndPtr && eventPtr)
    -    return (int)(eventEndPtr - eventPtr);
    +  if (parser == NULL)
    +    return 0;
    +  if (parser->m_eventEndPtr && parser->m_eventPtr)
    +    return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
       return 0;
     }
     
    @@ -1906,11 +2239,19 @@ const char * XMLCALL
     XML_GetInputContext(XML_Parser parser, int *offset, int *size)
     {
     #ifdef XML_CONTEXT_BYTES
    -  if (eventPtr && buffer) {
    -    *offset = (int)(eventPtr - buffer);
    -    *size   = (int)(bufferEnd - buffer);
    -    return buffer;
    +  if (parser == NULL)
    +    return NULL;
    +  if (parser->m_eventPtr && parser->m_buffer) {
    +    if (offset != NULL)
    +      *offset = (int)(parser->m_eventPtr - parser->m_buffer);
    +    if (size != NULL)
    +      *size   = (int)(parser->m_bufferEnd - parser->m_buffer);
    +    return parser->m_buffer;
       }
    +#else
    +  (void)parser;
    +  (void)offset;
    +  (void)size;
     #endif /* defined XML_CONTEXT_BYTES */
       return (char *) 0;
     }
    @@ -1918,109 +2259,166 @@ XML_GetInputContext(XML_Parser parser, int *offset, int *size)
     XML_Size XMLCALL
     XML_GetCurrentLineNumber(XML_Parser parser)
     {
    -  if (eventPtr && eventPtr >= positionPtr) {
    -    XmlUpdatePosition(encoding, positionPtr, eventPtr, &position);
    -    positionPtr = eventPtr;
    +  if (parser == NULL)
    +    return 0;
    +  if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
    +    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
    +    parser->m_positionPtr = parser->m_eventPtr;
       }
    -  return position.lineNumber + 1;
    +  return parser->m_position.lineNumber + 1;
     }
     
     XML_Size XMLCALL
     XML_GetCurrentColumnNumber(XML_Parser parser)
     {
    -  if (eventPtr && eventPtr >= positionPtr) {
    -    XmlUpdatePosition(encoding, positionPtr, eventPtr, &position);
    -    positionPtr = eventPtr;
    +  if (parser == NULL)
    +    return 0;
    +  if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
    +    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
    +    parser->m_positionPtr = parser->m_eventPtr;
       }
    -  return position.columnNumber;
    +  return parser->m_position.columnNumber;
     }
     
     void XMLCALL
     XML_FreeContentModel(XML_Parser parser, XML_Content *model)
     {
    -  FREE(model);
    +  if (parser != NULL)
    +    FREE(parser, model);
     }
     
     void * XMLCALL
     XML_MemMalloc(XML_Parser parser, size_t size)
     {
    -  return MALLOC(size);
    +  if (parser == NULL)
    +    return NULL;
    +  return MALLOC(parser, size);
     }
     
     void * XMLCALL
     XML_MemRealloc(XML_Parser parser, void *ptr, size_t size)
     {
    -  return REALLOC(ptr, size);
    +  if (parser == NULL)
    +    return NULL;
    +  return REALLOC(parser, ptr, size);
     }
     
     void XMLCALL
     XML_MemFree(XML_Parser parser, void *ptr)
     {
    -  FREE(ptr);
    +  if (parser != NULL)
    +    FREE(parser, ptr);
     }
     
     void XMLCALL
     XML_DefaultCurrent(XML_Parser parser)
     {
    -  if (defaultHandler) {
    -    if (openInternalEntities)
    +  if (parser == NULL)
    +    return;
    +  if (parser->m_defaultHandler) {
    +    if (parser->m_openInternalEntities)
           reportDefault(parser,
    -                    internalEncoding,
    -                    openInternalEntities->internalEventPtr,
    -                    openInternalEntities->internalEventEndPtr);
    +                    parser->m_internalEncoding,
    +                    parser->m_openInternalEntities->internalEventPtr,
    +                    parser->m_openInternalEntities->internalEventEndPtr);
         else
    -      reportDefault(parser, encoding, eventPtr, eventEndPtr);
    +      reportDefault(parser, parser->m_encoding, parser->m_eventPtr, parser->m_eventEndPtr);
       }
     }
     
     const XML_LChar * XMLCALL
     XML_ErrorString(enum XML_Error code)
     {
    -  static const XML_LChar* const message[] = {
    -    0,
    -    XML_L("out of memory"),
    -    XML_L("syntax error"),
    -    XML_L("no element found"),
    -    XML_L("not well-formed (invalid token)"),
    -    XML_L("unclosed token"),
    -    XML_L("partial character"),
    -    XML_L("mismatched tag"),
    -    XML_L("duplicate attribute"),
    -    XML_L("junk after document element"),
    -    XML_L("illegal parameter entity reference"),
    -    XML_L("undefined entity"),
    -    XML_L("recursive entity reference"),
    -    XML_L("asynchronous entity"),
    -    XML_L("reference to invalid character number"),
    -    XML_L("reference to binary entity"),
    -    XML_L("reference to external entity in attribute"),
    -    XML_L("XML or text declaration not at start of entity"),
    -    XML_L("unknown encoding"),
    -    XML_L("encoding specified in XML declaration is incorrect"),
    -    XML_L("unclosed CDATA section"),
    -    XML_L("error in processing external entity reference"),
    -    XML_L("document is not standalone"),
    -    XML_L("unexpected parser state - please send a bug report"),
    -    XML_L("entity declared in parameter entity"),
    -    XML_L("requested feature requires XML_DTD support in Expat"),
    -    XML_L("cannot change setting once parsing has begun"),
    -    XML_L("unbound prefix"),
    -    XML_L("must not undeclare prefix"),
    -    XML_L("incomplete markup in parameter entity"),
    -    XML_L("XML declaration not well-formed"),
    -    XML_L("text declaration not well-formed"),
    -    XML_L("illegal character(s) in public id"),
    -    XML_L("parser suspended"),
    -    XML_L("parser not suspended"),
    -    XML_L("parsing aborted"),
    -    XML_L("parsing finished"),
    -    XML_L("cannot suspend in external parameter entity"),
    -    XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name"),
    -    XML_L("reserved prefix (xmlns) must not be declared or undeclared"),
    -    XML_L("prefix must not be bound to one of the reserved namespace names")
    -  };
    -  if (code > 0 && code < sizeof(message)/sizeof(message[0]))
    -    return message[code];
    +  switch (code) {
    +  case XML_ERROR_NONE:
    +    return NULL;
    +  case XML_ERROR_NO_MEMORY:
    +    return XML_L("out of memory");
    +  case XML_ERROR_SYNTAX:
    +    return XML_L("syntax error");
    +  case XML_ERROR_NO_ELEMENTS:
    +    return XML_L("no element found");
    +  case XML_ERROR_INVALID_TOKEN:
    +    return XML_L("not well-formed (invalid token)");
    +  case XML_ERROR_UNCLOSED_TOKEN:
    +    return XML_L("unclosed token");
    +  case XML_ERROR_PARTIAL_CHAR:
    +    return XML_L("partial character");
    +  case XML_ERROR_TAG_MISMATCH:
    +    return XML_L("mismatched tag");
    +  case XML_ERROR_DUPLICATE_ATTRIBUTE:
    +    return XML_L("duplicate attribute");
    +  case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
    +    return XML_L("junk after document element");
    +  case XML_ERROR_PARAM_ENTITY_REF:
    +    return XML_L("illegal parameter entity reference");
    +  case XML_ERROR_UNDEFINED_ENTITY:
    +    return XML_L("undefined entity");
    +  case XML_ERROR_RECURSIVE_ENTITY_REF:
    +    return XML_L("recursive entity reference");
    +  case XML_ERROR_ASYNC_ENTITY:
    +    return XML_L("asynchronous entity");
    +  case XML_ERROR_BAD_CHAR_REF:
    +    return XML_L("reference to invalid character number");
    +  case XML_ERROR_BINARY_ENTITY_REF:
    +    return XML_L("reference to binary entity");
    +  case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
    +    return XML_L("reference to external entity in attribute");
    +  case XML_ERROR_MISPLACED_XML_PI:
    +    return XML_L("XML or text declaration not at start of entity");
    +  case XML_ERROR_UNKNOWN_ENCODING:
    +    return XML_L("unknown encoding");
    +  case XML_ERROR_INCORRECT_ENCODING:
    +    return XML_L("encoding specified in XML declaration is incorrect");
    +  case XML_ERROR_UNCLOSED_CDATA_SECTION:
    +    return XML_L("unclosed CDATA section");
    +  case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
    +    return XML_L("error in processing external entity reference");
    +  case XML_ERROR_NOT_STANDALONE:
    +    return XML_L("document is not standalone");
    +  case XML_ERROR_UNEXPECTED_STATE:
    +    return XML_L("unexpected parser state - please send a bug report");
    +  case XML_ERROR_ENTITY_DECLARED_IN_PE:
    +    return XML_L("entity declared in parameter entity");
    +  case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
    +    return XML_L("requested feature requires XML_DTD support in Expat");
    +  case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
    +    return XML_L("cannot change setting once parsing has begun");
    +  /* Added in 1.95.7. */
    +  case XML_ERROR_UNBOUND_PREFIX:
    +    return XML_L("unbound prefix");
    +  /* Added in 1.95.8. */
    +  case XML_ERROR_UNDECLARING_PREFIX:
    +    return XML_L("must not undeclare prefix");
    +  case XML_ERROR_INCOMPLETE_PE:
    +    return XML_L("incomplete markup in parameter entity");
    +  case XML_ERROR_XML_DECL:
    +    return XML_L("XML declaration not well-formed");
    +  case XML_ERROR_TEXT_DECL:
    +    return XML_L("text declaration not well-formed");
    +  case XML_ERROR_PUBLICID:
    +    return XML_L("illegal character(s) in public id");
    +  case XML_ERROR_SUSPENDED:
    +    return XML_L("parser suspended");
    +  case XML_ERROR_NOT_SUSPENDED:
    +    return XML_L("parser not suspended");
    +  case XML_ERROR_ABORTED:
    +    return XML_L("parsing aborted");
    +  case XML_ERROR_FINISHED:
    +    return XML_L("parsing finished");
    +  case XML_ERROR_SUSPEND_PE:
    +    return XML_L("cannot suspend in external parameter entity");
    +  /* Added in 2.0.0. */
    +  case XML_ERROR_RESERVED_PREFIX_XML:
    +    return XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name");
    +  case XML_ERROR_RESERVED_PREFIX_XMLNS:
    +    return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
    +  case XML_ERROR_RESERVED_NAMESPACE_URI:
    +    return XML_L("prefix must not be bound to one of the reserved namespace names");
    +  /* Added in 2.2.5. */
    +  case XML_ERROR_INVALID_ARGUMENT:  /* Constant added in 2.2.1, already */
    +    return XML_L("invalid argument");
    +  }
       return NULL;
     }
     
    @@ -2103,12 +2501,12 @@ XML_GetFeatureList(void)
     static XML_Bool
     storeRawNames(XML_Parser parser)
     {
    -  TAG *tag = tagStack;
    +  TAG *tag = parser->m_tagStack;
       while (tag) {
         int bufSize;
         int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
         char *rawNameBuf = tag->buf + nameLen;
    -    /* Stop if already stored.  Since tagStack is a stack, we can stop
    +    /* Stop if already stored.  Since m_tagStack is a stack, we can stop
            at the first entry that has already been copied; everything
            below it in the stack is already been accounted for in a
            previous call to this function.
    @@ -2120,7 +2518,7 @@ storeRawNames(XML_Parser parser)
         */
         bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
         if (bufSize > tag->bufEnd - tag->buf) {
    -      char *temp = (char *)REALLOC(tag->buf, bufSize);
    +      char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
           if (temp == NULL)
             return XML_FALSE;
           /* if tag->name.str points to tag->buf (only when namespace
    @@ -2151,8 +2549,8 @@ contentProcessor(XML_Parser parser,
                      const char *end,
                      const char **endPtr)
     {
    -  enum XML_Error result = doContent(parser, 0, encoding, start, end,
    -                                    endPtr, (XML_Bool)!ps_finalBuffer);
    +  enum XML_Error result = doContent(parser, 0, parser->m_encoding, start, end,
    +                                    endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
       if (result == XML_ERROR_NONE) {
         if (!storeRawNames(parser))
           return XML_ERROR_NO_MEMORY;
    @@ -2169,7 +2567,7 @@ externalEntityInitProcessor(XML_Parser parser,
       enum XML_Error result = initializeEncoding(parser);
       if (result != XML_ERROR_NONE)
         return result;
    -  processor = externalEntityInitProcessor2;
    +  parser->m_processor = externalEntityInitProcessor2;
       return externalEntityInitProcessor2(parser, start, end, endPtr);
     }
     
    @@ -2180,7 +2578,7 @@ externalEntityInitProcessor2(XML_Parser parser,
                                  const char **endPtr)
     {
       const char *next = start; /* XmlContentTok doesn't always set the last arg */
    -  int tok = XmlContentTok(encoding, start, end, &next);
    +  int tok = XmlContentTok(parser->m_encoding, start, end, &next);
       switch (tok) {
       case XML_TOK_BOM:
         /* If we are at the end of the buffer, this would cause the next stage,
    @@ -2188,28 +2586,28 @@ externalEntityInitProcessor2(XML_Parser parser,
            doContent (by detecting XML_TOK_NONE) without processing any xml text
            declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
         */
    -    if (next == end && !ps_finalBuffer) {
    +    if (next == end && !parser->m_parsingStatus.finalBuffer) {
           *endPtr = next;
           return XML_ERROR_NONE;
         }
         start = next;
         break;
       case XML_TOK_PARTIAL:
    -    if (!ps_finalBuffer) {
    +    if (!parser->m_parsingStatus.finalBuffer) {
           *endPtr = start;
           return XML_ERROR_NONE;
         }
    -    eventPtr = start;
    +    parser->m_eventPtr = start;
         return XML_ERROR_UNCLOSED_TOKEN;
       case XML_TOK_PARTIAL_CHAR:
    -    if (!ps_finalBuffer) {
    +    if (!parser->m_parsingStatus.finalBuffer) {
           *endPtr = start;
           return XML_ERROR_NONE;
         }
    -    eventPtr = start;
    +    parser->m_eventPtr = start;
         return XML_ERROR_PARTIAL_CHAR;
       }
    -  processor = externalEntityInitProcessor3;
    +  parser->m_processor = externalEntityInitProcessor3;
       return externalEntityInitProcessor3(parser, start, end, endPtr);
     }
     
    @@ -2221,9 +2619,9 @@ externalEntityInitProcessor3(XML_Parser parser,
     {
       int tok;
       const char *next = start; /* XmlContentTok doesn't always set the last arg */
    -  eventPtr = start;
    -  tok = XmlContentTok(encoding, start, end, &next);
    -  eventEndPtr = next;
    +  parser->m_eventPtr = start;
    +  tok = XmlContentTok(parser->m_encoding, start, end, &next);
    +  parser->m_eventEndPtr = next;
     
       switch (tok) {
       case XML_TOK_XML_DECL:
    @@ -2232,7 +2630,7 @@ externalEntityInitProcessor3(XML_Parser parser,
           result = processXmlDecl(parser, 1, start, next);
           if (result != XML_ERROR_NONE)
             return result;
    -      switch (ps_parsing) {
    +      switch (parser->m_parsingStatus.parsing) {
           case XML_SUSPENDED:
             *endPtr = next;
             return XML_ERROR_NONE;
    @@ -2244,20 +2642,20 @@ externalEntityInitProcessor3(XML_Parser parser,
         }
         break;
       case XML_TOK_PARTIAL:
    -    if (!ps_finalBuffer) {
    +    if (!parser->m_parsingStatus.finalBuffer) {
           *endPtr = start;
           return XML_ERROR_NONE;
         }
         return XML_ERROR_UNCLOSED_TOKEN;
       case XML_TOK_PARTIAL_CHAR:
    -    if (!ps_finalBuffer) {
    +    if (!parser->m_parsingStatus.finalBuffer) {
           *endPtr = start;
           return XML_ERROR_NONE;
         }
         return XML_ERROR_PARTIAL_CHAR;
       }
    -  processor = externalEntityContentProcessor;
    -  tagLevel = 1;
    +  parser->m_processor = externalEntityContentProcessor;
    +  parser->m_tagLevel = 1;
       return externalEntityContentProcessor(parser, start, end, endPtr);
     }
     
    @@ -2267,8 +2665,8 @@ externalEntityContentProcessor(XML_Parser parser,
                                    const char *end,
                                    const char **endPtr)
     {
    -  enum XML_Error result = doContent(parser, 1, encoding, start, end,
    -                                    endPtr, (XML_Bool)!ps_finalBuffer);
    +  enum XML_Error result = doContent(parser, 1, parser->m_encoding, start, end,
    +                                    endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
       if (result == XML_ERROR_NONE) {
         if (!storeRawNames(parser))
           return XML_ERROR_NO_MEMORY;
    @@ -2286,17 +2684,17 @@ doContent(XML_Parser parser,
               XML_Bool haveMore)
     {
       /* save one level of indirection */
    -  DTD * const dtd = _dtd;
    +  DTD * const dtd = parser->m_dtd;
     
       const char **eventPP;
       const char **eventEndPP;
    -  if (enc == encoding) {
    -    eventPP = &eventPtr;
    -    eventEndPP = &eventEndPtr;
    +  if (enc == parser->m_encoding) {
    +    eventPP = &parser->m_eventPtr;
    +    eventEndPP = &parser->m_eventEndPtr;
       }
       else {
    -    eventPP = &(openInternalEntities->internalEventPtr);
    -    eventEndPP = &(openInternalEntities->internalEventEndPtr);
    +    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
    +    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
       }
       *eventPP = s;
     
    @@ -2311,18 +2709,18 @@ doContent(XML_Parser parser,
             return XML_ERROR_NONE;
           }
           *eventEndPP = end;
    -      if (characterDataHandler) {
    +      if (parser->m_characterDataHandler) {
             XML_Char c = 0xA;
    -        characterDataHandler(handlerArg, &c, 1);
    +        parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
           }
    -      else if (defaultHandler)
    +      else if (parser->m_defaultHandler)
             reportDefault(parser, enc, s, end);
           /* We are at the end of the final buffer, should we check for
              XML_SUSPENDED, XML_FINISHED?
           */
           if (startTagLevel == 0)
             return XML_ERROR_NO_ELEMENTS;
    -      if (tagLevel != startTagLevel)
    +      if (parser->m_tagLevel != startTagLevel)
             return XML_ERROR_ASYNC_ENTITY;
           *nextPtr = end;
           return XML_ERROR_NONE;
    @@ -2332,7 +2730,7 @@ doContent(XML_Parser parser,
             return XML_ERROR_NONE;
           }
           if (startTagLevel > 0) {
    -        if (tagLevel != startTagLevel)
    +        if (parser->m_tagLevel != startTagLevel)
               return XML_ERROR_ASYNC_ENTITY;
             *nextPtr = s;
             return XML_ERROR_NONE;
    @@ -2361,9 +2759,9 @@ doContent(XML_Parser parser,
                                                   s + enc->minBytesPerChar,
                                                   next - enc->minBytesPerChar);
             if (ch) {
    -          if (characterDataHandler)
    -            characterDataHandler(handlerArg, &ch, 1);
    -          else if (defaultHandler)
    +          if (parser->m_characterDataHandler)
    +            parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
    +          else if (parser->m_defaultHandler)
                 reportDefault(parser, enc, s, next);
               break;
             }
    @@ -2385,9 +2783,9 @@ doContent(XML_Parser parser,
                 return XML_ERROR_ENTITY_DECLARED_IN_PE;
             }
             else if (!entity) {
    -          if (skippedEntityHandler)
    -            skippedEntityHandler(handlerArg, name, 0);
    -          else if (defaultHandler)
    +          if (parser->m_skippedEntityHandler)
    +            parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
    +          else if (parser->m_defaultHandler)
                 reportDefault(parser, enc, s, next);
               break;
             }
    @@ -2397,10 +2795,10 @@ doContent(XML_Parser parser,
               return XML_ERROR_BINARY_ENTITY_REF;
             if (entity->textPtr) {
               enum XML_Error result;
    -          if (!defaultExpandInternalEntities) {
    -            if (skippedEntityHandler)
    -              skippedEntityHandler(handlerArg, entity->name, 0);
    -            else if (defaultHandler)
    +          if (!parser->m_defaultExpandInternalEntities) {
    +            if (parser->m_skippedEntityHandler)
    +              parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name, 0);
    +            else if (parser->m_defaultHandler)
                   reportDefault(parser, enc, s, next);
                 break;
               }
    @@ -2408,22 +2806,22 @@ doContent(XML_Parser parser,
               if (result != XML_ERROR_NONE)
                 return result;
             }
    -        else if (externalEntityRefHandler) {
    +        else if (parser->m_externalEntityRefHandler) {
               const XML_Char *context;
               entity->open = XML_TRUE;
               context = getContext(parser);
               entity->open = XML_FALSE;
               if (!context)
                 return XML_ERROR_NO_MEMORY;
    -          if (!externalEntityRefHandler(externalEntityRefHandlerArg,
    +          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
                                             context,
                                             entity->base,
                                             entity->systemId,
                                             entity->publicId))
                 return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
    -          poolDiscard(&tempPool);
    +          poolDiscard(&parser->m_tempPool);
             }
    -        else if (defaultHandler)
    +        else if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
             break;
           }
    @@ -2434,29 +2832,29 @@ doContent(XML_Parser parser,
             TAG *tag;
             enum XML_Error result;
             XML_Char *toPtr;
    -        if (freeTagList) {
    -          tag = freeTagList;
    -          freeTagList = freeTagList->parent;
    +        if (parser->m_freeTagList) {
    +          tag = parser->m_freeTagList;
    +          parser->m_freeTagList = parser->m_freeTagList->parent;
             }
             else {
    -          tag = (TAG *)MALLOC(sizeof(TAG));
    +          tag = (TAG *)MALLOC(parser, sizeof(TAG));
               if (!tag)
                 return XML_ERROR_NO_MEMORY;
    -          tag->buf = (char *)MALLOC(INIT_TAG_BUF_SIZE);
    +          tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
               if (!tag->buf) {
    -            FREE(tag);
    +            FREE(parser, tag);
                 return XML_ERROR_NO_MEMORY;
               }
               tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
             }
             tag->bindings = NULL;
    -        tag->parent = tagStack;
    -        tagStack = tag;
    +        tag->parent = parser->m_tagStack;
    +        parser->m_tagStack = tag;
             tag->name.localPart = NULL;
             tag->name.prefix = NULL;
             tag->rawName = s + enc->minBytesPerChar;
             tag->rawNameLength = XmlNameLength(enc, tag->rawName);
    -        ++tagLevel;
    +        ++parser->m_tagLevel;
             {
               const char *rawNameEnd = tag->rawName + tag->rawNameLength;
               const char *fromPtr = tag->rawName;
    @@ -2468,13 +2866,13 @@ doContent(XML_Parser parser,
                            &fromPtr, rawNameEnd,
                            (ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1);
                 convLen = (int)(toPtr - (XML_Char *)tag->buf);
    -            if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
    +            if ((fromPtr >= rawNameEnd) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
                   tag->name.strLen = convLen;
                   break;
                 }
                 bufSize = (int)(tag->bufEnd - tag->buf) << 1;
                 {
    -              char *temp = (char *)REALLOC(tag->buf, bufSize);
    +              char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
                   if (temp == NULL)
                     return XML_ERROR_NO_MEMORY;
                   tag->buf = temp;
    @@ -2488,12 +2886,12 @@ doContent(XML_Parser parser,
             result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
             if (result)
               return result;
    -        if (startElementHandler)
    -          startElementHandler(handlerArg, tag->name.str,
    -                              (const XML_Char **)atts);
    -        else if (defaultHandler)
    +        if (parser->m_startElementHandler)
    +          parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
    +                              (const XML_Char **)parser->m_atts);
    +        else if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
    -        poolClear(&tempPool);
    +        poolClear(&parser->m_tempPool);
             break;
           }
         case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
    @@ -2505,51 +2903,49 @@ doContent(XML_Parser parser,
             BINDING *bindings = NULL;
             XML_Bool noElmHandlers = XML_TRUE;
             TAG_NAME name;
    -        name.str = poolStoreString(&tempPool, enc, rawName,
    +        name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
                                        rawName + XmlNameLength(enc, rawName));
             if (!name.str)
               return XML_ERROR_NO_MEMORY;
    -        poolFinish(&tempPool);
    +        poolFinish(&parser->m_tempPool);
             result = storeAtts(parser, enc, s, &name, &bindings);
    -        if (result)
    +        if (result != XML_ERROR_NONE) {
    +          freeBindings(parser, bindings);
               return result;
    -        poolFinish(&tempPool);
    -        if (startElementHandler) {
    -          startElementHandler(handlerArg, name.str, (const XML_Char **)atts);
    +        }
    +        poolFinish(&parser->m_tempPool);
    +        if (parser->m_startElementHandler) {
    +          parser->m_startElementHandler(parser->m_handlerArg, name.str, (const XML_Char **)parser->m_atts);
               noElmHandlers = XML_FALSE;
             }
    -        if (endElementHandler) {
    -          if (startElementHandler)
    +        if (parser->m_endElementHandler) {
    +          if (parser->m_startElementHandler)
                 *eventPP = *eventEndPP;
    -          endElementHandler(handlerArg, name.str);
    +          parser->m_endElementHandler(parser->m_handlerArg, name.str);
               noElmHandlers = XML_FALSE;
             }
    -        if (noElmHandlers && defaultHandler)
    +        if (noElmHandlers && parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
    -        poolClear(&tempPool);
    -        while (bindings) {
    -          BINDING *b = bindings;
    -          if (endNamespaceDeclHandler)
    -            endNamespaceDeclHandler(handlerArg, b->prefix->name);
    -          bindings = bindings->nextTagBinding;
    -          b->nextTagBinding = freeBindingList;
    -          freeBindingList = b;
    -          b->prefix->binding = b->prevPrefixBinding;
    -        }
    +        poolClear(&parser->m_tempPool);
    +        freeBindings(parser, bindings);
    +      }
    +      if ((parser->m_tagLevel == 0) && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
    +        if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
    +          parser->m_processor = epilogProcessor;
    +        else
    +          return epilogProcessor(parser, next, end, nextPtr);
           }
    -      if (tagLevel == 0)
    -        return epilogProcessor(parser, next, end, nextPtr);
           break;
         case XML_TOK_END_TAG:
    -      if (tagLevel == startTagLevel)
    +      if (parser->m_tagLevel == startTagLevel)
             return XML_ERROR_ASYNC_ENTITY;
           else {
             int len;
             const char *rawName;
    -        TAG *tag = tagStack;
    -        tagStack = tag->parent;
    -        tag->parent = freeTagList;
    -        freeTagList = tag;
    +        TAG *tag = parser->m_tagStack;
    +        parser->m_tagStack = tag->parent;
    +        tag->parent = parser->m_freeTagList;
    +        parser->m_freeTagList = tag;
             rawName = s + enc->minBytesPerChar*2;
             len = XmlNameLength(enc, rawName);
             if (len != tag->rawNameLength
    @@ -2557,13 +2953,13 @@ doContent(XML_Parser parser,
               *eventPP = rawName;
               return XML_ERROR_TAG_MISMATCH;
             }
    -        --tagLevel;
    -        if (endElementHandler) {
    +        --parser->m_tagLevel;
    +        if (parser->m_endElementHandler) {
               const XML_Char *localPart;
               const XML_Char *prefix;
               XML_Char *uri;
               localPart = tag->name.localPart;
    -          if (ns && localPart) {
    +          if (parser->m_ns && localPart) {
                 /* localPart and prefix may have been overwritten in
                    tag->name.str, since this points to the binding->uri
                    buffer which gets re-used; so we have to add them again
    @@ -2572,26 +2968,26 @@ doContent(XML_Parser parser,
                 /* don't need to check for space - already done in storeAtts() */
                 while (*localPart) *uri++ = *localPart++;
                 prefix = (XML_Char *)tag->name.prefix;
    -            if (ns_triplets && prefix) {
    -              *uri++ = namespaceSeparator;
    +            if (parser->m_ns_triplets && prefix) {
    +              *uri++ = parser->m_namespaceSeparator;
                   while (*prefix) *uri++ = *prefix++;
                  }
                 *uri = XML_T('\0');
               }
    -          endElementHandler(handlerArg, tag->name.str);
    +          parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
             }
    -        else if (defaultHandler)
    +        else if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
             while (tag->bindings) {
               BINDING *b = tag->bindings;
    -          if (endNamespaceDeclHandler)
    -            endNamespaceDeclHandler(handlerArg, b->prefix->name);
    +          if (parser->m_endNamespaceDeclHandler)
    +            parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
               tag->bindings = tag->bindings->nextTagBinding;
    -          b->nextTagBinding = freeBindingList;
    -          freeBindingList = b;
    +          b->nextTagBinding = parser->m_freeBindingList;
    +          parser->m_freeBindingList = b;
               b->prefix->binding = b->prevPrefixBinding;
             }
    -        if (tagLevel == 0)
    +        if (parser->m_tagLevel == 0)
               return epilogProcessor(parser, next, end, nextPtr);
           }
           break;
    @@ -2600,29 +2996,29 @@ doContent(XML_Parser parser,
             int n = XmlCharRefNumber(enc, s);
             if (n < 0)
               return XML_ERROR_BAD_CHAR_REF;
    -        if (characterDataHandler) {
    +        if (parser->m_characterDataHandler) {
               XML_Char buf[XML_ENCODE_MAX];
    -          characterDataHandler(handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
    +          parser->m_characterDataHandler(parser->m_handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
             }
    -        else if (defaultHandler)
    +        else if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
           }
           break;
         case XML_TOK_XML_DECL:
           return XML_ERROR_MISPLACED_XML_PI;
         case XML_TOK_DATA_NEWLINE:
    -      if (characterDataHandler) {
    +      if (parser->m_characterDataHandler) {
             XML_Char c = 0xA;
    -        characterDataHandler(handlerArg, &c, 1);
    +        parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
           }
    -      else if (defaultHandler)
    +      else if (parser->m_defaultHandler)
             reportDefault(parser, enc, s, next);
           break;
         case XML_TOK_CDATA_SECT_OPEN:
           {
             enum XML_Error result;
    -        if (startCdataSectionHandler)
    -          startCdataSectionHandler(handlerArg);
    +        if (parser->m_startCdataSectionHandler)
    +          parser->m_startCdataSectionHandler(parser->m_handlerArg);
     #if 0
             /* Suppose you doing a transformation on a document that involves
                changing only the character data.  You set up a defaultHandler
    @@ -2636,16 +3032,16 @@ doContent(XML_Parser parser,
                However, now we have a start/endCdataSectionHandler, so it seems
                easier to let the user deal with this.
             */
    -        else if (characterDataHandler)
    -          characterDataHandler(handlerArg, dataBuf, 0);
    +        else if (parser->m_characterDataHandler)
    +          parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
     #endif
    -        else if (defaultHandler)
    +        else if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
             result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
             if (result != XML_ERROR_NONE)
               return result;
             else if (!next) {
    -          processor = cdataSectionProcessor;
    +          parser->m_processor = cdataSectionProcessor;
               return result;
             }
           }
    @@ -2655,19 +3051,19 @@ doContent(XML_Parser parser,
             *nextPtr = s;
             return XML_ERROR_NONE;
           }
    -      if (characterDataHandler) {
    +      if (parser->m_characterDataHandler) {
             if (MUST_CONVERT(enc, s)) {
    -          ICHAR *dataPtr = (ICHAR *)dataBuf;
    -          XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
    -          characterDataHandler(handlerArg, dataBuf,
    -                               (int)(dataPtr - (ICHAR *)dataBuf));
    +          ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
    +          XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
    +          parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
    +                               (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
             }
             else
    -          characterDataHandler(handlerArg,
    +          parser->m_characterDataHandler(parser->m_handlerArg,
                                    (XML_Char *)s,
                                    (int)((XML_Char *)end - (XML_Char *)s));
           }
    -      else if (defaultHandler)
    +      else if (parser->m_defaultHandler)
             reportDefault(parser, enc, s, end);
           /* We are at the end of the final buffer, should we check for
              XML_SUSPENDED, XML_FINISHED?
    @@ -2676,7 +3072,7 @@ doContent(XML_Parser parser,
             *eventPP = end;
             return XML_ERROR_NO_ELEMENTS;
           }
    -      if (tagLevel != startTagLevel) {
    +      if (parser->m_tagLevel != startTagLevel) {
             *eventPP = end;
             return XML_ERROR_ASYNC_ENTITY;
           }
    @@ -2684,26 +3080,26 @@ doContent(XML_Parser parser,
           return XML_ERROR_NONE;
         case XML_TOK_DATA_CHARS:
           {
    -        XML_CharacterDataHandler charDataHandler = characterDataHandler;
    +        XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
             if (charDataHandler) {
               if (MUST_CONVERT(enc, s)) {
                 for (;;) {
    -              ICHAR *dataPtr = (ICHAR *)dataBuf;
    -              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
    +              ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
    +              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
                   *eventEndPP = s;
    -              charDataHandler(handlerArg, dataBuf,
    -                              (int)(dataPtr - (ICHAR *)dataBuf));
    +              charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
    +                              (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
                   if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
                     break;
                   *eventPP = s;
                 }
               }
               else
    -            charDataHandler(handlerArg,
    +            charDataHandler(parser->m_handlerArg,
                                 (XML_Char *)s,
                                 (int)((XML_Char *)next - (XML_Char *)s));
             }
    -        else if (defaultHandler)
    +        else if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
           }
           break;
    @@ -2716,12 +3112,20 @@ doContent(XML_Parser parser,
             return XML_ERROR_NO_MEMORY;
           break;
         default:
    -      if (defaultHandler)
    +      /* All of the tokens produced by XmlContentTok() have their own
    +       * explicit cases, so this default is not strictly necessary.
    +       * However it is a useful safety net, so we retain the code and
    +       * simply exclude it from the coverage tests.
    +       *
    +       * LCOV_EXCL_START
    +       */
    +      if (parser->m_defaultHandler)
             reportDefault(parser, enc, s, next);
           break;
    +      /* LCOV_EXCL_STOP */
         }
         *eventPP = s = next;
    -    switch (ps_parsing) {
    +    switch (parser->m_parsingStatus.parsing) {
         case XML_SUSPENDED:
           *nextPtr = next;
           return XML_ERROR_NONE;
    @@ -2733,6 +3137,29 @@ doContent(XML_Parser parser,
       /* not reached */
     }
     
    +/* This function does not call free() on the allocated memory, merely
    + * moving it to the parser's m_freeBindingList where it can be freed or
    + * reused as appropriate.
    + */
    +static void
    +freeBindings(XML_Parser parser, BINDING *bindings)
    +{
    +  while (bindings) {
    +    BINDING *b = bindings;
    +
    +    /* m_startNamespaceDeclHandler will have been called for this
    +     * binding in addBindings(), so call the end handler now.
    +     */
    +    if (parser->m_endNamespaceDeclHandler)
    +        parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
    +
    +    bindings = bindings->nextTagBinding;
    +    b->nextTagBinding = parser->m_freeBindingList;
    +    parser->m_freeBindingList = b;
    +    b->prefix->binding = b->prevPrefixBinding;
    +  }
    +}
    +
     /* Precondition: all arguments must be non-NULL;
        Purpose:
        - normalize attributes
    @@ -2748,7 +3175,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
               const char *attStr, TAG_NAME *tagNamePtr,
               BINDING **bindingsPtr)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       ELEMENT_TYPE *elementType;
       int nDefaultAtts;
       const XML_Char **appAtts;   /* the attribute list for the application */
    @@ -2771,39 +3198,43 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
                                              sizeof(ELEMENT_TYPE));
         if (!elementType)
           return XML_ERROR_NO_MEMORY;
    -    if (ns && !setElementTypePrefix(parser, elementType))
    +    if (parser->m_ns && !setElementTypePrefix(parser, elementType))
           return XML_ERROR_NO_MEMORY;
       }
       nDefaultAtts = elementType->nDefaultAtts;
     
       /* get the attributes from the tokenizer */
    -  n = XmlGetAttributes(enc, attStr, attsSize, atts);
    -  if (n + nDefaultAtts > attsSize) {
    -    int oldAttsSize = attsSize;
    +  n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
    +  if (n + nDefaultAtts > parser->m_attsSize) {
    +    int oldAttsSize = parser->m_attsSize;
         ATTRIBUTE *temp;
     #ifdef XML_ATTR_INFO
         XML_AttrInfo *temp2;
     #endif
    -    attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
    -    temp = (ATTRIBUTE *)REALLOC((void *)atts, attsSize * sizeof(ATTRIBUTE));
    -    if (temp == NULL)
    +    parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
    +    temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts, parser->m_attsSize * sizeof(ATTRIBUTE));
    +    if (temp == NULL) {
    +      parser->m_attsSize = oldAttsSize;
           return XML_ERROR_NO_MEMORY;
    -    atts = temp;
    +    }
    +    parser->m_atts = temp;
     #ifdef XML_ATTR_INFO
    -    temp2 = (XML_AttrInfo *)REALLOC((void *)attInfo, attsSize * sizeof(XML_AttrInfo));
    -    if (temp2 == NULL)
    +    temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo, parser->m_attsSize * sizeof(XML_AttrInfo));
    +    if (temp2 == NULL) {
    +      parser->m_attsSize = oldAttsSize;
           return XML_ERROR_NO_MEMORY;
    -    attInfo = temp2;
    +    }
    +    parser->m_attInfo = temp2;
     #endif
         if (n > oldAttsSize)
    -      XmlGetAttributes(enc, attStr, n, atts);
    +      XmlGetAttributes(enc, attStr, n, parser->m_atts);
       }
     
    -  appAtts = (const XML_Char **)atts;
    +  appAtts = (const XML_Char **)parser->m_atts;
       for (i = 0; i < n; i++) {
    -    ATTRIBUTE *currAtt = &atts[i];
    +    ATTRIBUTE *currAtt = &parser->m_atts[i];
     #ifdef XML_ATTR_INFO
    -    XML_AttrInfo *currAttInfo = &attInfo[i];
    +    XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
     #endif
         /* add the name and value to the attribute list */
         ATTRIBUTE_ID *attId = getAttributeId(parser, enc, currAtt->name,
    @@ -2812,25 +3243,25 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
         if (!attId)
           return XML_ERROR_NO_MEMORY;
     #ifdef XML_ATTR_INFO
    -    currAttInfo->nameStart = parseEndByteIndex - (parseEndPtr - currAtt->name);
    +    currAttInfo->nameStart = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
         currAttInfo->nameEnd = currAttInfo->nameStart +
                                XmlNameLength(enc, currAtt->name);
    -    currAttInfo->valueStart = parseEndByteIndex -
    -                            (parseEndPtr - currAtt->valuePtr);
    -    currAttInfo->valueEnd = parseEndByteIndex - (parseEndPtr - currAtt->valueEnd);
    +    currAttInfo->valueStart = parser->m_parseEndByteIndex -
    +                            (parser->m_parseEndPtr - currAtt->valuePtr);
    +    currAttInfo->valueEnd = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->valueEnd);
     #endif
         /* Detect duplicate attributes by their QNames. This does not work when
            namespace processing is turned on and different prefixes for the same
            namespace are used. For this case we have a check further down.
         */
         if ((attId->name)[-1]) {
    -      if (enc == encoding)
    -        eventPtr = atts[i].name;
    +      if (enc == parser->m_encoding)
    +        parser->m_eventPtr = parser->m_atts[i].name;
           return XML_ERROR_DUPLICATE_ATTRIBUTE;
         }
         (attId->name)[-1] = 1;
         appAtts[attIndex++] = attId->name;
    -    if (!atts[i].normalized) {
    +    if (!parser->m_atts[i].normalized) {
           enum XML_Error result;
           XML_Bool isCdata = XML_TRUE;
     
    @@ -2847,20 +3278,20 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
     
           /* normalize the attribute value */
           result = storeAttributeValue(parser, enc, isCdata,
    -                                   atts[i].valuePtr, atts[i].valueEnd,
    -                                   &tempPool);
    +                                   parser->m_atts[i].valuePtr, parser->m_atts[i].valueEnd,
    +                                   &parser->m_tempPool);
           if (result)
             return result;
    -      appAtts[attIndex] = poolStart(&tempPool);
    -      poolFinish(&tempPool);
    +      appAtts[attIndex] = poolStart(&parser->m_tempPool);
    +      poolFinish(&parser->m_tempPool);
         }
         else {
           /* the value did not need normalizing */
    -      appAtts[attIndex] = poolStoreString(&tempPool, enc, atts[i].valuePtr,
    -                                          atts[i].valueEnd);
    +      appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc, parser->m_atts[i].valuePtr,
    +                                          parser->m_atts[i].valueEnd);
           if (appAtts[attIndex] == 0)
             return XML_ERROR_NO_MEMORY;
    -      poolFinish(&tempPool);
    +      poolFinish(&parser->m_tempPool);
         }
         /* handle prefixed attribute names */
         if (attId->prefix) {
    @@ -2884,16 +3315,16 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
       }
     
       /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
    -  nSpecifiedAtts = attIndex;
    +  parser->m_nSpecifiedAtts = attIndex;
       if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
         for (i = 0; i < attIndex; i += 2)
           if (appAtts[i] == elementType->idAtt->name) {
    -        idAttIndex = i;
    +        parser->m_idAttIndex = i;
             break;
           }
       }
       else
    -    idAttIndex = -1;
    +    parser->m_idAttIndex = -1;
     
       /* do attribute defaulting */
       for (i = 0; i < nDefaultAtts; i++) {
    @@ -2927,29 +3358,33 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
       i = 0;
       if (nPrefixes) {
         int j;  /* hash table index */
    -    unsigned long version = nsAttsVersion;
    -    int nsAttsSize = (int)1 << nsAttsPower;
    +    unsigned long version = parser->m_nsAttsVersion;
    +    int nsAttsSize = (int)1 << parser->m_nsAttsPower;
    +    unsigned char oldNsAttsPower = parser->m_nsAttsPower;
         /* size of hash table must be at least 2 * (# of prefixed attributes) */
    -    if ((nPrefixes << 1) >> nsAttsPower) {  /* true for nsAttsPower = 0 */
    +    if ((nPrefixes << 1) >> parser->m_nsAttsPower) {  /* true for m_nsAttsPower = 0 */
           NS_ATT *temp;
           /* hash table size must also be a power of 2 and >= 8 */
    -      while (nPrefixes >> nsAttsPower++);
    -      if (nsAttsPower < 3)
    -        nsAttsPower = 3;
    -      nsAttsSize = (int)1 << nsAttsPower;
    -      temp = (NS_ATT *)REALLOC(nsAtts, nsAttsSize * sizeof(NS_ATT));
    -      if (!temp)
    +      while (nPrefixes >> parser->m_nsAttsPower++);
    +      if (parser->m_nsAttsPower < 3)
    +        parser->m_nsAttsPower = 3;
    +      nsAttsSize = (int)1 << parser->m_nsAttsPower;
    +      temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));
    +      if (!temp) {
    +        /* Restore actual size of memory in m_nsAtts */
    +        parser->m_nsAttsPower = oldNsAttsPower;
             return XML_ERROR_NO_MEMORY;
    -      nsAtts = temp;
    -      version = 0;  /* force re-initialization of nsAtts hash table */
    +      }
    +      parser->m_nsAtts = temp;
    +      version = 0;  /* force re-initialization of m_nsAtts hash table */
         }
    -    /* using a version flag saves us from initializing nsAtts every time */
    +    /* using a version flag saves us from initializing m_nsAtts every time */
         if (!version) {  /* initialize version flags when version wraps around */
           version = INIT_ATTS_VERSION;
           for (j = nsAttsSize; j != 0; )
    -        nsAtts[--j].version = version;
    +        parser->m_nsAtts[--j].version = version;
         }
    -    nsAttsVersion = --version;
    +    parser->m_nsAttsVersion = --version;
     
         /* expand prefixed names and check for duplicates */
         for (; i < attIndex; i += 2) {
    @@ -2957,71 +3392,96 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
           if (s[-1] == 2) {  /* prefixed */
             ATTRIBUTE_ID *id;
             const BINDING *b;
    -        unsigned long uriHash = hash_secret_salt;
    +        unsigned long uriHash;
    +        struct siphash sip_state;
    +        struct sipkey sip_key;
    +
    +        copy_salt_to_sipkey(parser, &sip_key);
    +        sip24_init(&sip_state, &sip_key);
    +
             ((XML_Char *)s)[-1] = 0;  /* clear flag */
             id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
    -        if (!id || !id->prefix)
    -          return XML_ERROR_NO_MEMORY;
    +        if (!id || !id->prefix) {
    +          /* This code is walking through the appAtts array, dealing
    +           * with (in this case) a prefixed attribute name.  To be in
    +           * the array, the attribute must have already been bound, so
    +           * has to have passed through the hash table lookup once
    +           * already.  That implies that an entry for it already
    +           * exists, so the lookup above will return a pointer to
    +           * already allocated memory.  There is no opportunaity for
    +           * the allocator to fail, so the condition above cannot be
    +           * fulfilled.
    +           *
    +           * Since it is difficult to be certain that the above
    +           * analysis is complete, we retain the test and merely
    +           * remove the code from coverage tests.
    +           */
    +          return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
    +        }
             b = id->prefix->binding;
             if (!b)
               return XML_ERROR_UNBOUND_PREFIX;
     
    -        /* as we expand the name we also calculate its hash value */
             for (j = 0; j < b->uriLen; j++) {
               const XML_Char c = b->uri[j];
    -          if (!poolAppendChar(&tempPool, c))
    +          if (!poolAppendChar(&parser->m_tempPool, c))
                 return XML_ERROR_NO_MEMORY;
    -          uriHash = CHAR_HASH(uriHash, c);
             }
    +
    +        sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));
    +
             while (*s++ != XML_T(ASCII_COLON))
               ;
    +
    +        sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
    +
             do {  /* copies null terminator */
    -          const XML_Char c = *s;
    -          if (!poolAppendChar(&tempPool, *s))
    +          if (!poolAppendChar(&parser->m_tempPool, *s))
                 return XML_ERROR_NO_MEMORY;
    -          uriHash = CHAR_HASH(uriHash, c);
             } while (*s++);
     
    +        uriHash = (unsigned long)sip24_final(&sip_state);
    +
             { /* Check hash table for duplicate of expanded name (uriName).
                  Derived from code in lookup(parser, HASH_TABLE *table, ...).
               */
               unsigned char step = 0;
               unsigned long mask = nsAttsSize - 1;
               j = uriHash & mask;  /* index into hash table */
    -          while (nsAtts[j].version == version) {
    +          while (parser->m_nsAtts[j].version == version) {
                 /* for speed we compare stored hash values first */
    -            if (uriHash == nsAtts[j].hash) {
    -              const XML_Char *s1 = poolStart(&tempPool);
    -              const XML_Char *s2 = nsAtts[j].uriName;
    +            if (uriHash == parser->m_nsAtts[j].hash) {
    +              const XML_Char *s1 = poolStart(&parser->m_tempPool);
    +              const XML_Char *s2 = parser->m_nsAtts[j].uriName;
                   /* s1 is null terminated, but not s2 */
                   for (; *s1 == *s2 && *s1 != 0; s1++, s2++);
                   if (*s1 == 0)
                     return XML_ERROR_DUPLICATE_ATTRIBUTE;
                 }
                 if (!step)
    -              step = PROBE_STEP(uriHash, mask, nsAttsPower);
    +              step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
                 j < step ? (j += nsAttsSize - step) : (j -= step);
               }
             }
     
    -        if (ns_triplets) {  /* append namespace separator and prefix */
    -          tempPool.ptr[-1] = namespaceSeparator;
    +        if (parser->m_ns_triplets) {  /* append namespace separator and prefix */
    +          parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
               s = b->prefix->name;
               do {
    -            if (!poolAppendChar(&tempPool, *s))
    +            if (!poolAppendChar(&parser->m_tempPool, *s))
                   return XML_ERROR_NO_MEMORY;
               } while (*s++);
             }
     
             /* store expanded name in attribute list */
    -        s = poolStart(&tempPool);
    -        poolFinish(&tempPool);
    +        s = poolStart(&parser->m_tempPool);
    +        poolFinish(&parser->m_tempPool);
             appAtts[i] = s;
     
             /* fill empty slot with new version, uriName and hash value */
    -        nsAtts[j].version = version;
    -        nsAtts[j].hash = uriHash;
    -        nsAtts[j].uriName = s;
    +        parser->m_nsAtts[j].version = version;
    +        parser->m_nsAtts[j].hash = uriHash;
    +        parser->m_nsAtts[j].uriName = s;
     
             if (!--nPrefixes) {
               i += 2;
    @@ -3038,7 +3498,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
       for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
         binding->attId->name[-1] = 0;
     
    -  if (!ns)
    +  if (!parser->m_ns)
         return XML_ERROR_NONE;
     
       /* expand the element type name */
    @@ -3057,7 +3517,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
       else
         return XML_ERROR_NONE;
       prefixLen = 0;
    -  if (ns_triplets && binding->prefix->name) {
    +  if (parser->m_ns_triplets && binding->prefix->name) {
         for (; binding->prefix->name[prefixLen++];)
           ;  /* prefixLen includes null terminator */
       }
    @@ -3070,24 +3530,24 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
       n = i + binding->uriLen + prefixLen;
       if (n > binding->uriAlloc) {
         TAG *p;
    -    uri = (XML_Char *)MALLOC((n + EXPAND_SPARE) * sizeof(XML_Char));
    +    uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
         if (!uri)
           return XML_ERROR_NO_MEMORY;
         binding->uriAlloc = n + EXPAND_SPARE;
         memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
    -    for (p = tagStack; p; p = p->parent)
    +    for (p = parser->m_tagStack; p; p = p->parent)
           if (p->name.str == binding->uri)
             p->name.str = uri;
    -    FREE(binding->uri);
    +    FREE(parser, binding->uri);
         binding->uri = uri;
       }
    -  /* if namespaceSeparator != '\0' then uri includes it already */
    +  /* if m_namespaceSeparator != '\0' then uri includes it already */
       uri = binding->uri + binding->uriLen;
       memcpy(uri, localPart, i * sizeof(XML_Char));
       /* we always have a namespace separator between localPart and prefix */
       if (prefixLen) {
         uri += i - 1;
    -    *uri = namespaceSeparator;  /* replace null terminator */
    +    *uri = parser->m_namespaceSeparator;  /* replace null terminator */
         memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
       }
       tagNamePtr->str = binding->uri;
    @@ -3165,48 +3625,48 @@ addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
       if (isXMLNS)
         return XML_ERROR_RESERVED_NAMESPACE_URI;
     
    -  if (namespaceSeparator)
    +  if (parser->m_namespaceSeparator)
         len++;
    -  if (freeBindingList) {
    -    b = freeBindingList;
    +  if (parser->m_freeBindingList) {
    +    b = parser->m_freeBindingList;
         if (len > b->uriAlloc) {
    -      XML_Char *temp = (XML_Char *)REALLOC(b->uri,
    +      XML_Char *temp = (XML_Char *)REALLOC(parser, b->uri,
                               sizeof(XML_Char) * (len + EXPAND_SPARE));
           if (temp == NULL)
             return XML_ERROR_NO_MEMORY;
           b->uri = temp;
           b->uriAlloc = len + EXPAND_SPARE;
         }
    -    freeBindingList = b->nextTagBinding;
    +    parser->m_freeBindingList = b->nextTagBinding;
       }
       else {
    -    b = (BINDING *)MALLOC(sizeof(BINDING));
    +    b = (BINDING *)MALLOC(parser, sizeof(BINDING));
         if (!b)
           return XML_ERROR_NO_MEMORY;
    -    b->uri = (XML_Char *)MALLOC(sizeof(XML_Char) * (len + EXPAND_SPARE));
    +    b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
         if (!b->uri) {
    -      FREE(b);
    +      FREE(parser, b);
           return XML_ERROR_NO_MEMORY;
         }
         b->uriAlloc = len + EXPAND_SPARE;
       }
       b->uriLen = len;
       memcpy(b->uri, uri, len * sizeof(XML_Char));
    -  if (namespaceSeparator)
    -    b->uri[len - 1] = namespaceSeparator;
    +  if (parser->m_namespaceSeparator)
    +    b->uri[len - 1] = parser->m_namespaceSeparator;
       b->prefix = prefix;
       b->attId = attId;
       b->prevPrefixBinding = prefix->binding;
       /* NULL binding when default namespace undeclared */
    -  if (*uri == XML_T('\0') && prefix == &_dtd->defaultPrefix)
    +  if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
         prefix->binding = NULL;
       else
         prefix->binding = b;
       b->nextTagBinding = *bindingsPtr;
       *bindingsPtr = b;
       /* if attId == NULL then we are not starting a namespace scope */
    -  if (attId && startNamespaceDeclHandler)
    -    startNamespaceDeclHandler(handlerArg, prefix->name,
    +  if (attId && parser->m_startNamespaceDeclHandler)
    +    parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
                                   prefix->binding ? uri : 0);
       return XML_ERROR_NONE;
     }
    @@ -3220,17 +3680,17 @@ cdataSectionProcessor(XML_Parser parser,
                           const char *end,
                           const char **endPtr)
     {
    -  enum XML_Error result = doCdataSection(parser, encoding, &start, end,
    -                                         endPtr, (XML_Bool)!ps_finalBuffer);
    +  enum XML_Error result = doCdataSection(parser, parser->m_encoding, &start, end,
    +                                         endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
       if (result != XML_ERROR_NONE)
         return result;
       if (start) {
    -    if (parentParser) {  /* we are parsing an external entity */
    -      processor = externalEntityContentProcessor;
    +    if (parser->m_parentParser) {  /* we are parsing an external entity */
    +      parser->m_processor = externalEntityContentProcessor;
           return externalEntityContentProcessor(parser, start, end, endPtr);
         }
         else {
    -      processor = contentProcessor;
    +      parser->m_processor = contentProcessor;
           return contentProcessor(parser, start, end, endPtr);
         }
       }
    @@ -3251,14 +3711,14 @@ doCdataSection(XML_Parser parser,
       const char *s = *startPtr;
       const char **eventPP;
       const char **eventEndPP;
    -  if (enc == encoding) {
    -    eventPP = &eventPtr;
    +  if (enc == parser->m_encoding) {
    +    eventPP = &parser->m_eventPtr;
         *eventPP = s;
    -    eventEndPP = &eventEndPtr;
    +    eventEndPP = &parser->m_eventEndPtr;
       }
       else {
    -    eventPP = &(openInternalEntities->internalEventPtr);
    -    eventEndPP = &(openInternalEntities->internalEventEndPtr);
    +    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
    +    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
       }
       *eventPP = s;
       *startPtr = NULL;
    @@ -3269,51 +3729,51 @@ doCdataSection(XML_Parser parser,
         *eventEndPP = next;
         switch (tok) {
         case XML_TOK_CDATA_SECT_CLOSE:
    -      if (endCdataSectionHandler)
    -        endCdataSectionHandler(handlerArg);
    +      if (parser->m_endCdataSectionHandler)
    +        parser->m_endCdataSectionHandler(parser->m_handlerArg);
     #if 0
           /* see comment under XML_TOK_CDATA_SECT_OPEN */
    -      else if (characterDataHandler)
    -        characterDataHandler(handlerArg, dataBuf, 0);
    +      else if (parser->m_characterDataHandler)
    +        parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
     #endif
    -      else if (defaultHandler)
    +      else if (parser->m_defaultHandler)
             reportDefault(parser, enc, s, next);
           *startPtr = next;
           *nextPtr = next;
    -      if (ps_parsing == XML_FINISHED)
    +      if (parser->m_parsingStatus.parsing == XML_FINISHED)
             return XML_ERROR_ABORTED;
           else
             return XML_ERROR_NONE;
         case XML_TOK_DATA_NEWLINE:
    -      if (characterDataHandler) {
    +      if (parser->m_characterDataHandler) {
             XML_Char c = 0xA;
    -        characterDataHandler(handlerArg, &c, 1);
    +        parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
           }
    -      else if (defaultHandler)
    +      else if (parser->m_defaultHandler)
             reportDefault(parser, enc, s, next);
           break;
         case XML_TOK_DATA_CHARS:
           {
    -        XML_CharacterDataHandler charDataHandler = characterDataHandler;
    +        XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
             if (charDataHandler) {
               if (MUST_CONVERT(enc, s)) {
                 for (;;) {
    -              ICHAR *dataPtr = (ICHAR *)dataBuf;
    -              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
    +              ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
    +              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
                   *eventEndPP = next;
    -              charDataHandler(handlerArg, dataBuf,
    -                              (int)(dataPtr - (ICHAR *)dataBuf));
    +              charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
    +                              (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
                   if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
                     break;
                   *eventPP = s;
                 }
               }
               else
    -            charDataHandler(handlerArg,
    +            charDataHandler(parser->m_handlerArg,
                                 (XML_Char *)s,
                                 (int)((XML_Char *)next - (XML_Char *)s));
             }
    -        else if (defaultHandler)
    +        else if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
           }
           break;
    @@ -3334,12 +3794,20 @@ doCdataSection(XML_Parser parser,
           }
           return XML_ERROR_UNCLOSED_CDATA_SECTION;
         default:
    +      /* Every token returned by XmlCdataSectionTok() has its own
    +       * explicit case, so this default case will never be executed.
    +       * We retain it as a safety net and exclude it from the coverage
    +       * statistics.
    +       *
    +       * LCOV_EXCL_START
    +      */
           *eventPP = next;
           return XML_ERROR_UNEXPECTED_STATE;
    +      /* LCOV_EXCL_STOP */
         }
     
         *eventPP = s = next;
    -    switch (ps_parsing) {
    +    switch (parser->m_parsingStatus.parsing) {
         case XML_SUSPENDED:
           *nextPtr = next;
           return XML_ERROR_NONE;
    @@ -3362,12 +3830,12 @@ ignoreSectionProcessor(XML_Parser parser,
                            const char *end,
                            const char **endPtr)
     {
    -  enum XML_Error result = doIgnoreSection(parser, encoding, &start, end,
    -                                          endPtr, (XML_Bool)!ps_finalBuffer);
    +  enum XML_Error result = doIgnoreSection(parser, parser->m_encoding, &start, end,
    +                                          endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
       if (result != XML_ERROR_NONE)
         return result;
       if (start) {
    -    processor = prologProcessor;
    +    parser->m_processor = prologProcessor;
         return prologProcessor(parser, start, end, endPtr);
       }
       return result;
    @@ -3389,14 +3857,26 @@ doIgnoreSection(XML_Parser parser,
       const char *s = *startPtr;
       const char **eventPP;
       const char **eventEndPP;
    -  if (enc == encoding) {
    -    eventPP = &eventPtr;
    +  if (enc == parser->m_encoding) {
    +    eventPP = &parser->m_eventPtr;
         *eventPP = s;
    -    eventEndPP = &eventEndPtr;
    +    eventEndPP = &parser->m_eventEndPtr;
       }
       else {
    -    eventPP = &(openInternalEntities->internalEventPtr);
    -    eventEndPP = &(openInternalEntities->internalEventEndPtr);
    +    /* It's not entirely clear, but it seems the following two lines
    +     * of code cannot be executed.  The only occasions on which 'enc'
    +     * is not 'encoding' are when this function is called
    +     * from the internal entity processing, and IGNORE sections are an
    +     * error in internal entities.
    +     *
    +     * Since it really isn't clear that this is true, we keep the code
    +     * and just remove it from our coverage tests.
    +     *
    +     * LCOV_EXCL_START
    +     */
    +    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
    +    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
    +    /* LCOV_EXCL_STOP */
       }
       *eventPP = s;
       *startPtr = NULL;
    @@ -3404,11 +3884,11 @@ doIgnoreSection(XML_Parser parser,
       *eventEndPP = next;
       switch (tok) {
       case XML_TOK_IGNORE_SECT:
    -    if (defaultHandler)
    +    if (parser->m_defaultHandler)
           reportDefault(parser, enc, s, next);
         *startPtr = next;
         *nextPtr = next;
    -    if (ps_parsing == XML_FINISHED)
    +    if (parser->m_parsingStatus.parsing == XML_FINISHED)
           return XML_ERROR_ABORTED;
         else
           return XML_ERROR_NONE;
    @@ -3429,8 +3909,16 @@ doIgnoreSection(XML_Parser parser,
         }
         return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
       default:
    +    /* All of the tokens that XmlIgnoreSectionTok() returns have
    +     * explicit cases to handle them, so this default case is never
    +     * executed.  We keep it as a safety net anyway, and remove it
    +     * from our test coverage statistics.
    +     *
    +     * LCOV_EXCL_START
    +     */
         *eventPP = next;
         return XML_ERROR_UNEXPECTED_STATE;
    +    /* LCOV_EXCL_STOP */
       }
       /* not reached */
     }
    @@ -3443,27 +3931,28 @@ initializeEncoding(XML_Parser parser)
       const char *s;
     #ifdef XML_UNICODE
       char encodingBuf[128];
    -  if (!protocolEncodingName)
    +  /* See comments abount `protoclEncodingName` in parserInit() */
    +  if (!parser->m_protocolEncodingName)
         s = NULL;
       else {
         int i;
    -    for (i = 0; protocolEncodingName[i]; i++) {
    +    for (i = 0; parser->m_protocolEncodingName[i]; i++) {
           if (i == sizeof(encodingBuf) - 1
    -          || (protocolEncodingName[i] & ~0x7f) != 0) {
    +          || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
             encodingBuf[0] = '\0';
             break;
           }
    -      encodingBuf[i] = (char)protocolEncodingName[i];
    +      encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
         }
         encodingBuf[i] = '\0';
         s = encodingBuf;
       }
     #else
    -  s = protocolEncodingName;
    +  s = parser->m_protocolEncodingName;
     #endif
    -  if ((ns ? XmlInitEncodingNS : XmlInitEncoding)(&initEncoding, &encoding, s))
    +  if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(&parser->m_initEncoding, &parser->m_encoding, s))
         return XML_ERROR_NONE;
    -  return handleUnknownEncoding(parser, protocolEncodingName);
    +  return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
     }
     
     static enum XML_Error
    @@ -3477,13 +3966,13 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
       const char *versionend;
       const XML_Char *storedversion = NULL;
       int standalone = -1;
    -  if (!(ns
    +  if (!(parser->m_ns
             ? XmlParseXmlDeclNS
             : XmlParseXmlDecl)(isGeneralTextEntity,
    -                           encoding,
    +                           parser->m_encoding,
                                s,
                                next,
    -                           &eventPtr,
    +                           &parser->m_eventPtr,
                                &version,
                                &versionend,
                                &encodingName,
    @@ -3495,62 +3984,69 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
           return XML_ERROR_XML_DECL;
       }
       if (!isGeneralTextEntity && standalone == 1) {
    -    _dtd->standalone = XML_TRUE;
    +    parser->m_dtd->standalone = XML_TRUE;
     #ifdef XML_DTD
    -    if (paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
    -      paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
    +    if (parser->m_paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
    +      parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
     #endif /* XML_DTD */
       }
    -  if (xmlDeclHandler) {
    +  if (parser->m_xmlDeclHandler) {
         if (encodingName != NULL) {
    -      storedEncName = poolStoreString(&temp2Pool,
    -                                      encoding,
    +      storedEncName = poolStoreString(&parser->m_temp2Pool,
    +                                      parser->m_encoding,
                                           encodingName,
                                           encodingName
    -                                      + XmlNameLength(encoding, encodingName));
    +                                      + XmlNameLength(parser->m_encoding, encodingName));
           if (!storedEncName)
                   return XML_ERROR_NO_MEMORY;
    -      poolFinish(&temp2Pool);
    +      poolFinish(&parser->m_temp2Pool);
         }
         if (version) {
    -      storedversion = poolStoreString(&temp2Pool,
    -                                      encoding,
    +      storedversion = poolStoreString(&parser->m_temp2Pool,
    +                                      parser->m_encoding,
                                           version,
    -                                      versionend - encoding->minBytesPerChar);
    +                                      versionend - parser->m_encoding->minBytesPerChar);
           if (!storedversion)
             return XML_ERROR_NO_MEMORY;
         }
    -    xmlDeclHandler(handlerArg, storedversion, storedEncName, standalone);
    +    parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName, standalone);
       }
    -  else if (defaultHandler)
    -    reportDefault(parser, encoding, s, next);
    -  if (protocolEncodingName == NULL) {
    +  else if (parser->m_defaultHandler)
    +    reportDefault(parser, parser->m_encoding, s, next);
    +  if (parser->m_protocolEncodingName == NULL) {
         if (newEncoding) {
    -      if (newEncoding->minBytesPerChar != encoding->minBytesPerChar) {
    -        eventPtr = encodingName;
    +      /* Check that the specified encoding does not conflict with what
    +       * the parser has already deduced.  Do we have the same number
    +       * of bytes in the smallest representation of a character?  If
    +       * this is UTF-16, is it the same endianness?
    +       */
    +      if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
    +          || (newEncoding->minBytesPerChar == 2 &&
    +              newEncoding != parser->m_encoding)) {
    +        parser->m_eventPtr = encodingName;
             return XML_ERROR_INCORRECT_ENCODING;
           }
    -      encoding = newEncoding;
    +      parser->m_encoding = newEncoding;
         }
         else if (encodingName) {
           enum XML_Error result;
           if (!storedEncName) {
             storedEncName = poolStoreString(
    -          &temp2Pool, encoding, encodingName,
    -          encodingName + XmlNameLength(encoding, encodingName));
    +          &parser->m_temp2Pool, parser->m_encoding, encodingName,
    +          encodingName + XmlNameLength(parser->m_encoding, encodingName));
             if (!storedEncName)
               return XML_ERROR_NO_MEMORY;
           }
           result = handleUnknownEncoding(parser, storedEncName);
    -      poolClear(&temp2Pool);
    +      poolClear(&parser->m_temp2Pool);
           if (result == XML_ERROR_UNKNOWN_ENCODING)
    -        eventPtr = encodingName;
    +        parser->m_eventPtr = encodingName;
           return result;
         }
       }
     
       if (storedEncName || storedversion)
    -    poolClear(&temp2Pool);
    +    poolClear(&parser->m_temp2Pool);
     
       return XML_ERROR_NONE;
     }
    @@ -3558,7 +4054,7 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
     static enum XML_Error
     handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
     {
    -  if (unknownEncodingHandler) {
    +  if (parser->m_unknownEncodingHandler) {
         XML_Encoding info;
         int i;
         for (i = 0; i < 256; i++)
    @@ -3566,25 +4062,25 @@ handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
         info.convert = NULL;
         info.data = NULL;
         info.release = NULL;
    -    if (unknownEncodingHandler(unknownEncodingHandlerData, encodingName,
    +    if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName,
                                    &info)) {
           ENCODING *enc;
    -      unknownEncodingMem = MALLOC(XmlSizeOfUnknownEncoding());
    -      if (!unknownEncodingMem) {
    +      parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
    +      if (!parser->m_unknownEncodingMem) {
             if (info.release)
               info.release(info.data);
             return XML_ERROR_NO_MEMORY;
           }
    -      enc = (ns
    +      enc = (parser->m_ns
                  ? XmlInitUnknownEncodingNS
    -             : XmlInitUnknownEncoding)(unknownEncodingMem,
    +             : XmlInitUnknownEncoding)(parser->m_unknownEncodingMem,
                                            info.map,
                                            info.convert,
                                            info.data);
           if (enc) {
    -        unknownEncodingData = info.data;
    -        unknownEncodingRelease = info.release;
    -        encoding = enc;
    +        parser->m_unknownEncodingData = info.data;
    +        parser->m_unknownEncodingRelease = info.release;
    +        parser->m_encoding = enc;
             return XML_ERROR_NONE;
           }
         }
    @@ -3603,7 +4099,7 @@ prologInitProcessor(XML_Parser parser,
       enum XML_Error result = initializeEncoding(parser);
       if (result != XML_ERROR_NONE)
         return result;
    -  processor = prologProcessor;
    +  parser->m_processor = prologProcessor;
       return prologProcessor(parser, s, end, nextPtr);
     }
     
    @@ -3621,14 +4117,14 @@ externalParEntInitProcessor(XML_Parser parser,
     
       /* we know now that XML_Parse(Buffer) has been called,
          so we consider the external parameter entity read */
    -  _dtd->paramEntityRead = XML_TRUE;
    +  parser->m_dtd->paramEntityRead = XML_TRUE;
     
    -  if (prologState.inEntityValue) {
    -    processor = entityValueInitProcessor;
    +  if (parser->m_prologState.inEntityValue) {
    +    parser->m_processor = entityValueInitProcessor;
         return entityValueInitProcessor(parser, s, end, nextPtr);
       }
       else {
    -    processor = externalParEntProcessor;
    +    parser->m_processor = externalParEntProcessor;
         return externalParEntProcessor(parser, s, end, nextPtr);
       }
     }
    @@ -3642,13 +4138,13 @@ entityValueInitProcessor(XML_Parser parser,
       int tok;
       const char *start = s;
       const char *next = start;
    -  eventPtr = start;
    +  parser->m_eventPtr = start;
     
       for (;;) {
    -    tok = XmlPrologTok(encoding, start, end, &next);
    -    eventEndPtr = next;
    +    tok = XmlPrologTok(parser->m_encoding, start, end, &next);
    +    parser->m_eventEndPtr = next;
         if (tok <= 0) {
    -      if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
    +      if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
             *nextPtr = s;
             return XML_ERROR_NONE;
           }
    @@ -3664,24 +4160,23 @@ entityValueInitProcessor(XML_Parser parser,
             break;
           }
           /* found end of entity value - can store it now */
    -      return storeEntityValue(parser, encoding, s, end);
    +      return storeEntityValue(parser, parser->m_encoding, s, end);
         }
         else if (tok == XML_TOK_XML_DECL) {
           enum XML_Error result;
           result = processXmlDecl(parser, 0, start, next);
           if (result != XML_ERROR_NONE)
             return result;
    -      switch (ps_parsing) {
    -      case XML_SUSPENDED:
    -        *nextPtr = next;
    -        return XML_ERROR_NONE;
    -      case XML_FINISHED:
    +      /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED.  For that
    +       * to happen, a parameter entity parsing handler must have
    +       * attempted to suspend the parser, which fails and raises an
    +       * error.  The parser can be aborted, but can't be suspended.
    +       */
    +      if (parser->m_parsingStatus.parsing == XML_FINISHED)
             return XML_ERROR_ABORTED;
    -      default:
    -        *nextPtr = next;
    -      }
    +      *nextPtr = next;
           /* stop scanning for text declaration - we found one */
    -      processor = entityValueProcessor;
    +      parser->m_processor = entityValueProcessor;
           return entityValueProcessor(parser, next, end, nextPtr);
         }
         /* If we are at the end of the buffer, this would cause XmlPrologTok to
    @@ -3691,12 +4186,20 @@ entityValueInitProcessor(XML_Parser parser,
            then, when this routine is entered the next time, XmlPrologTok will
            return XML_TOK_INVALID, since the BOM is still in the buffer
         */
    -    else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) {
    +    else if (tok == XML_TOK_BOM && next == end && !parser->m_parsingStatus.finalBuffer) {
           *nextPtr = next;
           return XML_ERROR_NONE;
         }
    +    /* If we get this token, we have the start of what might be a
    +       normal tag, but not a declaration (i.e. it doesn't begin with
    +       "m_eventPtr = start;
       }
     }
     
    @@ -3709,9 +4212,9 @@ externalParEntProcessor(XML_Parser parser,
       const char *next = s;
       int tok;
     
    -  tok = XmlPrologTok(encoding, s, end, &next);
    +  tok = XmlPrologTok(parser->m_encoding, s, end, &next);
       if (tok <= 0) {
    -    if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
    +    if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
           *nextPtr = s;
           return XML_ERROR_NONE;
         }
    @@ -3733,12 +4236,12 @@ externalParEntProcessor(XML_Parser parser,
       */
       else if (tok == XML_TOK_BOM) {
         s = next;
    -    tok = XmlPrologTok(encoding, s, end, &next);
    +    tok = XmlPrologTok(parser->m_encoding, s, end, &next);
       }
     
    -  processor = prologProcessor;
    -  return doProlog(parser, encoding, s, end, tok, next,
    -                  nextPtr, (XML_Bool)!ps_finalBuffer);
    +  parser->m_processor = prologProcessor;
    +  return doProlog(parser, parser->m_encoding, s, end, tok, next,
    +                  nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
     }
     
     static enum XML_Error PTRCALL
    @@ -3749,13 +4252,13 @@ entityValueProcessor(XML_Parser parser,
     {
       const char *start = s;
       const char *next = s;
    -  const ENCODING *enc = encoding;
    +  const ENCODING *enc = parser->m_encoding;
       int tok;
     
       for (;;) {
         tok = XmlPrologTok(enc, start, end, &next);
         if (tok <= 0) {
    -      if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
    +      if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
             *nextPtr = s;
             return XML_ERROR_NONE;
           }
    @@ -3786,9 +4289,9 @@ prologProcessor(XML_Parser parser,
                     const char **nextPtr)
     {
       const char *next = s;
    -  int tok = XmlPrologTok(encoding, s, end, &next);
    -  return doProlog(parser, encoding, s, end, tok, next,
    -                  nextPtr, (XML_Bool)!ps_finalBuffer);
    +  int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
    +  return doProlog(parser, parser->m_encoding, s, end, tok, next,
    +                  nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
     }
     
     static enum XML_Error
    @@ -3825,19 +4328,19 @@ doProlog(XML_Parser parser,
       static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' };
     
       /* save one level of indirection */
    -  DTD * const dtd = _dtd;
    +  DTD * const dtd = parser->m_dtd;
     
       const char **eventPP;
       const char **eventEndPP;
       enum XML_Content_Quant quant;
     
    -  if (enc == encoding) {
    -    eventPP = &eventPtr;
    -    eventEndPP = &eventEndPtr;
    +  if (enc == parser->m_encoding) {
    +    eventPP = &parser->m_eventPtr;
    +    eventEndPP = &parser->m_eventEndPtr;
       }
       else {
    -    eventPP = &(openInternalEntities->internalEventPtr);
    -    eventEndPP = &(openInternalEntities->internalEventEndPtr);
    +    eventPP = &(parser->m_openInternalEntities->internalEventPtr);
    +    eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
       }
     
       for (;;) {
    @@ -3864,7 +4367,7 @@ doProlog(XML_Parser parser,
           case XML_TOK_NONE:
     #ifdef XML_DTD
             /* for internal PE NOT referenced between declarations */
    -        if (enc != encoding && !openInternalEntities->betweenDecl) {
    +        if (enc != parser->m_encoding && !parser->m_openInternalEntities->betweenDecl) {
               *nextPtr = s;
               return XML_ERROR_NONE;
             }
    @@ -3872,8 +4375,8 @@ doProlog(XML_Parser parser,
                complete markup, not only for external PEs, but also for
                internal PEs if the reference occurs between declarations.
             */
    -        if (isParamEntity || enc != encoding) {
    -          if (XmlTokenRole(&prologState, XML_TOK_NONE, end, end, enc)
    +        if (parser->m_isParamEntity || enc != parser->m_encoding) {
    +          if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
                   == XML_ROLE_ERROR)
                 return XML_ERROR_INCOMPLETE_PE;
               *nextPtr = s;
    @@ -3887,34 +4390,34 @@ doProlog(XML_Parser parser,
             break;
           }
         }
    -    role = XmlTokenRole(&prologState, tok, s, next, enc);
    +    role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
         switch (role) {
         case XML_ROLE_XML_DECL:
           {
             enum XML_Error result = processXmlDecl(parser, 0, s, next);
             if (result != XML_ERROR_NONE)
               return result;
    -        enc = encoding;
    +        enc = parser->m_encoding;
             handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_DOCTYPE_NAME:
    -      if (startDoctypeDeclHandler) {
    -        doctypeName = poolStoreString(&tempPool, enc, s, next);
    -        if (!doctypeName)
    +      if (parser->m_startDoctypeDeclHandler) {
    +        parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next);
    +        if (!parser->m_doctypeName)
               return XML_ERROR_NO_MEMORY;
    -        poolFinish(&tempPool);
    -        doctypePubid = NULL;
    +        poolFinish(&parser->m_tempPool);
    +        parser->m_doctypePubid = NULL;
             handleDefault = XML_FALSE;
           }
    -      doctypeSysid = NULL; /* always initialize to NULL */
    +      parser->m_doctypeSysid = NULL; /* always initialize to NULL */
           break;
         case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
    -      if (startDoctypeDeclHandler) {
    -        startDoctypeDeclHandler(handlerArg, doctypeName, doctypeSysid,
    -                                doctypePubid, 1);
    -        doctypeName = NULL;
    -        poolClear(&tempPool);
    +      if (parser->m_startDoctypeDeclHandler) {
    +        parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
    +                                parser->m_doctypePubid, 1);
    +        parser->m_doctypeName = NULL;
    +        poolClear(&parser->m_tempPool);
             handleDefault = XML_FALSE;
           }
           break;
    @@ -3924,34 +4427,34 @@ doProlog(XML_Parser parser,
             enum XML_Error result = processXmlDecl(parser, 1, s, next);
             if (result != XML_ERROR_NONE)
               return result;
    -        enc = encoding;
    +        enc = parser->m_encoding;
             handleDefault = XML_FALSE;
           }
           break;
     #endif /* XML_DTD */
         case XML_ROLE_DOCTYPE_PUBLIC_ID:
     #ifdef XML_DTD
    -      useForeignDTD = XML_FALSE;
    -      declEntity = (ENTITY *)lookup(parser,
    +      parser->m_useForeignDTD = XML_FALSE;
    +      parser->m_declEntity = (ENTITY *)lookup(parser,
                                         &dtd->paramEntities,
                                         externalSubsetName,
                                         sizeof(ENTITY));
    -      if (!declEntity)
    +      if (!parser->m_declEntity)
             return XML_ERROR_NO_MEMORY;
     #endif /* XML_DTD */
           dtd->hasParamEntityRefs = XML_TRUE;
    -      if (startDoctypeDeclHandler) {
    +      if (parser->m_startDoctypeDeclHandler) {
             XML_Char *pubId;
             if (!XmlIsPublicId(enc, s, next, eventPP))
               return XML_ERROR_PUBLICID;
    -        pubId = poolStoreString(&tempPool, enc,
    +        pubId = poolStoreString(&parser->m_tempPool, enc,
                                     s + enc->minBytesPerChar,
                                     next - enc->minBytesPerChar);
             if (!pubId)
               return XML_ERROR_NO_MEMORY;
             normalizePublicId(pubId);
    -        poolFinish(&tempPool);
    -        doctypePubid = pubId;
    +        poolFinish(&parser->m_tempPool);
    +        parser->m_doctypePubid = pubId;
             handleDefault = XML_FALSE;
             goto alreadyChecked;
           }
    @@ -3960,7 +4463,7 @@ doProlog(XML_Parser parser,
           if (!XmlIsPublicId(enc, s, next, eventPP))
             return XML_ERROR_PUBLICID;
         alreadyChecked:
    -      if (dtd->keepProcessing && declEntity) {
    +      if (dtd->keepProcessing && parser->m_declEntity) {
             XML_Char *tem = poolStoreString(&dtd->pool,
                                             enc,
                                             s + enc->minBytesPerChar,
    @@ -3968,38 +4471,47 @@ doProlog(XML_Parser parser,
             if (!tem)
               return XML_ERROR_NO_MEMORY;
             normalizePublicId(tem);
    -        declEntity->publicId = tem;
    +        parser->m_declEntity->publicId = tem;
             poolFinish(&dtd->pool);
    -        if (entityDeclHandler)
    +        /* Don't suppress the default handler if we fell through from
    +         * the XML_ROLE_DOCTYPE_PUBLIC_ID case.
    +         */
    +        if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
               handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_DOCTYPE_CLOSE:
    -      if (doctypeName) {
    -        startDoctypeDeclHandler(handlerArg, doctypeName,
    -                                doctypeSysid, doctypePubid, 0);
    -        poolClear(&tempPool);
    +      if (parser->m_doctypeName) {
    +        parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName,
    +                                parser->m_doctypeSysid, parser->m_doctypePubid, 0);
    +        poolClear(&parser->m_tempPool);
             handleDefault = XML_FALSE;
           }
    -      /* doctypeSysid will be non-NULL in the case of a previous
    -         XML_ROLE_DOCTYPE_SYSTEM_ID, even if startDoctypeDeclHandler
    +      /* parser->m_doctypeSysid will be non-NULL in the case of a previous
    +         XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
              was not set, indicating an external subset
           */
     #ifdef XML_DTD
    -      if (doctypeSysid || useForeignDTD) {
    +      if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
             XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
             dtd->hasParamEntityRefs = XML_TRUE;
    -        if (paramEntityParsing && externalEntityRefHandler) {
    +        if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
               ENTITY *entity = (ENTITY *)lookup(parser,
                                                 &dtd->paramEntities,
                                                 externalSubsetName,
                                                 sizeof(ENTITY));
    -          if (!entity)
    -            return XML_ERROR_NO_MEMORY;
    -          if (useForeignDTD)
    -            entity->base = curBase;
    +          if (!entity) {
    +            /* The external subset name "#" will have already been
    +             * inserted into the hash table at the start of the
    +             * external entity parsing, so no allocation will happen
    +             * and lookup() cannot fail.
    +             */
    +            return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
    +          }
    +          if (parser->m_useForeignDTD)
    +            entity->base = parser->m_curBase;
               dtd->paramEntityRead = XML_FALSE;
    -          if (!externalEntityRefHandler(externalEntityRefHandlerArg,
    +          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
                                             0,
                                             entity->base,
                                             entity->systemId,
    @@ -4007,22 +4519,22 @@ doProlog(XML_Parser parser,
                 return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
               if (dtd->paramEntityRead) {
                 if (!dtd->standalone &&
    -                notStandaloneHandler &&
    -                !notStandaloneHandler(handlerArg))
    +                parser->m_notStandaloneHandler &&
    +                !parser->m_notStandaloneHandler(parser->m_handlerArg))
                   return XML_ERROR_NOT_STANDALONE;
               }
               /* if we didn't read the foreign DTD then this means that there
                  is no external subset and we must reset dtd->hasParamEntityRefs
               */
    -          else if (!doctypeSysid)
    +          else if (!parser->m_doctypeSysid)
                 dtd->hasParamEntityRefs = hadParamEntityRefs;
               /* end of DTD - no need to update dtd->keepProcessing */
             }
    -        useForeignDTD = XML_FALSE;
    +        parser->m_useForeignDTD = XML_FALSE;
           }
     #endif /* XML_DTD */
    -      if (endDoctypeDeclHandler) {
    -        endDoctypeDeclHandler(handlerArg);
    +      if (parser->m_endDoctypeDeclHandler) {
    +        parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
             handleDefault = XML_FALSE;
           }
           break;
    @@ -4031,18 +4543,18 @@ doProlog(XML_Parser parser,
           /* if there is no DOCTYPE declaration then now is the
              last chance to read the foreign DTD
           */
    -      if (useForeignDTD) {
    +      if (parser->m_useForeignDTD) {
             XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
             dtd->hasParamEntityRefs = XML_TRUE;
    -        if (paramEntityParsing && externalEntityRefHandler) {
    +        if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
               ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
                                                 externalSubsetName,
                                                 sizeof(ENTITY));
               if (!entity)
                 return XML_ERROR_NO_MEMORY;
    -          entity->base = curBase;
    +          entity->base = parser->m_curBase;
               dtd->paramEntityRead = XML_FALSE;
    -          if (!externalEntityRefHandler(externalEntityRefHandlerArg,
    +          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
                                             0,
                                             entity->base,
                                             entity->systemId,
    @@ -4050,8 +4562,8 @@ doProlog(XML_Parser parser,
                 return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
               if (dtd->paramEntityRead) {
                 if (!dtd->standalone &&
    -                notStandaloneHandler &&
    -                !notStandaloneHandler(handlerArg))
    +                parser->m_notStandaloneHandler &&
    +                !parser->m_notStandaloneHandler(parser->m_handlerArg))
                   return XML_ERROR_NOT_STANDALONE;
               }
               /* if we didn't read the foreign DTD then this means that there
    @@ -4063,55 +4575,55 @@ doProlog(XML_Parser parser,
             }
           }
     #endif /* XML_DTD */
    -      processor = contentProcessor;
    +      parser->m_processor = contentProcessor;
           return contentProcessor(parser, s, end, nextPtr);
         case XML_ROLE_ATTLIST_ELEMENT_NAME:
    -      declElementType = getElementType(parser, enc, s, next);
    -      if (!declElementType)
    +      parser->m_declElementType = getElementType(parser, enc, s, next);
    +      if (!parser->m_declElementType)
             return XML_ERROR_NO_MEMORY;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_NAME:
    -      declAttributeId = getAttributeId(parser, enc, s, next);
    -      if (!declAttributeId)
    +      parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
    +      if (!parser->m_declAttributeId)
             return XML_ERROR_NO_MEMORY;
    -      declAttributeIsCdata = XML_FALSE;
    -      declAttributeType = NULL;
    -      declAttributeIsId = XML_FALSE;
    +      parser->m_declAttributeIsCdata = XML_FALSE;
    +      parser->m_declAttributeType = NULL;
    +      parser->m_declAttributeIsId = XML_FALSE;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
    -      declAttributeIsCdata = XML_TRUE;
    -      declAttributeType = atypeCDATA;
    +      parser->m_declAttributeIsCdata = XML_TRUE;
    +      parser->m_declAttributeType = atypeCDATA;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_ID:
    -      declAttributeIsId = XML_TRUE;
    -      declAttributeType = atypeID;
    +      parser->m_declAttributeIsId = XML_TRUE;
    +      parser->m_declAttributeType = atypeID;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
    -      declAttributeType = atypeIDREF;
    +      parser->m_declAttributeType = atypeIDREF;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
    -      declAttributeType = atypeIDREFS;
    +      parser->m_declAttributeType = atypeIDREFS;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
    -      declAttributeType = atypeENTITY;
    +      parser->m_declAttributeType = atypeENTITY;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
    -      declAttributeType = atypeENTITIES;
    +      parser->m_declAttributeType = atypeENTITIES;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
    -      declAttributeType = atypeNMTOKEN;
    +      parser->m_declAttributeType = atypeNMTOKEN;
           goto checkAttListDeclHandler;
         case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
    -      declAttributeType = atypeNMTOKENS;
    +      parser->m_declAttributeType = atypeNMTOKENS;
         checkAttListDeclHandler:
    -      if (dtd->keepProcessing && attlistDeclHandler)
    +      if (dtd->keepProcessing && parser->m_attlistDeclHandler)
             handleDefault = XML_FALSE;
           break;
         case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
         case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
    -      if (dtd->keepProcessing && attlistDeclHandler) {
    +      if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
             const XML_Char *prefix;
    -        if (declAttributeType) {
    +        if (parser->m_declAttributeType) {
               prefix = enumValueSep;
             }
             else {
    @@ -4119,37 +4631,37 @@ doProlog(XML_Parser parser,
                         ? notationPrefix
                         : enumValueStart);
             }
    -        if (!poolAppendString(&tempPool, prefix))
    +        if (!poolAppendString(&parser->m_tempPool, prefix))
               return XML_ERROR_NO_MEMORY;
    -        if (!poolAppend(&tempPool, enc, s, next))
    +        if (!poolAppend(&parser->m_tempPool, enc, s, next))
               return XML_ERROR_NO_MEMORY;
    -        declAttributeType = tempPool.start;
    +        parser->m_declAttributeType = parser->m_tempPool.start;
             handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
         case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
           if (dtd->keepProcessing) {
    -        if (!defineAttribute(declElementType, declAttributeId,
    -                             declAttributeIsCdata, declAttributeIsId,
    +        if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
    +                             parser->m_declAttributeIsCdata, parser->m_declAttributeIsId,
                                  0, parser))
               return XML_ERROR_NO_MEMORY;
    -        if (attlistDeclHandler && declAttributeType) {
    -          if (*declAttributeType == XML_T(ASCII_LPAREN)
    -              || (*declAttributeType == XML_T(ASCII_N)
    -                  && declAttributeType[1] == XML_T(ASCII_O))) {
    +        if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
    +          if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
    +              || (*parser->m_declAttributeType == XML_T(ASCII_N)
    +                  && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
                 /* Enumerated or Notation type */
    -            if (!poolAppendChar(&tempPool, XML_T(ASCII_RPAREN))
    -                || !poolAppendChar(&tempPool, XML_T('\0')))
    +            if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
    +                || !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
                   return XML_ERROR_NO_MEMORY;
    -            declAttributeType = tempPool.start;
    -            poolFinish(&tempPool);
    +            parser->m_declAttributeType = parser->m_tempPool.start;
    +            poolFinish(&parser->m_tempPool);
               }
               *eventEndPP = s;
    -          attlistDeclHandler(handlerArg, declElementType->name,
    -                             declAttributeId->name, declAttributeType,
    +          parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
    +                             parser->m_declAttributeId->name, parser->m_declAttributeType,
                                  0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
    -          poolClear(&tempPool);
    +          poolClear(&parser->m_tempPool);
               handleDefault = XML_FALSE;
             }
           }
    @@ -4159,7 +4671,7 @@ doProlog(XML_Parser parser,
           if (dtd->keepProcessing) {
             const XML_Char *attVal;
             enum XML_Error result =
    -          storeAttributeValue(parser, enc, declAttributeIsCdata,
    +          storeAttributeValue(parser, enc, parser->m_declAttributeIsCdata,
                                   s + enc->minBytesPerChar,
                                   next - enc->minBytesPerChar,
                                   &dtd->pool);
    @@ -4168,26 +4680,26 @@ doProlog(XML_Parser parser,
             attVal = poolStart(&dtd->pool);
             poolFinish(&dtd->pool);
             /* ID attributes aren't allowed to have a default */
    -        if (!defineAttribute(declElementType, declAttributeId,
    -                             declAttributeIsCdata, XML_FALSE, attVal, parser))
    +        if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
    +                             parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
               return XML_ERROR_NO_MEMORY;
    -        if (attlistDeclHandler && declAttributeType) {
    -          if (*declAttributeType == XML_T(ASCII_LPAREN)
    -              || (*declAttributeType == XML_T(ASCII_N)
    -                  && declAttributeType[1] == XML_T(ASCII_O))) {
    +        if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
    +          if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
    +              || (*parser->m_declAttributeType == XML_T(ASCII_N)
    +                  && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
                 /* Enumerated or Notation type */
    -            if (!poolAppendChar(&tempPool, XML_T(ASCII_RPAREN))
    -                || !poolAppendChar(&tempPool, XML_T('\0')))
    +            if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
    +                || !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
                   return XML_ERROR_NO_MEMORY;
    -            declAttributeType = tempPool.start;
    -            poolFinish(&tempPool);
    +            parser->m_declAttributeType = parser->m_tempPool.start;
    +            poolFinish(&parser->m_tempPool);
               }
               *eventEndPP = s;
    -          attlistDeclHandler(handlerArg, declElementType->name,
    -                             declAttributeId->name, declAttributeType,
    +          parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
    +                             parser->m_declAttributeId->name, parser->m_declAttributeType,
                                  attVal,
                                  role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
    -          poolClear(&tempPool);
    +          poolClear(&parser->m_tempPool);
               handleDefault = XML_FALSE;
             }
           }
    @@ -4197,18 +4709,18 @@ doProlog(XML_Parser parser,
             enum XML_Error result = storeEntityValue(parser, enc,
                                                 s + enc->minBytesPerChar,
                                                 next - enc->minBytesPerChar);
    -        if (declEntity) {
    -          declEntity->textPtr = poolStart(&dtd->entityValuePool);
    -          declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
    +        if (parser->m_declEntity) {
    +          parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
    +          parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
               poolFinish(&dtd->entityValuePool);
    -          if (entityDeclHandler) {
    +          if (parser->m_entityDeclHandler) {
                 *eventEndPP = s;
    -            entityDeclHandler(handlerArg,
    -                              declEntity->name,
    -                              declEntity->is_param,
    -                              declEntity->textPtr,
    -                              declEntity->textLen,
    -                              curBase, 0, 0, 0);
    +            parser->m_entityDeclHandler(parser->m_handlerArg,
    +                              parser->m_declEntity->name,
    +                              parser->m_declEntity->is_param,
    +                              parser->m_declEntity->textPtr,
    +                              parser->m_declEntity->textLen,
    +                              parser->m_curBase, 0, 0, 0);
                 handleDefault = XML_FALSE;
               }
             }
    @@ -4220,97 +4732,100 @@ doProlog(XML_Parser parser,
           break;
         case XML_ROLE_DOCTYPE_SYSTEM_ID:
     #ifdef XML_DTD
    -      useForeignDTD = XML_FALSE;
    +      parser->m_useForeignDTD = XML_FALSE;
     #endif /* XML_DTD */
           dtd->hasParamEntityRefs = XML_TRUE;
    -      if (startDoctypeDeclHandler) {
    -        doctypeSysid = poolStoreString(&tempPool, enc,
    +      if (parser->m_startDoctypeDeclHandler) {
    +        parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
                                            s + enc->minBytesPerChar,
                                            next - enc->minBytesPerChar);
    -        if (doctypeSysid == NULL)
    +        if (parser->m_doctypeSysid == NULL)
               return XML_ERROR_NO_MEMORY;
    -        poolFinish(&tempPool);
    +        poolFinish(&parser->m_tempPool);
             handleDefault = XML_FALSE;
           }
     #ifdef XML_DTD
           else
    -        /* use externalSubsetName to make doctypeSysid non-NULL
    -           for the case where no startDoctypeDeclHandler is set */
    -        doctypeSysid = externalSubsetName;
    +        /* use externalSubsetName to make parser->m_doctypeSysid non-NULL
    +           for the case where no parser->m_startDoctypeDeclHandler is set */
    +        parser->m_doctypeSysid = externalSubsetName;
     #endif /* XML_DTD */
           if (!dtd->standalone
     #ifdef XML_DTD
    -          && !paramEntityParsing
    +          && !parser->m_paramEntityParsing
     #endif /* XML_DTD */
    -          && notStandaloneHandler
    -          && !notStandaloneHandler(handlerArg))
    +          && parser->m_notStandaloneHandler
    +          && !parser->m_notStandaloneHandler(parser->m_handlerArg))
             return XML_ERROR_NOT_STANDALONE;
     #ifndef XML_DTD
           break;
     #else /* XML_DTD */
    -      if (!declEntity) {
    -        declEntity = (ENTITY *)lookup(parser,
    +      if (!parser->m_declEntity) {
    +        parser->m_declEntity = (ENTITY *)lookup(parser,
                                           &dtd->paramEntities,
                                           externalSubsetName,
                                           sizeof(ENTITY));
    -        if (!declEntity)
    +        if (!parser->m_declEntity)
               return XML_ERROR_NO_MEMORY;
    -        declEntity->publicId = NULL;
    +        parser->m_declEntity->publicId = NULL;
           }
    -      /* fall through */
     #endif /* XML_DTD */
    +      /* fall through */
         case XML_ROLE_ENTITY_SYSTEM_ID:
    -      if (dtd->keepProcessing && declEntity) {
    -        declEntity->systemId = poolStoreString(&dtd->pool, enc,
    +      if (dtd->keepProcessing && parser->m_declEntity) {
    +        parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc,
                                                    s + enc->minBytesPerChar,
                                                    next - enc->minBytesPerChar);
    -        if (!declEntity->systemId)
    +        if (!parser->m_declEntity->systemId)
               return XML_ERROR_NO_MEMORY;
    -        declEntity->base = curBase;
    +        parser->m_declEntity->base = parser->m_curBase;
             poolFinish(&dtd->pool);
    -        if (entityDeclHandler)
    +        /* Don't suppress the default handler if we fell through from
    +         * the XML_ROLE_DOCTYPE_SYSTEM_ID case.
    +         */
    +        if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
               handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_ENTITY_COMPLETE:
    -      if (dtd->keepProcessing && declEntity && entityDeclHandler) {
    +      if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) {
             *eventEndPP = s;
    -        entityDeclHandler(handlerArg,
    -                          declEntity->name,
    -                          declEntity->is_param,
    +        parser->m_entityDeclHandler(parser->m_handlerArg,
    +                          parser->m_declEntity->name,
    +                          parser->m_declEntity->is_param,
                               0,0,
    -                          declEntity->base,
    -                          declEntity->systemId,
    -                          declEntity->publicId,
    +                          parser->m_declEntity->base,
    +                          parser->m_declEntity->systemId,
    +                          parser->m_declEntity->publicId,
                               0);
             handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_ENTITY_NOTATION_NAME:
    -      if (dtd->keepProcessing && declEntity) {
    -        declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
    -        if (!declEntity->notation)
    +      if (dtd->keepProcessing && parser->m_declEntity) {
    +        parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
    +        if (!parser->m_declEntity->notation)
               return XML_ERROR_NO_MEMORY;
             poolFinish(&dtd->pool);
    -        if (unparsedEntityDeclHandler) {
    +        if (parser->m_unparsedEntityDeclHandler) {
               *eventEndPP = s;
    -          unparsedEntityDeclHandler(handlerArg,
    -                                    declEntity->name,
    -                                    declEntity->base,
    -                                    declEntity->systemId,
    -                                    declEntity->publicId,
    -                                    declEntity->notation);
    +          parser->m_unparsedEntityDeclHandler(parser->m_handlerArg,
    +                                    parser->m_declEntity->name,
    +                                    parser->m_declEntity->base,
    +                                    parser->m_declEntity->systemId,
    +                                    parser->m_declEntity->publicId,
    +                                    parser->m_declEntity->notation);
               handleDefault = XML_FALSE;
             }
    -        else if (entityDeclHandler) {
    +        else if (parser->m_entityDeclHandler) {
               *eventEndPP = s;
    -          entityDeclHandler(handlerArg,
    -                            declEntity->name,
    +          parser->m_entityDeclHandler(parser->m_handlerArg,
    +                            parser->m_declEntity->name,
                                 0,0,0,
    -                            declEntity->base,
    -                            declEntity->systemId,
    -                            declEntity->publicId,
    -                            declEntity->notation);
    +                            parser->m_declEntity->base,
    +                            parser->m_declEntity->systemId,
    +                            parser->m_declEntity->publicId,
    +                            parser->m_declEntity->notation);
               handleDefault = XML_FALSE;
             }
           }
    @@ -4318,36 +4833,36 @@ doProlog(XML_Parser parser,
         case XML_ROLE_GENERAL_ENTITY_NAME:
           {
             if (XmlPredefinedEntityName(enc, s, next)) {
    -          declEntity = NULL;
    +          parser->m_declEntity = NULL;
               break;
             }
             if (dtd->keepProcessing) {
               const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
               if (!name)
                 return XML_ERROR_NO_MEMORY;
    -          declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name,
    +          parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name,
                                             sizeof(ENTITY));
    -          if (!declEntity)
    +          if (!parser->m_declEntity)
                 return XML_ERROR_NO_MEMORY;
    -          if (declEntity->name != name) {
    +          if (parser->m_declEntity->name != name) {
                 poolDiscard(&dtd->pool);
    -            declEntity = NULL;
    +            parser->m_declEntity = NULL;
               }
               else {
                 poolFinish(&dtd->pool);
    -            declEntity->publicId = NULL;
    -            declEntity->is_param = XML_FALSE;
    +            parser->m_declEntity->publicId = NULL;
    +            parser->m_declEntity->is_param = XML_FALSE;
                 /* if we have a parent parser or are reading an internal parameter
                    entity, then the entity declaration is not considered "internal"
                 */
    -            declEntity->is_internal = !(parentParser || openInternalEntities);
    -            if (entityDeclHandler)
    +            parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
    +            if (parser->m_entityDeclHandler)
                   handleDefault = XML_FALSE;
               }
             }
             else {
               poolDiscard(&dtd->pool);
    -          declEntity = NULL;
    +          parser->m_declEntity = NULL;
             }
           }
           break;
    @@ -4357,90 +4872,90 @@ doProlog(XML_Parser parser,
             const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
             if (!name)
               return XML_ERROR_NO_MEMORY;
    -        declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
    +        parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
                                                name, sizeof(ENTITY));
    -        if (!declEntity)
    +        if (!parser->m_declEntity)
               return XML_ERROR_NO_MEMORY;
    -        if (declEntity->name != name) {
    +        if (parser->m_declEntity->name != name) {
               poolDiscard(&dtd->pool);
    -          declEntity = NULL;
    +          parser->m_declEntity = NULL;
             }
             else {
               poolFinish(&dtd->pool);
    -          declEntity->publicId = NULL;
    -          declEntity->is_param = XML_TRUE;
    +          parser->m_declEntity->publicId = NULL;
    +          parser->m_declEntity->is_param = XML_TRUE;
               /* if we have a parent parser or are reading an internal parameter
                  entity, then the entity declaration is not considered "internal"
               */
    -          declEntity->is_internal = !(parentParser || openInternalEntities);
    -          if (entityDeclHandler)
    +          parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
    +          if (parser->m_entityDeclHandler)
                 handleDefault = XML_FALSE;
             }
           }
           else {
             poolDiscard(&dtd->pool);
    -        declEntity = NULL;
    +        parser->m_declEntity = NULL;
           }
     #else /* not XML_DTD */
    -      declEntity = NULL;
    +      parser->m_declEntity = NULL;
     #endif /* XML_DTD */
           break;
         case XML_ROLE_NOTATION_NAME:
    -      declNotationPublicId = NULL;
    -      declNotationName = NULL;
    -      if (notationDeclHandler) {
    -        declNotationName = poolStoreString(&tempPool, enc, s, next);
    -        if (!declNotationName)
    +      parser->m_declNotationPublicId = NULL;
    +      parser->m_declNotationName = NULL;
    +      if (parser->m_notationDeclHandler) {
    +        parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next);
    +        if (!parser->m_declNotationName)
               return XML_ERROR_NO_MEMORY;
    -        poolFinish(&tempPool);
    +        poolFinish(&parser->m_tempPool);
             handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_NOTATION_PUBLIC_ID:
           if (!XmlIsPublicId(enc, s, next, eventPP))
             return XML_ERROR_PUBLICID;
    -      if (declNotationName) {  /* means notationDeclHandler != NULL */
    -        XML_Char *tem = poolStoreString(&tempPool,
    +      if (parser->m_declNotationName) {  /* means m_notationDeclHandler != NULL */
    +        XML_Char *tem = poolStoreString(&parser->m_tempPool,
                                             enc,
                                             s + enc->minBytesPerChar,
                                             next - enc->minBytesPerChar);
             if (!tem)
               return XML_ERROR_NO_MEMORY;
             normalizePublicId(tem);
    -        declNotationPublicId = tem;
    -        poolFinish(&tempPool);
    +        parser->m_declNotationPublicId = tem;
    +        poolFinish(&parser->m_tempPool);
             handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_NOTATION_SYSTEM_ID:
    -      if (declNotationName && notationDeclHandler) {
    +      if (parser->m_declNotationName && parser->m_notationDeclHandler) {
             const XML_Char *systemId
    -          = poolStoreString(&tempPool, enc,
    +          = poolStoreString(&parser->m_tempPool, enc,
                                 s + enc->minBytesPerChar,
                                 next - enc->minBytesPerChar);
             if (!systemId)
               return XML_ERROR_NO_MEMORY;
             *eventEndPP = s;
    -        notationDeclHandler(handlerArg,
    -                            declNotationName,
    -                            curBase,
    +        parser->m_notationDeclHandler(parser->m_handlerArg,
    +                            parser->m_declNotationName,
    +                            parser->m_curBase,
                                 systemId,
    -                            declNotationPublicId);
    +                            parser->m_declNotationPublicId);
             handleDefault = XML_FALSE;
           }
    -      poolClear(&tempPool);
    +      poolClear(&parser->m_tempPool);
           break;
         case XML_ROLE_NOTATION_NO_SYSTEM_ID:
    -      if (declNotationPublicId && notationDeclHandler) {
    +      if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
             *eventEndPP = s;
    -        notationDeclHandler(handlerArg,
    -                            declNotationName,
    -                            curBase,
    +        parser->m_notationDeclHandler(parser->m_handlerArg,
    +                            parser->m_declNotationName,
    +                            parser->m_curBase,
                                 0,
    -                            declNotationPublicId);
    +                            parser->m_declNotationPublicId);
             handleDefault = XML_FALSE;
           }
    -      poolClear(&tempPool);
    +      poolClear(&parser->m_tempPool);
           break;
         case XML_ROLE_ERROR:
           switch (tok) {
    @@ -4457,41 +4972,45 @@ doProlog(XML_Parser parser,
         case XML_ROLE_IGNORE_SECT:
           {
             enum XML_Error result;
    -        if (defaultHandler)
    +        if (parser->m_defaultHandler)
               reportDefault(parser, enc, s, next);
             handleDefault = XML_FALSE;
             result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
             if (result != XML_ERROR_NONE)
               return result;
             else if (!next) {
    -          processor = ignoreSectionProcessor;
    +          parser->m_processor = ignoreSectionProcessor;
               return result;
             }
           }
           break;
     #endif /* XML_DTD */
         case XML_ROLE_GROUP_OPEN:
    -      if (prologState.level >= groupSize) {
    -        if (groupSize) {
    -          char *temp = (char *)REALLOC(groupConnector, groupSize *= 2);
    -          if (temp == NULL)
    +      if (parser->m_prologState.level >= parser->m_groupSize) {
    +        if (parser->m_groupSize) {
    +          char *temp = (char *)REALLOC(parser, parser->m_groupConnector, parser->m_groupSize *= 2);
    +          if (temp == NULL) {
    +            parser->m_groupSize /= 2;
                 return XML_ERROR_NO_MEMORY;
    -          groupConnector = temp;
    +          }
    +          parser->m_groupConnector = temp;
               if (dtd->scaffIndex) {
    -            int *temp = (int *)REALLOC(dtd->scaffIndex,
    -                          groupSize * sizeof(int));
    +            int *temp = (int *)REALLOC(parser, dtd->scaffIndex,
    +                          parser->m_groupSize * sizeof(int));
                 if (temp == NULL)
                   return XML_ERROR_NO_MEMORY;
                 dtd->scaffIndex = temp;
               }
             }
             else {
    -          groupConnector = (char *)MALLOC(groupSize = 32);
    -          if (!groupConnector)
    +          parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32);
    +          if (!parser->m_groupConnector) {
    +            parser->m_groupSize = 0;
                 return XML_ERROR_NO_MEMORY;
    +          }
             }
           }
    -      groupConnector[prologState.level] = 0;
    +      parser->m_groupConnector[parser->m_prologState.level] = 0;
           if (dtd->in_eldecl) {
             int myindex = nextScaffoldPart(parser);
             if (myindex < 0)
    @@ -4499,37 +5018,37 @@ doProlog(XML_Parser parser,
             dtd->scaffIndex[dtd->scaffLevel] = myindex;
             dtd->scaffLevel++;
             dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
    -        if (elementDeclHandler)
    +        if (parser->m_elementDeclHandler)
               handleDefault = XML_FALSE;
           }
           break;
         case XML_ROLE_GROUP_SEQUENCE:
    -      if (groupConnector[prologState.level] == ASCII_PIPE)
    +      if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
             return XML_ERROR_SYNTAX;
    -      groupConnector[prologState.level] = ASCII_COMMA;
    -      if (dtd->in_eldecl && elementDeclHandler)
    +      parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
    +      if (dtd->in_eldecl && parser->m_elementDeclHandler)
             handleDefault = XML_FALSE;
           break;
         case XML_ROLE_GROUP_CHOICE:
    -      if (groupConnector[prologState.level] == ASCII_COMMA)
    +      if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
             return XML_ERROR_SYNTAX;
           if (dtd->in_eldecl
    -          && !groupConnector[prologState.level]
    +          && !parser->m_groupConnector[parser->m_prologState.level]
               && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
                   != XML_CTYPE_MIXED)
               ) {
             dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
                 = XML_CTYPE_CHOICE;
    -        if (elementDeclHandler)
    +        if (parser->m_elementDeclHandler)
               handleDefault = XML_FALSE;
           }
    -      groupConnector[prologState.level] = ASCII_PIPE;
    +      parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
           break;
         case XML_ROLE_PARAM_ENTITY_REF:
     #ifdef XML_DTD
         case XML_ROLE_INNER_PARAM_ENTITY_REF:
           dtd->hasParamEntityRefs = XML_TRUE;
    -      if (!paramEntityParsing)
    +      if (!parser->m_paramEntityParsing)
             dtd->keepProcessing = dtd->standalone;
           else {
             const XML_Char *name;
    @@ -4545,20 +5064,41 @@ doProlog(XML_Parser parser,
                if yes, check that the entity exists, and that it is internal,
                otherwise call the skipped entity handler
             */
    -        if (prologState.documentEntity &&
    +        if (parser->m_prologState.documentEntity &&
                 (dtd->standalone
    -             ? !openInternalEntities
    +             ? !parser->m_openInternalEntities
                  : !dtd->hasParamEntityRefs)) {
               if (!entity)
                 return XML_ERROR_UNDEFINED_ENTITY;
    -          else if (!entity->is_internal)
    -            return XML_ERROR_ENTITY_DECLARED_IN_PE;
    +          else if (!entity->is_internal) {
    +            /* It's hard to exhaustively search the code to be sure,
    +             * but there doesn't seem to be a way of executing the
    +             * following line.  There are two cases:
    +             *
    +             * If 'standalone' is false, the DTD must have no
    +             * parameter entities or we wouldn't have passed the outer
    +             * 'if' statement.  That measn the only entity in the hash
    +             * table is the external subset name "#" which cannot be
    +             * given as a parameter entity name in XML syntax, so the
    +             * lookup must have returned NULL and we don't even reach
    +             * the test for an internal entity.
    +             *
    +             * If 'standalone' is true, it does not seem to be
    +             * possible to create entities taking this code path that
    +             * are not internal entities, so fail the test above.
    +             *
    +             * Because this analysis is very uncertain, the code is
    +             * being left in place and merely removed from the
    +             * coverage test statistics.
    +             */
    +            return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
    +          }
             }
             else if (!entity) {
               dtd->keepProcessing = dtd->standalone;
               /* cannot report skipped entities in declarations */
    -          if ((role == XML_ROLE_PARAM_ENTITY_REF) && skippedEntityHandler) {
    -            skippedEntityHandler(handlerArg, name, 1);
    +          if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) {
    +            parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
                 handleDefault = XML_FALSE;
               }
               break;
    @@ -4575,10 +5115,10 @@ doProlog(XML_Parser parser,
               handleDefault = XML_FALSE;
               break;
             }
    -        if (externalEntityRefHandler) {
    +        if (parser->m_externalEntityRefHandler) {
               dtd->paramEntityRead = XML_FALSE;
               entity->open = XML_TRUE;
    -          if (!externalEntityRefHandler(externalEntityRefHandlerArg,
    +          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
                                             0,
                                             entity->base,
                                             entity->systemId,
    @@ -4600,17 +5140,17 @@ doProlog(XML_Parser parser,
           }
     #endif /* XML_DTD */
           if (!dtd->standalone &&
    -          notStandaloneHandler &&
    -          !notStandaloneHandler(handlerArg))
    +          parser->m_notStandaloneHandler &&
    +          !parser->m_notStandaloneHandler(parser->m_handlerArg))
             return XML_ERROR_NOT_STANDALONE;
           break;
     
         /* Element declaration stuff */
     
         case XML_ROLE_ELEMENT_NAME:
    -      if (elementDeclHandler) {
    -        declElementType = getElementType(parser, enc, s, next);
    -        if (!declElementType)
    +      if (parser->m_elementDeclHandler) {
    +        parser->m_declElementType = getElementType(parser, enc, s, next);
    +        if (!parser->m_declElementType)
               return XML_ERROR_NO_MEMORY;
             dtd->scaffLevel = 0;
             dtd->scaffCount = 0;
    @@ -4622,8 +5162,8 @@ doProlog(XML_Parser parser,
         case XML_ROLE_CONTENT_ANY:
         case XML_ROLE_CONTENT_EMPTY:
           if (dtd->in_eldecl) {
    -        if (elementDeclHandler) {
    -          XML_Content * content = (XML_Content *) MALLOC(sizeof(XML_Content));
    +        if (parser->m_elementDeclHandler) {
    +          XML_Content * content = (XML_Content *) MALLOC(parser, sizeof(XML_Content));
               if (!content)
                 return XML_ERROR_NO_MEMORY;
               content->quant = XML_CQUANT_NONE;
    @@ -4634,7 +5174,7 @@ doProlog(XML_Parser parser,
                                XML_CTYPE_ANY :
                                XML_CTYPE_EMPTY);
               *eventEndPP = s;
    -          elementDeclHandler(handlerArg, declElementType->name, content);
    +          parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, content);
               handleDefault = XML_FALSE;
             }
             dtd->in_eldecl = XML_FALSE;
    @@ -4645,7 +5185,7 @@ doProlog(XML_Parser parser,
           if (dtd->in_eldecl) {
             dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
                 = XML_CTYPE_MIXED;
    -        if (elementDeclHandler)
    +        if (parser->m_elementDeclHandler)
               handleDefault = XML_FALSE;
           }
           break;
    @@ -4682,7 +5222,7 @@ doProlog(XML_Parser parser,
             nameLen = 0;
             for (; name[nameLen++]; );
             dtd->contentStringLen +=  nameLen;
    -        if (elementDeclHandler)
    +        if (parser->m_elementDeclHandler)
               handleDefault = XML_FALSE;
           }
           break;
    @@ -4700,7 +5240,7 @@ doProlog(XML_Parser parser,
           quant = XML_CQUANT_PLUS;
         closeGroup:
           if (dtd->in_eldecl) {
    -        if (elementDeclHandler)
    +        if (parser->m_elementDeclHandler)
               handleDefault = XML_FALSE;
             dtd->scaffLevel--;
             dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
    @@ -4710,7 +5250,7 @@ doProlog(XML_Parser parser,
                 if (!model)
                   return XML_ERROR_NO_MEMORY;
                 *eventEndPP = s;
    -            elementDeclHandler(handlerArg, declElementType->name, model);
    +            parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, model);
               }
               dtd->in_eldecl = XML_FALSE;
               dtd->contentStringLen = 0;
    @@ -4737,31 +5277,31 @@ doProlog(XML_Parser parser,
           }
           break;
         case XML_ROLE_DOCTYPE_NONE:
    -      if (startDoctypeDeclHandler)
    +      if (parser->m_startDoctypeDeclHandler)
             handleDefault = XML_FALSE;
           break;
         case XML_ROLE_ENTITY_NONE:
    -      if (dtd->keepProcessing && entityDeclHandler)
    +      if (dtd->keepProcessing && parser->m_entityDeclHandler)
             handleDefault = XML_FALSE;
           break;
         case XML_ROLE_NOTATION_NONE:
    -      if (notationDeclHandler)
    +      if (parser->m_notationDeclHandler)
             handleDefault = XML_FALSE;
           break;
         case XML_ROLE_ATTLIST_NONE:
    -      if (dtd->keepProcessing && attlistDeclHandler)
    +      if (dtd->keepProcessing && parser->m_attlistDeclHandler)
             handleDefault = XML_FALSE;
           break;
         case XML_ROLE_ELEMENT_NONE:
    -      if (elementDeclHandler)
    +      if (parser->m_elementDeclHandler)
             handleDefault = XML_FALSE;
           break;
         } /* end of big switch */
     
    -    if (handleDefault && defaultHandler)
    +    if (handleDefault && parser->m_defaultHandler)
           reportDefault(parser, enc, s, next);
     
    -    switch (ps_parsing) {
    +    switch (parser->m_parsingStatus.parsing) {
         case XML_SUSPENDED:
           *nextPtr = next;
           return XML_ERROR_NONE;
    @@ -4781,18 +5321,18 @@ epilogProcessor(XML_Parser parser,
                     const char *end,
                     const char **nextPtr)
     {
    -  processor = epilogProcessor;
    -  eventPtr = s;
    +  parser->m_processor = epilogProcessor;
    +  parser->m_eventPtr = s;
       for (;;) {
         const char *next = NULL;
    -    int tok = XmlPrologTok(encoding, s, end, &next);
    -    eventEndPtr = next;
    +    int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
    +    parser->m_eventEndPtr = next;
         switch (tok) {
         /* report partial linebreak - it might be the last token */
         case -XML_TOK_PROLOG_S:
    -      if (defaultHandler) {
    -        reportDefault(parser, encoding, s, next);
    -        if (ps_parsing == XML_FINISHED)
    +      if (parser->m_defaultHandler) {
    +        reportDefault(parser, parser->m_encoding, s, next);
    +        if (parser->m_parsingStatus.parsing == XML_FINISHED)
               return XML_ERROR_ABORTED;
           }
           *nextPtr = next;
    @@ -4801,28 +5341,28 @@ epilogProcessor(XML_Parser parser,
           *nextPtr = s;
           return XML_ERROR_NONE;
         case XML_TOK_PROLOG_S:
    -      if (defaultHandler)
    -        reportDefault(parser, encoding, s, next);
    +      if (parser->m_defaultHandler)
    +        reportDefault(parser, parser->m_encoding, s, next);
           break;
         case XML_TOK_PI:
    -      if (!reportProcessingInstruction(parser, encoding, s, next))
    +      if (!reportProcessingInstruction(parser, parser->m_encoding, s, next))
             return XML_ERROR_NO_MEMORY;
           break;
         case XML_TOK_COMMENT:
    -      if (!reportComment(parser, encoding, s, next))
    +      if (!reportComment(parser, parser->m_encoding, s, next))
             return XML_ERROR_NO_MEMORY;
           break;
         case XML_TOK_INVALID:
    -      eventPtr = next;
    +      parser->m_eventPtr = next;
           return XML_ERROR_INVALID_TOKEN;
         case XML_TOK_PARTIAL:
    -      if (!ps_finalBuffer) {
    +      if (!parser->m_parsingStatus.finalBuffer) {
             *nextPtr = s;
             return XML_ERROR_NONE;
           }
           return XML_ERROR_UNCLOSED_TOKEN;
         case XML_TOK_PARTIAL_CHAR:
    -      if (!ps_finalBuffer) {
    +      if (!parser->m_parsingStatus.finalBuffer) {
             *nextPtr = s;
             return XML_ERROR_NONE;
           }
    @@ -4830,8 +5370,8 @@ epilogProcessor(XML_Parser parser,
         default:
           return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
         }
    -    eventPtr = s = next;
    -    switch (ps_parsing) {
    +    parser->m_eventPtr = s = next;
    +    switch (parser->m_parsingStatus.parsing) {
         case XML_SUSPENDED:
           *nextPtr = next;
           return XML_ERROR_NONE;
    @@ -4851,49 +5391,51 @@ processInternalEntity(XML_Parser parser, ENTITY *entity,
       enum XML_Error result;
       OPEN_INTERNAL_ENTITY *openEntity;
     
    -  if (freeInternalEntities) {
    -    openEntity = freeInternalEntities;
    -    freeInternalEntities = openEntity->next;
    +  if (parser->m_freeInternalEntities) {
    +    openEntity = parser->m_freeInternalEntities;
    +    parser->m_freeInternalEntities = openEntity->next;
       }
       else {
    -    openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(sizeof(OPEN_INTERNAL_ENTITY));
    +    openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
         if (!openEntity)
           return XML_ERROR_NO_MEMORY;
       }
       entity->open = XML_TRUE;
       entity->processed = 0;
    -  openEntity->next = openInternalEntities;
    -  openInternalEntities = openEntity;
    +  openEntity->next = parser->m_openInternalEntities;
    +  parser->m_openInternalEntities = openEntity;
       openEntity->entity = entity;
    -  openEntity->startTagLevel = tagLevel;
    +  openEntity->startTagLevel = parser->m_tagLevel;
       openEntity->betweenDecl = betweenDecl;
       openEntity->internalEventPtr = NULL;
       openEntity->internalEventEndPtr = NULL;
       textStart = (char *)entity->textPtr;
       textEnd = (char *)(entity->textPtr + entity->textLen);
    +  /* Set a safe default value in case 'next' does not get set */
    +  next = textStart;
     
     #ifdef XML_DTD
       if (entity->is_param) {
    -    int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next);
    -    result = doProlog(parser, internalEncoding, textStart, textEnd, tok,
    +    int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
    +    result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
                           next, &next, XML_FALSE);
       }
       else
     #endif /* XML_DTD */
    -    result = doContent(parser, tagLevel, internalEncoding, textStart,
    +    result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart,
                            textEnd, &next, XML_FALSE);
     
       if (result == XML_ERROR_NONE) {
    -    if (textEnd != next && ps_parsing == XML_SUSPENDED) {
    +    if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
           entity->processed = (int)(next - textStart);
    -      processor = internalEntityProcessor;
    +      parser->m_processor = internalEntityProcessor;
         }
         else {
           entity->open = XML_FALSE;
    -      openInternalEntities = openEntity->next;
    +      parser->m_openInternalEntities = openEntity->next;
           /* put openEntity back in list of free instances */
    -      openEntity->next = freeInternalEntities;
    -      freeInternalEntities = openEntity;
    +      openEntity->next = parser->m_freeInternalEntities;
    +      parser->m_freeInternalEntities = openEntity;
         }
       }
       return result;
    @@ -4909,54 +5451,56 @@ internalEntityProcessor(XML_Parser parser,
       const char *textStart, *textEnd;
       const char *next;
       enum XML_Error result;
    -  OPEN_INTERNAL_ENTITY *openEntity = openInternalEntities;
    +  OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
       if (!openEntity)
         return XML_ERROR_UNEXPECTED_STATE;
     
       entity = openEntity->entity;
       textStart = ((char *)entity->textPtr) + entity->processed;
       textEnd = (char *)(entity->textPtr + entity->textLen);
    +  /* Set a safe default value in case 'next' does not get set */
    +  next = textStart;
     
     #ifdef XML_DTD
       if (entity->is_param) {
    -    int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next);
    -    result = doProlog(parser, internalEncoding, textStart, textEnd, tok,
    +    int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
    +    result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
                           next, &next, XML_FALSE);
       }
       else
     #endif /* XML_DTD */
    -    result = doContent(parser, openEntity->startTagLevel, internalEncoding,
    +    result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding,
                            textStart, textEnd, &next, XML_FALSE);
     
       if (result != XML_ERROR_NONE)
         return result;
    -  else if (textEnd != next && ps_parsing == XML_SUSPENDED) {
    +  else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
         entity->processed = (int)(next - (char *)entity->textPtr);
         return result;
       }
       else {
         entity->open = XML_FALSE;
    -    openInternalEntities = openEntity->next;
    +    parser->m_openInternalEntities = openEntity->next;
         /* put openEntity back in list of free instances */
    -    openEntity->next = freeInternalEntities;
    -    freeInternalEntities = openEntity;
    +    openEntity->next = parser->m_freeInternalEntities;
    +    parser->m_freeInternalEntities = openEntity;
       }
     
     #ifdef XML_DTD
       if (entity->is_param) {
         int tok;
    -    processor = prologProcessor;
    -    tok = XmlPrologTok(encoding, s, end, &next);
    -    return doProlog(parser, encoding, s, end, tok, next, nextPtr,
    -                    (XML_Bool)!ps_finalBuffer);
    +    parser->m_processor = prologProcessor;
    +    tok = XmlPrologTok(parser->m_encoding, s, end, &next);
    +    return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
    +                    (XML_Bool)!parser->m_parsingStatus.finalBuffer);
       }
       else
     #endif /* XML_DTD */
       {
    -    processor = contentProcessor;
    +    parser->m_processor = contentProcessor;
         /* see externalEntityContentProcessor vs contentProcessor */
    -    return doContent(parser, parentParser ? 1 : 0, encoding, s, end,
    -                     nextPtr, (XML_Bool)!ps_finalBuffer);
    +    return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end,
    +                     nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
       }
     }
     
    @@ -4966,7 +5510,7 @@ errorProcessor(XML_Parser parser,
                    const char *UNUSED_P(end),
                    const char **UNUSED_P(nextPtr))
     {
    -  return errorCode;
    +  return parser->m_errorCode;
     }
     
     static enum XML_Error
    @@ -4990,7 +5534,7 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
                          const char *ptr, const char *end,
                          STRING_POOL *pool)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       for (;;) {
         const char *next;
         int tok = XmlAttributeValueTok(enc, ptr, end, &next);
    @@ -4998,12 +5542,12 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
         case XML_TOK_NONE:
           return XML_ERROR_NONE;
         case XML_TOK_INVALID:
    -      if (enc == encoding)
    -        eventPtr = next;
    +      if (enc == parser->m_encoding)
    +        parser->m_eventPtr = next;
           return XML_ERROR_INVALID_TOKEN;
         case XML_TOK_PARTIAL:
    -      if (enc == encoding)
    -        eventPtr = ptr;
    +      if (enc == parser->m_encoding)
    +        parser->m_eventPtr = ptr;
           return XML_ERROR_INVALID_TOKEN;
         case XML_TOK_CHAR_REF:
           {
    @@ -5011,8 +5555,8 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
             int i;
             int n = XmlCharRefNumber(enc, ptr);
             if (n < 0) {
    -          if (enc == encoding)
    -            eventPtr = ptr;
    +          if (enc == parser->m_encoding)
    +            parser->m_eventPtr = ptr;
               return XML_ERROR_BAD_CHAR_REF;
             }
             if (!isCdata
    @@ -5020,11 +5564,15 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
                 && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
               break;
             n = XmlEncode(n, (ICHAR *)buf);
    -        if (!n) {
    -          if (enc == encoding)
    -            eventPtr = ptr;
    -          return XML_ERROR_BAD_CHAR_REF;
    -        }
    +        /* The XmlEncode() functions can never return 0 here.  That
    +         * error return happens if the code point passed in is either
    +         * negative or greater than or equal to 0x110000.  The
    +         * XmlCharRefNumber() functions will all return a number
    +         * strictly less than 0x110000 or a negative value if an error
    +         * occurred.  The negative value is intercepted above, so
    +         * XmlEncode() is never passed a value it might return an
    +         * error for.
    +         */
             for (i = 0; i < n; i++) {
               if (!poolAppendChar(pool, buf[i]))
                 return XML_ERROR_NO_MEMORY;
    @@ -5058,25 +5606,25 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
                     return XML_ERROR_NO_MEMORY;
               break;
             }
    -        name = poolStoreString(&temp2Pool, enc,
    +        name = poolStoreString(&parser->m_temp2Pool, enc,
                                    ptr + enc->minBytesPerChar,
                                    next - enc->minBytesPerChar);
             if (!name)
               return XML_ERROR_NO_MEMORY;
             entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
    -        poolDiscard(&temp2Pool);
    +        poolDiscard(&parser->m_temp2Pool);
             /* First, determine if a check for an existing declaration is needed;
                if yes, check that the entity exists, and that it is internal.
             */
             if (pool == &dtd->pool)  /* are we called from prolog? */
               checkEntityDecl =
     #ifdef XML_DTD
    -              prologState.documentEntity &&
    +              parser->m_prologState.documentEntity &&
     #endif /* XML_DTD */
                   (dtd->standalone
    -               ? !openInternalEntities
    +               ? !parser->m_openInternalEntities
                    : !dtd->hasParamEntityRefs);
    -        else /* if (pool == &tempPool): we are called from content */
    +        else /* if (pool == &parser->m_tempPool): we are called from content */
               checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone;
             if (checkEntityDecl) {
               if (!entity)
    @@ -5086,37 +5634,55 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
             }
             else if (!entity) {
               /* Cannot report skipped entity here - see comments on
    -             skippedEntityHandler.
    -          if (skippedEntityHandler)
    -            skippedEntityHandler(handlerArg, name, 0);
    +             parser->m_skippedEntityHandler.
    +          if (parser->m_skippedEntityHandler)
    +            parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
               */
               /* Cannot call the default handler because this would be
                  out of sync with the call to the startElementHandler.
    -          if ((pool == &tempPool) && defaultHandler)
    +          if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
                 reportDefault(parser, enc, ptr, next);
               */
               break;
             }
             if (entity->open) {
    -          if (enc == encoding)
    -            eventPtr = ptr;
    +          if (enc == parser->m_encoding) {
    +            /* It does not appear that this line can be executed.
    +             *
    +             * The "if (entity->open)" check catches recursive entity
    +             * definitions.  In order to be called with an open
    +             * entity, it must have gone through this code before and
    +             * been through the recursive call to
    +             * appendAttributeValue() some lines below.  That call
    +             * sets the local encoding ("enc") to the parser's
    +             * internal encoding (internal_utf8 or internal_utf16),
    +             * which can never be the same as the principle encoding.
    +             * It doesn't appear there is another code path that gets
    +             * here with entity->open being TRUE.
    +             *
    +             * Since it is not certain that this logic is watertight,
    +             * we keep the line and merely exclude it from coverage
    +             * tests.
    +             */
    +            parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
    +          }
               return XML_ERROR_RECURSIVE_ENTITY_REF;
             }
             if (entity->notation) {
    -          if (enc == encoding)
    -            eventPtr = ptr;
    +          if (enc == parser->m_encoding)
    +            parser->m_eventPtr = ptr;
               return XML_ERROR_BINARY_ENTITY_REF;
             }
             if (!entity->textPtr) {
    -          if (enc == encoding)
    -            eventPtr = ptr;
    +          if (enc == parser->m_encoding)
    +            parser->m_eventPtr = ptr;
               return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
             }
             else {
               enum XML_Error result;
               const XML_Char *textEnd = entity->textPtr + entity->textLen;
               entity->open = XML_TRUE;
    -          result = appendAttributeValue(parser, internalEncoding, isCdata,
    +          result = appendAttributeValue(parser, parser->m_internalEncoding, isCdata,
                                             (char *)entity->textPtr,
                                             (char *)textEnd, pool);
               entity->open = XML_FALSE;
    @@ -5126,9 +5692,21 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
           }
           break;
         default:
    -      if (enc == encoding)
    -        eventPtr = ptr;
    +      /* The only token returned by XmlAttributeValueTok() that does
    +       * not have an explicit case here is XML_TOK_PARTIAL_CHAR.
    +       * Getting that would require an entity name to contain an
    +       * incomplete XML character (e.g. \xE2\x82); however previous
    +       * tokenisers will have already recognised and rejected such
    +       * names before XmlAttributeValueTok() gets a look-in.  This
    +       * default case should be retained as a safety net, but the code
    +       * excluded from coverage tests.
    +       *
    +       * LCOV_EXCL_START
    +       */
    +      if (enc == parser->m_encoding)
    +        parser->m_eventPtr = ptr;
           return XML_ERROR_UNEXPECTED_STATE;
    +      /* LCOV_EXCL_STOP */
         }
         ptr = next;
       }
    @@ -5141,12 +5719,12 @@ storeEntityValue(XML_Parser parser,
                      const char *entityTextPtr,
                      const char *entityTextEnd)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       STRING_POOL *pool = &(dtd->entityValuePool);
       enum XML_Error result = XML_ERROR_NONE;
     #ifdef XML_DTD
    -  int oldInEntityValue = prologState.inEntityValue;
    -  prologState.inEntityValue = 1;
    +  int oldInEntityValue = parser->m_prologState.inEntityValue;
    +  parser->m_prologState.inEntityValue = 1;
     #endif /* XML_DTD */
       /* never return Null for the value argument in EntityDeclHandler,
          since this would indicate an external entity; therefore we
    @@ -5162,10 +5740,10 @@ storeEntityValue(XML_Parser parser,
         switch (tok) {
         case XML_TOK_PARAM_ENTITY_REF:
     #ifdef XML_DTD
    -      if (isParamEntity || enc != encoding) {
    +      if (parser->m_isParamEntity || enc != parser->m_encoding) {
             const XML_Char *name;
             ENTITY *entity;
    -        name = poolStoreString(&tempPool, enc,
    +        name = poolStoreString(&parser->m_tempPool, enc,
                                    entityTextPtr + enc->minBytesPerChar,
                                    next - enc->minBytesPerChar);
             if (!name) {
    @@ -5173,28 +5751,28 @@ storeEntityValue(XML_Parser parser,
               goto endEntityValue;
             }
             entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
    -        poolDiscard(&tempPool);
    +        poolDiscard(&parser->m_tempPool);
             if (!entity) {
               /* not a well-formedness error - see XML 1.0: WFC Entity Declared */
               /* cannot report skipped entity here - see comments on
    -             skippedEntityHandler
    -          if (skippedEntityHandler)
    -            skippedEntityHandler(handlerArg, name, 0);
    +             parser->m_skippedEntityHandler
    +          if (parser->m_skippedEntityHandler)
    +            parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
               */
               dtd->keepProcessing = dtd->standalone;
               goto endEntityValue;
             }
             if (entity->open) {
    -          if (enc == encoding)
    -            eventPtr = entityTextPtr;
    +          if (enc == parser->m_encoding)
    +            parser->m_eventPtr = entityTextPtr;
               result = XML_ERROR_RECURSIVE_ENTITY_REF;
               goto endEntityValue;
             }
             if (entity->systemId) {
    -          if (externalEntityRefHandler) {
    +          if (parser->m_externalEntityRefHandler) {
                 dtd->paramEntityRead = XML_FALSE;
                 entity->open = XML_TRUE;
    -            if (!externalEntityRefHandler(externalEntityRefHandlerArg,
    +            if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
                                               0,
                                               entity->base,
                                               entity->systemId,
    @@ -5213,7 +5791,7 @@ storeEntityValue(XML_Parser parser,
             else {
               entity->open = XML_TRUE;
               result = storeEntityValue(parser,
    -                                    internalEncoding,
    +                                    parser->m_internalEncoding,
                                         (char *)entity->textPtr,
                                         (char *)(entity->textPtr
                                                  + entity->textLen));
    @@ -5226,7 +5804,7 @@ storeEntityValue(XML_Parser parser,
     #endif /* XML_DTD */
           /* In the internal subset, PE references are not legal
              within markup declarations, e.g entity values in this case. */
    -      eventPtr = entityTextPtr;
    +      parser->m_eventPtr = entityTextPtr;
           result = XML_ERROR_PARAM_ENTITY_REF;
           goto endEntityValue;
         case XML_TOK_NONE:
    @@ -5255,18 +5833,21 @@ storeEntityValue(XML_Parser parser,
             int i;
             int n = XmlCharRefNumber(enc, entityTextPtr);
             if (n < 0) {
    -          if (enc == encoding)
    -            eventPtr = entityTextPtr;
    +          if (enc == parser->m_encoding)
    +            parser->m_eventPtr = entityTextPtr;
               result = XML_ERROR_BAD_CHAR_REF;
               goto endEntityValue;
             }
             n = XmlEncode(n, (ICHAR *)buf);
    -        if (!n) {
    -          if (enc == encoding)
    -            eventPtr = entityTextPtr;
    -          result = XML_ERROR_BAD_CHAR_REF;
    -          goto endEntityValue;
    -        }
    +        /* The XmlEncode() functions can never return 0 here.  That
    +         * error return happens if the code point passed in is either
    +         * negative or greater than or equal to 0x110000.  The
    +         * XmlCharRefNumber() functions will all return a number
    +         * strictly less than 0x110000 or a negative value if an error
    +         * occurred.  The negative value is intercepted above, so
    +         * XmlEncode() is never passed a value it might return an
    +         * error for.
    +         */
             for (i = 0; i < n; i++) {
               if (pool->end == pool->ptr && !poolGrow(pool)) {
                 result = XML_ERROR_NO_MEMORY;
    @@ -5277,26 +5858,34 @@ storeEntityValue(XML_Parser parser,
           }
           break;
         case XML_TOK_PARTIAL:
    -      if (enc == encoding)
    -        eventPtr = entityTextPtr;
    +      if (enc == parser->m_encoding)
    +        parser->m_eventPtr = entityTextPtr;
           result = XML_ERROR_INVALID_TOKEN;
           goto endEntityValue;
         case XML_TOK_INVALID:
    -      if (enc == encoding)
    -        eventPtr = next;
    +      if (enc == parser->m_encoding)
    +        parser->m_eventPtr = next;
           result = XML_ERROR_INVALID_TOKEN;
           goto endEntityValue;
         default:
    -      if (enc == encoding)
    -        eventPtr = entityTextPtr;
    +      /* This default case should be unnecessary -- all the tokens
    +       * that XmlEntityValueTok() can return have their own explicit
    +       * cases -- but should be retained for safety.  We do however
    +       * exclude it from the coverage statistics.
    +       *
    +       * LCOV_EXCL_START
    +       */
    +      if (enc == parser->m_encoding)
    +        parser->m_eventPtr = entityTextPtr;
           result = XML_ERROR_UNEXPECTED_STATE;
           goto endEntityValue;
    +      /* LCOV_EXCL_STOP */
         }
         entityTextPtr = next;
       }
     endEntityValue:
     #ifdef XML_DTD
    -  prologState.inEntityValue = oldInEntityValue;
    +  parser->m_prologState.inEntityValue = oldInEntityValue;
     #endif /* XML_DTD */
       return result;
     }
    @@ -5331,25 +5920,25 @@ reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
       const XML_Char *target;
       XML_Char *data;
       const char *tem;
    -  if (!processingInstructionHandler) {
    -    if (defaultHandler)
    +  if (!parser->m_processingInstructionHandler) {
    +    if (parser->m_defaultHandler)
           reportDefault(parser, enc, start, end);
         return 1;
       }
       start += enc->minBytesPerChar * 2;
       tem = start + XmlNameLength(enc, start);
    -  target = poolStoreString(&tempPool, enc, start, tem);
    +  target = poolStoreString(&parser->m_tempPool, enc, start, tem);
       if (!target)
         return 0;
    -  poolFinish(&tempPool);
    -  data = poolStoreString(&tempPool, enc,
    +  poolFinish(&parser->m_tempPool);
    +  data = poolStoreString(&parser->m_tempPool, enc,
                             XmlSkipS(enc, tem),
                             end - enc->minBytesPerChar*2);
       if (!data)
         return 0;
       normalizeLines(data);
    -  processingInstructionHandler(handlerArg, target, data);
    -  poolClear(&tempPool);
    +  parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
    +  poolClear(&parser->m_tempPool);
       return 1;
     }
     
    @@ -5358,20 +5947,20 @@ reportComment(XML_Parser parser, const ENCODING *enc,
                   const char *start, const char *end)
     {
       XML_Char *data;
    -  if (!commentHandler) {
    -    if (defaultHandler)
    +  if (!parser->m_commentHandler) {
    +    if (parser->m_defaultHandler)
           reportDefault(parser, enc, start, end);
         return 1;
       }
    -  data = poolStoreString(&tempPool,
    +  data = poolStoreString(&parser->m_tempPool,
                              enc,
                              start + enc->minBytesPerChar * 4,
                              end - enc->minBytesPerChar * 3);
       if (!data)
         return 0;
       normalizeLines(data);
    -  commentHandler(handlerArg, data);
    -  poolClear(&tempPool);
    +  parser->m_commentHandler(parser->m_handlerArg, data);
    +  poolClear(&parser->m_tempPool);
       return 1;
     }
     
    @@ -5383,24 +5972,41 @@ reportDefault(XML_Parser parser, const ENCODING *enc,
         enum XML_Convert_Result convert_res;
         const char **eventPP;
         const char **eventEndPP;
    -    if (enc == encoding) {
    -      eventPP = &eventPtr;
    -      eventEndPP = &eventEndPtr;
    +    if (enc == parser->m_encoding) {
    +      eventPP = &parser->m_eventPtr;
    +      eventEndPP = &parser->m_eventEndPtr;
         }
         else {
    -      eventPP = &(openInternalEntities->internalEventPtr);
    -      eventEndPP = &(openInternalEntities->internalEventEndPtr);
    +      /* To get here, two things must be true; the parser must be
    +       * using a character encoding that is not the same as the
    +       * encoding passed in, and the encoding passed in must need
    +       * conversion to the internal format (UTF-8 unless XML_UNICODE
    +       * is defined).  The only occasions on which the encoding passed
    +       * in is not the same as the parser's encoding are when it is
    +       * the internal encoding (e.g. a previously defined parameter
    +       * entity, already converted to internal format).  This by
    +       * definition doesn't need conversion, so the whole branch never
    +       * gets executed.
    +       *
    +       * For safety's sake we don't delete these lines and merely
    +       * exclude them from coverage statistics.
    +       *
    +       * LCOV_EXCL_START
    +       */
    +      eventPP = &(parser->m_openInternalEntities->internalEventPtr);
    +      eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
    +      /* LCOV_EXCL_STOP */
         }
         do {
    -      ICHAR *dataPtr = (ICHAR *)dataBuf;
    -      convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
    +      ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
    +      convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
           *eventEndPP = s;
    -      defaultHandler(handlerArg, dataBuf, (int)(dataPtr - (ICHAR *)dataBuf));
    +      parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf, (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
           *eventPP = s;
         } while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
       }
       else
    -    defaultHandler(handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
    +    parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
     }
     
     
    @@ -5422,16 +6028,18 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
       if (type->nDefaultAtts == type->allocDefaultAtts) {
         if (type->allocDefaultAtts == 0) {
           type->allocDefaultAtts = 8;
    -      type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(type->allocDefaultAtts
    +      type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(parser, type->allocDefaultAtts
                                 * sizeof(DEFAULT_ATTRIBUTE));
    -      if (!type->defaultAtts)
    +      if (!type->defaultAtts) {
    +        type->allocDefaultAtts = 0;
             return 0;
    +      }
         }
         else {
           DEFAULT_ATTRIBUTE *temp;
           int count = type->allocDefaultAtts * 2;
           temp = (DEFAULT_ATTRIBUTE *)
    -        REALLOC(type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
    +        REALLOC(parser, type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
           if (temp == NULL)
             return 0;
           type->allocDefaultAtts = count;
    @@ -5451,7 +6059,7 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
     static int
     setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       const XML_Char *name;
       for (name = elementType->name; *name; name++) {
         if (*name == XML_T(ASCII_COLON)) {
    @@ -5482,7 +6090,7 @@ static ATTRIBUTE_ID *
     getAttributeId(XML_Parser parser, const ENCODING *enc,
                    const char *start, const char *end)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       ATTRIBUTE_ID *id;
       const XML_Char *name;
       if (!poolAppendChar(&dtd->pool, XML_T('\0')))
    @@ -5499,7 +6107,7 @@ getAttributeId(XML_Parser parser, const ENCODING *enc,
         poolDiscard(&dtd->pool);
       else {
         poolFinish(&dtd->pool);
    -    if (!ns)
    +    if (!parser->m_ns)
           ;
         else if (name[0] == XML_T(ASCII_x)
             && name[1] == XML_T(ASCII_m)
    @@ -5546,21 +6154,42 @@ getAttributeId(XML_Parser parser, const ENCODING *enc,
     static const XML_Char *
     getContext(XML_Parser parser)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       HASH_TABLE_ITER iter;
       XML_Bool needSep = XML_FALSE;
     
       if (dtd->defaultPrefix.binding) {
         int i;
         int len;
    -    if (!poolAppendChar(&tempPool, XML_T(ASCII_EQUALS)))
    +    if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
           return NULL;
         len = dtd->defaultPrefix.binding->uriLen;
    -    if (namespaceSeparator)
    +    if (parser->m_namespaceSeparator)
           len--;
    -    for (i = 0; i < len; i++)
    -      if (!poolAppendChar(&tempPool, dtd->defaultPrefix.binding->uri[i]))
    -        return NULL;
    +    for (i = 0; i < len; i++) {
    +      if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) {
    +        /* Because of memory caching, I don't believe this line can be
    +         * executed.
    +         *
    +         * This is part of a loop copying the default prefix binding
    +         * URI into the parser's temporary string pool.  Previously,
    +         * that URI was copied into the same string pool, with a
    +         * terminating NUL character, as part of setContext().  When
    +         * the pool was cleared, that leaves a block definitely big
    +         * enough to hold the URI on the free block list of the pool.
    +         * The URI copy in getContext() therefore cannot run out of
    +         * memory.
    +         *
    +         * If the pool is used between the setContext() and
    +         * getContext() calls, the worst it can do is leave a bigger
    +         * block on the front of the free list.  Given that this is
    +         * all somewhat inobvious and program logic can be changed, we
    +         * don't delete the line but we do exclude it from the test
    +         * coverage statistics.
    +         */
    +        return NULL; /* LCOV_EXCL_LINE */
    +      }
    +    }
         needSep = XML_TRUE;
       }
     
    @@ -5572,20 +6201,27 @@ getContext(XML_Parser parser)
         PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
         if (!prefix)
           break;
    -    if (!prefix->binding)
    -      continue;
    -    if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP))
    +    if (!prefix->binding) {
    +      /* This test appears to be (justifiable) paranoia.  There does
    +       * not seem to be a way of injecting a prefix without a binding
    +       * that doesn't get errored long before this function is called.
    +       * The test should remain for safety's sake, so we instead
    +       * exclude the following line from the coverage statistics.
    +       */
    +      continue; /* LCOV_EXCL_LINE */
    +    }
    +    if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
           return NULL;
         for (s = prefix->name; *s; s++)
    -      if (!poolAppendChar(&tempPool, *s))
    +      if (!poolAppendChar(&parser->m_tempPool, *s))
             return NULL;
    -    if (!poolAppendChar(&tempPool, XML_T(ASCII_EQUALS)))
    +    if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
           return NULL;
         len = prefix->binding->uriLen;
    -    if (namespaceSeparator)
    +    if (parser->m_namespaceSeparator)
           len--;
         for (i = 0; i < len; i++)
    -      if (!poolAppendChar(&tempPool, prefix->binding->uri[i]))
    +      if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
             return NULL;
         needSep = XML_TRUE;
       }
    @@ -5599,73 +6235,73 @@ getContext(XML_Parser parser)
           break;
         if (!e->open)
           continue;
    -    if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP))
    +    if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
           return NULL;
         for (s = e->name; *s; s++)
    -      if (!poolAppendChar(&tempPool, *s))
    +      if (!poolAppendChar(&parser->m_tempPool, *s))
             return 0;
         needSep = XML_TRUE;
       }
     
    -  if (!poolAppendChar(&tempPool, XML_T('\0')))
    +  if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
         return NULL;
    -  return tempPool.start;
    +  return parser->m_tempPool.start;
     }
     
     static XML_Bool
     setContext(XML_Parser parser, const XML_Char *context)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       const XML_Char *s = context;
     
       while (*context != XML_T('\0')) {
         if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
           ENTITY *e;
    -      if (!poolAppendChar(&tempPool, XML_T('\0')))
    +      if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
             return XML_FALSE;
    -      e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&tempPool), 0);
    +      e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&parser->m_tempPool), 0);
           if (e)
             e->open = XML_TRUE;
           if (*s != XML_T('\0'))
             s++;
           context = s;
    -      poolDiscard(&tempPool);
    +      poolDiscard(&parser->m_tempPool);
         }
         else if (*s == XML_T(ASCII_EQUALS)) {
           PREFIX *prefix;
    -      if (poolLength(&tempPool) == 0)
    +      if (poolLength(&parser->m_tempPool) == 0)
             prefix = &dtd->defaultPrefix;
           else {
    -        if (!poolAppendChar(&tempPool, XML_T('\0')))
    +        if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
               return XML_FALSE;
    -        prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&tempPool),
    +        prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&parser->m_tempPool),
                                       sizeof(PREFIX));
             if (!prefix)
               return XML_FALSE;
    -        if (prefix->name == poolStart(&tempPool)) {
    +        if (prefix->name == poolStart(&parser->m_tempPool)) {
               prefix->name = poolCopyString(&dtd->pool, prefix->name);
               if (!prefix->name)
                 return XML_FALSE;
             }
    -        poolDiscard(&tempPool);
    +        poolDiscard(&parser->m_tempPool);
           }
           for (context = s + 1;
                *context != CONTEXT_SEP && *context != XML_T('\0');
                context++)
    -        if (!poolAppendChar(&tempPool, *context))
    +        if (!poolAppendChar(&parser->m_tempPool, *context))
               return XML_FALSE;
    -      if (!poolAppendChar(&tempPool, XML_T('\0')))
    +      if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
             return XML_FALSE;
    -      if (addBinding(parser, prefix, NULL, poolStart(&tempPool),
    -                     &inheritedBindings) != XML_ERROR_NONE)
    +      if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
    +                     &parser->m_inheritedBindings) != XML_ERROR_NONE)
             return XML_FALSE;
    -      poolDiscard(&tempPool);
    +      poolDiscard(&parser->m_tempPool);
           if (*context != XML_T('\0'))
             ++context;
           s = context;
         }
         else {
    -      if (!poolAppendChar(&tempPool, *s))
    +      if (!poolAppendChar(&parser->m_tempPool, *s))
             return XML_FALSE;
           s++;
         }
    @@ -5876,7 +6512,6 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd, const XML_Memory_H
           newE->defaultAtts = (DEFAULT_ATTRIBUTE *)
               ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
           if (!newE->defaultAtts) {
    -        ms->free_fcn(newE);
             return 0;
           }
         }
    @@ -6011,13 +6646,31 @@ keyeq(KEY s1, KEY s2)
       return XML_FALSE;
     }
     
    +static size_t
    +keylen(KEY s)
    +{
    +  size_t len = 0;
    +  for (; *s; s++, len++);
    +  return len;
    +}
    +
    +static void
    +copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key)
    +{
    +  key->k[0] = 0;
    +  key->k[1] = get_hash_secret_salt(parser);
    +}
    +
     static unsigned long FASTCALL
     hash(XML_Parser parser, KEY s)
     {
    -  unsigned long h = hash_secret_salt;
    -  while (*s)
    -    h = CHAR_HASH(h, *s++);
    -  return h;
    +  struct siphash state;
    +  struct sipkey key;
    +  (void)sip24_valid;
    +  copy_salt_to_sipkey(parser, &key);
    +  sip24_init(&state, &key);
    +  sip24_update(&state, s, keylen(s) * sizeof(XML_Char));
    +  return (unsigned long)sip24_final(&state);
     }
     
     static NAMED *
    @@ -6226,8 +6879,20 @@ poolCopyString(STRING_POOL *pool, const XML_Char *s)
     static const XML_Char *
     poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n)
     {
    -  if (!pool->ptr && !poolGrow(pool))
    -    return NULL;
    +  if (!pool->ptr && !poolGrow(pool)) {
    +    /* The following line is unreachable given the current usage of
    +     * poolCopyStringN().  Currently it is called from exactly one
    +     * place to copy the text of a simple general entity.  By that
    +     * point, the name of the entity is already stored in the pool, so
    +     * pool->ptr cannot be NULL.
    +     *
    +     * If poolCopyStringN() is used elsewhere as it well might be,
    +     * this line may well become executable again.  Regardless, this
    +     * sort of check shouldn't be removed lightly, so we just exclude
    +     * it from the coverage statistics.
    +     */
    +    return NULL; /* LCOV_EXCL_LINE */
    +  }
       for (; n > 0; --n, s++) {
         if (!poolAppendChar(pool, *s))
           return NULL;
    @@ -6260,6 +6925,35 @@ poolStoreString(STRING_POOL *pool, const ENCODING *enc,
       return pool->start;
     }
     
    +static size_t
    +poolBytesToAllocateFor(int blockSize)
    +{
    +  /* Unprotected math would be:
    +  ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
    +  **
    +  ** Detect overflow, avoiding _signed_ overflow undefined behavior
    +  ** For a + b * c we check b * c in isolation first, so that addition of a
    +  ** on top has no chance of making us accept a small non-negative number
    +  */
    +  const size_t stretch = sizeof(XML_Char);  /* can be 4 bytes */
    +
    +  if (blockSize <= 0)
    +    return 0;
    +
    +  if (blockSize > (int)(INT_MAX / stretch))
    +    return 0;
    +
    +  {
    +    const int stretchedBlockSize = blockSize * (int)stretch;
    +    const int bytesToAllocate = (int)(
    +        offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
    +    if (bytesToAllocate < 0)
    +      return 0;
    +
    +    return (size_t)bytesToAllocate;
    +  }
    +}
    +
     static XML_Bool FASTCALL
     poolGrow(STRING_POOL *pool)
     {
    @@ -6289,35 +6983,69 @@ poolGrow(STRING_POOL *pool)
       if (pool->blocks && pool->start == pool->blocks->s) {
         BLOCK *temp;
         int blockSize = (int)((unsigned)(pool->end - pool->start)*2U);
    +    size_t bytesToAllocate;
     
    -    if (blockSize < 0)
    +    /* NOTE: Needs to be calculated prior to calling `realloc`
    +             to avoid dangling pointers: */
    +    const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
    +
    +    if (blockSize < 0) {
    +      /* This condition traps a situation where either more than
    +       * INT_MAX/2 bytes have already been allocated.  This isn't
    +       * readily testable, since it is unlikely that an average
    +       * machine will have that much memory, so we exclude it from the
    +       * coverage statistics.
    +       */
    +      return XML_FALSE; /* LCOV_EXCL_LINE */
    +    }
    +
    +    bytesToAllocate = poolBytesToAllocateFor(blockSize);
    +    if (bytesToAllocate == 0)
           return XML_FALSE;
     
         temp = (BLOCK *)
    -      pool->mem->realloc_fcn(pool->blocks,
    -                             (offsetof(BLOCK, s)
    -                              + blockSize * sizeof(XML_Char)));
    +      pool->mem->realloc_fcn(pool->blocks, (unsigned)bytesToAllocate);
         if (temp == NULL)
           return XML_FALSE;
         pool->blocks = temp;
         pool->blocks->size = blockSize;
    -    pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
    +    pool->ptr = pool->blocks->s + offsetInsideBlock;
         pool->start = pool->blocks->s;
         pool->end = pool->start + blockSize;
       }
       else {
         BLOCK *tem;
         int blockSize = (int)(pool->end - pool->start);
    +    size_t bytesToAllocate;
     
    -    if (blockSize < 0)
    -      return XML_FALSE;
    +    if (blockSize < 0) {
    +      /* This condition traps a situation where either more than
    +       * INT_MAX bytes have already been allocated (which is prevented
    +       * by various pieces of program logic, not least this one, never
    +       * mind the unlikelihood of actually having that much memory) or
    +       * the pool control fields have been corrupted (which could
    +       * conceivably happen in an extremely buggy user handler
    +       * function).  Either way it isn't readily testable, so we
    +       * exclude it from the coverage statistics.
    +       */
    +      return XML_FALSE;  /* LCOV_EXCL_LINE */
    +    }
     
         if (blockSize < INIT_BLOCK_SIZE)
           blockSize = INIT_BLOCK_SIZE;
    -    else
    +    else {
    +      /* Detect overflow, avoiding _signed_ overflow undefined behavior */
    +      if ((int)((unsigned)blockSize * 2U) < 0) {
    +        return XML_FALSE;
    +      }
           blockSize *= 2;
    -    tem = (BLOCK *)pool->mem->malloc_fcn(offsetof(BLOCK, s)
    -                                        + blockSize * sizeof(XML_Char));
    +    }
    +
    +    bytesToAllocate = poolBytesToAllocateFor(blockSize);
    +    if (bytesToAllocate == 0)
    +      return XML_FALSE;
    +
    +    tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate);
         if (!tem)
           return XML_FALSE;
         tem->size = blockSize;
    @@ -6336,12 +7064,12 @@ poolGrow(STRING_POOL *pool)
     static int FASTCALL
     nextScaffoldPart(XML_Parser parser)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       CONTENT_SCAFFOLD * me;
       int next;
     
       if (!dtd->scaffIndex) {
    -    dtd->scaffIndex = (int *)MALLOC(groupSize * sizeof(int));
    +    dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
         if (!dtd->scaffIndex)
           return -1;
         dtd->scaffIndex[0] = 0;
    @@ -6351,13 +7079,13 @@ nextScaffoldPart(XML_Parser parser)
         CONTENT_SCAFFOLD *temp;
         if (dtd->scaffold) {
           temp = (CONTENT_SCAFFOLD *)
    -        REALLOC(dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
    +        REALLOC(parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
           if (temp == NULL)
             return -1;
           dtd->scaffSize *= 2;
         }
         else {
    -      temp = (CONTENT_SCAFFOLD *)MALLOC(INIT_SCAFFOLD_ELEMENTS
    +      temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
                                             * sizeof(CONTENT_SCAFFOLD));
           if (temp == NULL)
             return -1;
    @@ -6388,7 +7116,7 @@ build_node(XML_Parser parser,
                XML_Content **contpos,
                XML_Char **strpos)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       dest->type = dtd->scaffold[src_node].type;
       dest->quant = dtd->scaffold[src_node].quant;
       if (dest->type == XML_CTYPE_NAME) {
    @@ -6422,14 +7150,14 @@ build_node(XML_Parser parser,
     static XML_Content *
     build_model (XML_Parser parser)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       XML_Content *ret;
       XML_Content *cpos;
       XML_Char * str;
       int allocsize = (dtd->scaffCount * sizeof(XML_Content)
                        + (dtd->contentStringLen * sizeof(XML_Char)));
     
    -  ret = (XML_Content *)MALLOC(allocsize);
    +  ret = (XML_Content *)MALLOC(parser, allocsize);
       if (!ret)
         return NULL;
     
    @@ -6446,7 +7174,7 @@ getElementType(XML_Parser parser,
                    const char *ptr,
                    const char *end)
     {
    -  DTD * const dtd = _dtd;  /* save one level of indirection */
    +  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
       const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
       ELEMENT_TYPE *ret;
     
    @@ -6464,3 +7192,26 @@ getElementType(XML_Parser parser,
       }
       return ret;
     }
    +
    +static XML_Char *
    +copyString(const XML_Char *s,
    +           const XML_Memory_Handling_Suite *memsuite)
    +{
    +    int charsRequired = 0;
    +    XML_Char *result;
    +
    +    /* First determine how long the string is */
    +    while (s[charsRequired] != 0) {
    +      charsRequired++;
    +    }
    +    /* Include the terminator */
    +    charsRequired++;
    +
    +    /* Now allocate space for the copy */
    +    result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
    +    if (result == NULL)
    +        return NULL;
    +    /* Copy the original into place */
    +    memcpy(result, s, charsRequired * sizeof(XML_Char));
    +    return result;
    +}
    diff --git a/contrib/expat/lib/xmlrole.c b/contrib/expat/lib/xmlrole.c
    index fcd0dc6948f4..708507d575be 100644
    --- a/contrib/expat/lib/xmlrole.c
    +++ b/contrib/expat/lib/xmlrole.c
    @@ -1,22 +1,44 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #include 
     
    -#ifdef WIN32
    +#ifdef _WIN32
     #include "winconfig.h"
    -#elif defined(MACOS_CLASSIC)
    -#include "macconfig.h"
    -#elif defined(__amigaos__)
    -#include "amigaconfig.h"
    -#elif defined(__WATCOMC__)
    -#include "watcomconfig.h"
     #else
     #ifdef HAVE_EXPAT_CONFIG_H
     #include 
     #endif
    -#endif /* ndef WIN32 */
    +#endif /* ndef _WIN32 */
     
     #include "expat_external.h"
     #include "internal.h"
    @@ -176,7 +198,14 @@ prolog1(PROLOG_STATE *state,
       case XML_TOK_COMMENT:
         return XML_ROLE_COMMENT;
       case XML_TOK_BOM:
    -    return XML_ROLE_NONE;
    +    /* This case can never arise.  To reach this role function, the
    +     * parse must have passed through prolog0 and therefore have had
    +     * some form of input, even if only a space.  At that point, a
    +     * byte order mark is no longer a valid character (though
    +     * technically it should be interpreted as a non-breaking space),
    +     * so will be rejected by the tokenizing stages.
    +     */
    +    return XML_ROLE_NONE; /* LCOV_EXCL_LINE */
       case XML_TOK_DECL_OPEN:
         if (!XmlNameMatchesAscii(enc,
                                  ptr + 2 * MIN_BYTES_PER_CHAR(enc),
    @@ -1291,6 +1320,26 @@ declClose(PROLOG_STATE *state,
       return common(state, tok);
     }
     
    +/* This function will only be invoked if the internal logic of the
    + * parser has broken down.  It is used in two cases:
    + *
    + * 1: When the XML prolog has been finished.  At this point the
    + * processor (the parser level above these role handlers) should
    + * switch from prologProcessor to contentProcessor and reinitialise
    + * the handler function.
    + *
    + * 2: When an error has been detected (via common() below).  At this
    + * point again the processor should be switched to errorProcessor,
    + * which will never call a handler.
    + *
    + * The result of this is that error() can only be called if the
    + * processor switch failed to happen, which is an internal error and
    + * therefore we shouldn't be able to provoke it simply by using the
    + * library.  It is a necessary backstop, however, so we merely exclude
    + * it from the coverage statistics.
    + *
    + * LCOV_EXCL_START
    + */
     static int PTRCALL
     error(PROLOG_STATE *UNUSED_P(state),
           int UNUSED_P(tok),
    @@ -1300,6 +1349,7 @@ error(PROLOG_STATE *UNUSED_P(state),
     {
       return XML_ROLE_NONE;
     }
    +/* LCOV_EXCL_STOP */
     
     static int FASTCALL
     common(PROLOG_STATE *state, int tok)
    diff --git a/contrib/expat/lib/xmlrole.h b/contrib/expat/lib/xmlrole.h
    index 4dd9f06f9767..e5f048eab55c 100644
    --- a/contrib/expat/lib/xmlrole.h
    +++ b/contrib/expat/lib/xmlrole.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #ifndef XmlRole_INCLUDED
    diff --git a/contrib/expat/lib/xmltok.c b/contrib/expat/lib/xmltok.c
    index a29d9e2f8ac3..6b415d83972c 100644
    --- a/contrib/expat/lib/xmltok.c
    +++ b/contrib/expat/lib/xmltok.c
    @@ -1,22 +1,55 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #include 
    +#include   /* memcpy */
     
    -#ifdef WIN32
    +#if defined(_MSC_VER) && (_MSC_VER <= 1700)
    +  /* for vs2012/11.0/1700 and earlier Visual Studio compilers */
    +# define bool   int
    +# define false  0
    +# define true   1
    +#else
    +# include 
    +#endif
    +
    +
    +#ifdef _WIN32
     #include "winconfig.h"
    -#elif defined(MACOS_CLASSIC)
    -#include "macconfig.h"
    -#elif defined(__amigaos__)
    -#include "amigaconfig.h"
    -#elif defined(__WATCOMC__)
    -#include "watcomconfig.h"
     #else
     #ifdef HAVE_EXPAT_CONFIG_H
     #include 
     #endif
    -#endif /* ndef WIN32 */
    +#endif /* ndef _WIN32 */
     
     #include "expat_external.h"
     #include "internal.h"
    @@ -33,7 +66,6 @@
       { PREFIX(prologTok), PREFIX(contentTok), \
         PREFIX(cdataSectionTok) IGNORE_SECTION_TOK_VTABLE }, \
       { PREFIX(attributeValueTok), PREFIX(entityValueTok) }, \
    -  PREFIX(sameName), \
       PREFIX(nameMatchesAscii), \
       PREFIX(nameLength), \
       PREFIX(skipS), \
    @@ -330,7 +362,7 @@ enum {  /* UTF8_cvalN is value of masked first byte of N byte sequence */
     };
     
     void
    -align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef)
    +_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef)
     {
       const char * fromLim = *fromLimRef;
       size_t walked = 0;
    @@ -369,24 +401,39 @@ utf8_toUtf8(const ENCODING *UNUSED_P(enc),
                 const char **fromP, const char *fromLim,
                 char **toP, const char *toLim)
     {
    -  enum XML_Convert_Result res = XML_CONVERT_COMPLETED;
    -  char *to;
    -  const char *from;
    -  if (fromLim - *fromP > toLim - *toP) {
    -    /* Avoid copying partial characters. */
    -    res = XML_CONVERT_OUTPUT_EXHAUSTED;
    -    fromLim = *fromP + (toLim - *toP);
    -    align_limit_to_full_utf8_characters(*fromP, &fromLim);
    -  }
    -  for (to = *toP, from = *fromP; (from < fromLim) && (to < toLim); from++, to++)
    -    *to = *from;
    -  *fromP = from;
    -  *toP = to;
    +  bool input_incomplete = false;
    +  bool output_exhausted = false;
     
    -  if ((to == toLim) && (from < fromLim))
    +  /* Avoid copying partial characters (due to limited space). */
    +  const ptrdiff_t bytesAvailable = fromLim - *fromP;
    +  const ptrdiff_t bytesStorable = toLim - *toP;
    +  if (bytesAvailable > bytesStorable) {
    +    fromLim = *fromP + bytesStorable;
    +    output_exhausted = true;
    +  }
    +
    +  /* Avoid copying partial characters (from incomplete input). */
    +  {
    +    const char * const fromLimBefore = fromLim;
    +    _INTERNAL_trim_to_complete_utf8_characters(*fromP, &fromLim);
    +    if (fromLim < fromLimBefore) {
    +      input_incomplete = true;
    +    }
    +  }
    +
    +  {
    +    const ptrdiff_t bytesToCopy = fromLim - *fromP;
    +    memcpy(*toP, *fromP, bytesToCopy);
    +    *fromP += bytesToCopy;
    +    *toP += bytesToCopy;
    +  }
    +
    +  if (output_exhausted)  /* needs to go first */
         return XML_CONVERT_OUTPUT_EXHAUSTED;
    +  else if (input_incomplete)
    +    return XML_CONVERT_INPUT_INCOMPLETE;
       else
    -    return res;
    +    return XML_CONVERT_COMPLETED;
     }
     
     static enum XML_Convert_Result PTRCALL
    @@ -402,7 +449,7 @@ utf8_toUtf16(const ENCODING *enc,
         case BT_LEAD2:
           if (fromLim - from < 2) {
             res = XML_CONVERT_INPUT_INCOMPLETE;
    -        break;
    +        goto after;
           }
           *to++ = (unsigned short)(((from[0] & 0x1f) << 6) | (from[1] & 0x3f));
           from += 2;
    @@ -410,7 +457,7 @@ utf8_toUtf16(const ENCODING *enc,
         case BT_LEAD3:
           if (fromLim - from < 3) {
             res = XML_CONVERT_INPUT_INCOMPLETE;
    -        break;
    +        goto after;
           }
           *to++ = (unsigned short)(((from[0] & 0xf) << 12)
                                    | ((from[1] & 0x3f) << 6) | (from[2] & 0x3f));
    @@ -441,6 +488,8 @@ utf8_toUtf16(const ENCODING *enc,
           break;
         }
       }
    +  if (from < fromLim)
    +    res = XML_CONVERT_OUTPUT_EXHAUSTED;
     after:
       *fromP = from;
       *toP = to;
    @@ -1023,7 +1072,11 @@ streqci(const char *s1, const char *s2)
         if (ASCII_a <= c1 && c1 <= ASCII_z)
           c1 += ASCII_A - ASCII_a;
         if (ASCII_a <= c2 && c2 <= ASCII_z)
    -      c2 += ASCII_A - ASCII_a;
    +      /* The following line will never get executed.  streqci() is
    +       * only called from two places, both of which guarantee to put
    +       * upper-case strings into s2.
    +       */
    +      c2 += ASCII_A - ASCII_a; /* LCOV_EXCL_LINE */
         if (c1 != c2)
           return 0;
         if (!c1)
    @@ -1295,7 +1348,7 @@ XmlUtf8Encode(int c, char *buf)
       };
     
       if (c < 0)
    -    return 0;
    +    return 0; /* LCOV_EXCL_LINE: this case is always eliminated beforehand */
       if (c < min2) {
         buf[0] = (char)(c | UTF8_cval1);
         return 1;
    @@ -1318,7 +1371,7 @@ XmlUtf8Encode(int c, char *buf)
         buf[3] = (char)((c & 0x3f) | 0x80);
         return 4;
       }
    -  return 0;
    +  return 0; /* LCOV_EXCL_LINE: this case too is eliminated before calling */
     }
     
     int FASTCALL
    @@ -1411,9 +1464,8 @@ unknown_toUtf8(const ENCODING *enc,
             return XML_CONVERT_OUTPUT_EXHAUSTED;
           (*fromP)++;
         }
    -    do {
    -      *(*toP)++ = *utf8++;
    -    } while (--n != 0);
    +    memcpy(*toP, utf8, n);
    +    *toP += n;
       }
     }
     
    @@ -1469,6 +1521,9 @@ XmlInitUnknownEncoding(void *mem,
         else if (c < 0) {
           if (c < -4)
             return 0;
    +      /* Multi-byte sequences need a converter function */
    +      if (!convert)
    +        return 0;
           e->normal.type[i] = (unsigned char)(BT_LEAD2 - (c + 2));
           e->utf8[i][0] = 0;
           e->utf16[i] = 0;
    diff --git a/contrib/expat/lib/xmltok.h b/contrib/expat/lib/xmltok.h
    index 752007e8b9e2..50926f38ab32 100644
    --- a/contrib/expat/lib/xmltok.h
    +++ b/contrib/expat/lib/xmltok.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #ifndef XmlTok_INCLUDED
    @@ -139,9 +167,6 @@ enum XML_Convert_Result {
     struct encoding {
       SCANNER scanners[XML_N_STATES];
       SCANNER literalScanners[XML_N_LITERAL_TYPES];
    -  int (PTRCALL *sameName)(const ENCODING *,
    -                          const char *,
    -                          const char *);
       int (PTRCALL *nameMatchesAscii)(const ENCODING *,
                                       const char *,
                                       const char *,
    @@ -232,8 +257,6 @@ struct encoding {
     #define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \
        XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr)
     
    -#define XmlSameName(enc, ptr1, ptr2) (((enc)->sameName)(enc, ptr1, ptr2))
    -
     #define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \
       (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2))
     
    diff --git a/contrib/expat/lib/xmltok_impl.c b/contrib/expat/lib/xmltok_impl.c
    index 5f779c0571b5..4d9ae7dc3896 100644
    --- a/contrib/expat/lib/xmltok_impl.c
    +++ b/contrib/expat/lib/xmltok_impl.c
    @@ -1,8 +1,35 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/* This file is included!
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
    -/* This file is included! */
     #ifdef XML_TOK_IMPL_C
     
     #ifndef IS_INVALID_CHAR
    @@ -47,6 +74,7 @@
           *nextTokPtr = ptr; \
           return XML_TOK_INVALID; \
         } \
    +    /* fall through */ \
       case BT_NMSTRT: \
       case BT_HEX: \
       case BT_DIGIT: \
    @@ -75,6 +103,7 @@
           *nextTokPtr = ptr; \
           return XML_TOK_INVALID; \
         } \
    +    /* fall through */ \
       case BT_NMSTRT: \
       case BT_HEX: \
         ptr += MINBPC(enc); \
    @@ -575,7 +604,7 @@ PREFIX(scanAtts)(const ENCODING *enc, const char *ptr, const char *end,
               return XML_TOK_INVALID;
             }
           }
    -    /* fall through */
    +      /* fall through */
         case BT_EQUALS:
           {
             int open;
    @@ -1198,8 +1227,14 @@ PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr,
       const char *start;
       if (ptr >= end)
         return XML_TOK_NONE;
    -  else if (! HAS_CHAR(enc, ptr, end))
    -    return XML_TOK_PARTIAL;
    +  else if (! HAS_CHAR(enc, ptr, end)) {
    +    /* This line cannot be executed.  The incoming data has already
    +     * been tokenized once, so incomplete characters like this have
    +     * already been eliminated from the input.  Retaining the paranoia
    +     * check is still valuable, however.
    +     */
    +    return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */
    +  }
       start = ptr;
       while (HAS_CHAR(enc, ptr, end)) {
         switch (BYTE_TYPE(enc, ptr)) {
    @@ -1258,8 +1293,14 @@ PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr,
       const char *start;
       if (ptr >= end)
         return XML_TOK_NONE;
    -  else if (! HAS_CHAR(enc, ptr, end))
    -    return XML_TOK_PARTIAL;
    +  else if (! HAS_CHAR(enc, ptr, end)) {
    +    /* This line cannot be executed.  The incoming data has already
    +     * been tokenized once, so incomplete characters like this have
    +     * already been eliminated from the input.  Retaining the paranoia
    +     * check is still valuable, however.
    +     */
    +    return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */
    +  }
       start = ptr;
       while (HAS_CHAR(enc, ptr, end)) {
         switch (BYTE_TYPE(enc, ptr)) {
    @@ -1403,6 +1444,7 @@ PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end,
         case BT_NMSTRT:
           if (!(BYTE_TO_ASCII(enc, ptr) & ~0x7f))
             break;
    +      /* fall through */
         default:
           switch (BYTE_TO_ASCII(enc, ptr)) {
           case 0x24: /* $ */
    @@ -1614,77 +1656,19 @@ PREFIX(predefinedEntityName)(const ENCODING *UNUSED_P(enc), const char *ptr,
       return 0;
     }
     
    -static int PTRCALL
    -PREFIX(sameName)(const ENCODING *enc, const char *ptr1, const char *ptr2)
    -{
    -  for (;;) {
    -    switch (BYTE_TYPE(enc, ptr1)) {
    -#define LEAD_CASE(n) \
    -    case BT_LEAD ## n: \
    -      if (*ptr1++ != *ptr2++) \
    -        return 0;
    -    LEAD_CASE(4) LEAD_CASE(3) LEAD_CASE(2)
    -#undef LEAD_CASE
    -      /* fall through */
    -      if (*ptr1++ != *ptr2++)
    -        return 0;
    -      break;
    -    case BT_NONASCII:
    -    case BT_NMSTRT:
    -#ifdef XML_NS
    -    case BT_COLON:
    -#endif
    -    case BT_HEX:
    -    case BT_DIGIT:
    -    case BT_NAME:
    -    case BT_MINUS:
    -      if (*ptr2++ != *ptr1++)
    -        return 0;
    -      if (MINBPC(enc) > 1) {
    -        if (*ptr2++ != *ptr1++)
    -          return 0;
    -        if (MINBPC(enc) > 2) {
    -          if (*ptr2++ != *ptr1++)
    -            return 0;
    -          if (MINBPC(enc) > 3) {
    -            if (*ptr2++ != *ptr1++)
    -              return 0;
    -          }
    -        }
    -      }
    -      break;
    -    default:
    -      if (MINBPC(enc) == 1 && *ptr1 == *ptr2)
    -        return 1;
    -      switch (BYTE_TYPE(enc, ptr2)) {
    -      case BT_LEAD2:
    -      case BT_LEAD3:
    -      case BT_LEAD4:
    -      case BT_NONASCII:
    -      case BT_NMSTRT:
    -#ifdef XML_NS
    -      case BT_COLON:
    -#endif
    -      case BT_HEX:
    -      case BT_DIGIT:
    -      case BT_NAME:
    -      case BT_MINUS:
    -        return 0;
    -      default:
    -        return 1;
    -      }
    -    }
    -  }
    -  /* not reached */
    -}
    -
     static int PTRCALL
     PREFIX(nameMatchesAscii)(const ENCODING *UNUSED_P(enc), const char *ptr1,
                              const char *end1, const char *ptr2)
     {
       for (; *ptr2; ptr1 += MINBPC(enc), ptr2++) {
    -    if (end1 - ptr1 < MINBPC(enc))
    -      return 0;
    +    if (end1 - ptr1 < MINBPC(enc)) {
    +      /* This line cannot be executed.  The incoming data has already
    +       * been tokenized once, so incomplete characters like this have
    +       * already been eliminated from the input.  Retaining the
    +       * paranoia check is still valuable, however.
    +       */
    +      return 0; /* LCOV_EXCL_LINE */
    +    }
         if (!CHAR_MATCHES(enc, ptr1, *ptr2))
           return 0;
       }
    diff --git a/contrib/expat/lib/xmltok_impl.h b/contrib/expat/lib/xmltok_impl.h
    index da0ea60a657d..a6420f48eedc 100644
    --- a/contrib/expat/lib/xmltok_impl.h
    +++ b/contrib/expat/lib/xmltok_impl.h
    @@ -1,6 +1,33 @@
     /*
    -Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -See the file COPYING for copying permission.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     enum {
    diff --git a/contrib/expat/lib/xmltok_ns.c b/contrib/expat/lib/xmltok_ns.c
    index c3b88fdf4e3e..23d31e8e4249 100644
    --- a/contrib/expat/lib/xmltok_ns.c
    +++ b/contrib/expat/lib/xmltok_ns.c
    @@ -1,8 +1,35 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/* This file is included!
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
    -/* This file is included! */
     #ifdef XML_TOK_NS_C
     
     const ENCODING *
    diff --git a/contrib/expat/run.sh.in b/contrib/expat/run.sh.in
    new file mode 100644
    index 000000000000..ff3fb36447ca
    --- /dev/null
    +++ b/contrib/expat/run.sh.in
    @@ -0,0 +1,12 @@
    +#! /usr/bin/env bash
    +# Copyright (C) 2017 Expat development team
    +# Licensed under the MIT license
    +
    +case "@host@" in
    +*-mingw*)
    +    exec wine "$@"
    +    ;;
    +*)
    +    exec "$@"
    +    ;;
    +esac
    diff --git a/contrib/expat/test-driver-wrapper.sh b/contrib/expat/test-driver-wrapper.sh
    new file mode 100755
    index 000000000000..30b34d547aec
    --- /dev/null
    +++ b/contrib/expat/test-driver-wrapper.sh
    @@ -0,0 +1,43 @@
    +#! /bin/bash
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +set -e
    +top_srcdir="$(dirname "$(type -p "$0")")"
    +top_builddir=..
    +
    +# Suck up all dash-dash test-driver arguments
    +test_driver_args=()
    +while [[ ${1} != '--' ]]; do
    +    test_driver_args=( "${test_driver_args[@]}" "${1}" )
    +    shift
    +done
    +shift  # drop "--"
    +
    +exec "${top_srcdir}"/conftools/test-driver "${test_driver_args[@]}" "${top_builddir}"/run.sh "$@"
    diff --git a/contrib/expat/tests/Makefile.am b/contrib/expat/tests/Makefile.am
    new file mode 100644
    index 000000000000..742ed437dbde
    --- /dev/null
    +++ b/contrib/expat/tests/Makefile.am
    @@ -0,0 +1,66 @@
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +SUBDIRS = . benchmark
    +
    +AM_CPPFLAGS = -I$(srcdir)/../lib
    +
    +noinst_LIBRARIES = libruntests.a
    +
    +check_PROGRAMS = runtests runtestspp
    +TESTS = runtests runtestspp
    +
    +# To support MinGW and Non-MinGW at the same time:
    +LOG_DRIVER = $(srcdir)/../test-driver-wrapper.sh
    +
    +libruntests_a_SOURCES = \
    +    chardata.c \
    +    structdata.c \
    +    memcheck.c \
    +    minicheck.c
    +
    +runtests_SOURCES = \
    +    runtests.c
    +
    +runtestspp_SOURCES = \
    +    runtestspp.cpp
    +
    +runtests_LDADD = libruntests.a ../lib/libexpat.la
    +runtestspp_LDADD = libruntests.a ../lib/libexpat.la
    +
    +EXTRA_DIST = \
    +    chardata.h \
    +    structdata.h \
    +    minicheck.h \
    +    memcheck.h \
    +    README.txt \
    +    udiffer.py \
    +    xmltest.log.expected \
    +    xmltest.sh
    diff --git a/contrib/expat/tests/Makefile.in b/contrib/expat/tests/Makefile.in
    new file mode 100644
    index 000000000000..723c3a961045
    --- /dev/null
    +++ b/contrib/expat/tests/Makefile.in
    @@ -0,0 +1,1219 @@
    +# Makefile.in generated by automake 1.15.1 from Makefile.am.
    +# @configure_input@
    +
    +# Copyright (C) 1994-2017 Free Software Foundation, Inc.
    +
    +# This Makefile.in is free software; the Free Software Foundation
    +# gives unlimited permission to copy and/or distribute it,
    +# with or without modifications, as long as this notice is preserved.
    +
    +# This program is distributed in the hope that it will be useful,
    +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
    +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
    +# PARTICULAR PURPOSE.
    +
    +@SET_MAKE@
    +
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +VPATH = @srcdir@
    +am__is_gnu_make = { \
    +  if test -z '$(MAKELEVEL)'; then \
    +    false; \
    +  elif test -n '$(MAKE_HOST)'; then \
    +    true; \
    +  elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
    +    true; \
    +  else \
    +    false; \
    +  fi; \
    +}
    +am__make_running_with_option = \
    +  case $${target_option-} in \
    +      ?) ;; \
    +      *) echo "am__make_running_with_option: internal error: invalid" \
    +              "target option '$${target_option-}' specified" >&2; \
    +         exit 1;; \
    +  esac; \
    +  has_opt=no; \
    +  sane_makeflags=$$MAKEFLAGS; \
    +  if $(am__is_gnu_make); then \
    +    sane_makeflags=$$MFLAGS; \
    +  else \
    +    case $$MAKEFLAGS in \
    +      *\\[\ \	]*) \
    +        bs=\\; \
    +        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
    +          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
    +    esac; \
    +  fi; \
    +  skip_next=no; \
    +  strip_trailopt () \
    +  { \
    +    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
    +  }; \
    +  for flg in $$sane_makeflags; do \
    +    test $$skip_next = yes && { skip_next=no; continue; }; \
    +    case $$flg in \
    +      *=*|--*) continue;; \
    +        -*I) strip_trailopt 'I'; skip_next=yes;; \
    +      -*I?*) strip_trailopt 'I';; \
    +        -*O) strip_trailopt 'O'; skip_next=yes;; \
    +      -*O?*) strip_trailopt 'O';; \
    +        -*l) strip_trailopt 'l'; skip_next=yes;; \
    +      -*l?*) strip_trailopt 'l';; \
    +      -[dEDm]) skip_next=yes;; \
    +      -[JT]) skip_next=yes;; \
    +    esac; \
    +    case $$flg in \
    +      *$$target_option*) has_opt=yes; break;; \
    +    esac; \
    +  done; \
    +  test $$has_opt = yes
    +am__make_dryrun = (target_option=n; $(am__make_running_with_option))
    +am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
    +pkgdatadir = $(datadir)/@PACKAGE@
    +pkgincludedir = $(includedir)/@PACKAGE@
    +pkglibdir = $(libdir)/@PACKAGE@
    +pkglibexecdir = $(libexecdir)/@PACKAGE@
    +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
    +install_sh_DATA = $(install_sh) -c -m 644
    +install_sh_PROGRAM = $(install_sh) -c
    +install_sh_SCRIPT = $(install_sh) -c
    +INSTALL_HEADER = $(INSTALL_DATA)
    +transform = $(program_transform_name)
    +NORMAL_INSTALL = :
    +PRE_INSTALL = :
    +POST_INSTALL = :
    +NORMAL_UNINSTALL = :
    +PRE_UNINSTALL = :
    +POST_UNINSTALL = :
    +build_triplet = @build@
    +host_triplet = @host@
    +check_PROGRAMS = runtests$(EXEEXT) runtestspp$(EXEEXT)
    +TESTS = runtests$(EXEEXT) runtestspp$(EXEEXT)
    +subdir = tests
    +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
    +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
    +	$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
    +	$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
    +	$(top_srcdir)/conftools/ac_c_bigendian_cross.m4 \
    +	$(top_srcdir)/configure.ac
    +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
    +	$(ACLOCAL_M4)
    +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON)
    +mkinstalldirs = $(install_sh) -d
    +CONFIG_HEADER = $(top_builddir)/expat_config.h
    +CONFIG_CLEAN_FILES =
    +CONFIG_CLEAN_VPATH_FILES =
    +LIBRARIES = $(noinst_LIBRARIES)
    +ARFLAGS = cru
    +AM_V_AR = $(am__v_AR_@AM_V@)
    +am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@)
    +am__v_AR_0 = @echo "  AR      " $@;
    +am__v_AR_1 = 
    +libruntests_a_AR = $(AR) $(ARFLAGS)
    +libruntests_a_LIBADD =
    +am_libruntests_a_OBJECTS = chardata.$(OBJEXT) structdata.$(OBJEXT) \
    +	memcheck.$(OBJEXT) minicheck.$(OBJEXT)
    +libruntests_a_OBJECTS = $(am_libruntests_a_OBJECTS)
    +am_runtests_OBJECTS = runtests.$(OBJEXT)
    +runtests_OBJECTS = $(am_runtests_OBJECTS)
    +runtests_DEPENDENCIES = libruntests.a ../lib/libexpat.la
    +AM_V_lt = $(am__v_lt_@AM_V@)
    +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
    +am__v_lt_0 = --silent
    +am__v_lt_1 = 
    +am_runtestspp_OBJECTS = runtestspp.$(OBJEXT)
    +runtestspp_OBJECTS = $(am_runtestspp_OBJECTS)
    +runtestspp_DEPENDENCIES = libruntests.a ../lib/libexpat.la
    +AM_V_P = $(am__v_P_@AM_V@)
    +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
    +am__v_P_0 = false
    +am__v_P_1 = :
    +AM_V_GEN = $(am__v_GEN_@AM_V@)
    +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
    +am__v_GEN_0 = @echo "  GEN     " $@;
    +am__v_GEN_1 = 
    +AM_V_at = $(am__v_at_@AM_V@)
    +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
    +am__v_at_0 = @
    +am__v_at_1 = 
    +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
    +depcomp = $(SHELL) $(top_srcdir)/conftools/depcomp
    +am__depfiles_maybe = depfiles
    +am__mv = mv -f
    +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
    +	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
    +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
    +	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
    +	$(AM_CFLAGS) $(CFLAGS)
    +AM_V_CC = $(am__v_CC_@AM_V@)
    +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
    +am__v_CC_0 = @echo "  CC      " $@;
    +am__v_CC_1 = 
    +CCLD = $(CC)
    +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
    +	$(AM_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_CCLD = $(am__v_CCLD_@AM_V@)
    +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
    +am__v_CCLD_0 = @echo "  CCLD    " $@;
    +am__v_CCLD_1 = 
    +CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
    +	$(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)
    +LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \
    +	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
    +	$(AM_CXXFLAGS) $(CXXFLAGS)
    +AM_V_CXX = $(am__v_CXX_@AM_V@)
    +am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@)
    +am__v_CXX_0 = @echo "  CXX     " $@;
    +am__v_CXX_1 = 
    +CXXLD = $(CXX)
    +CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \
    +	$(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_CXXLD = $(am__v_CXXLD_@AM_V@)
    +am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@)
    +am__v_CXXLD_0 = @echo "  CXXLD   " $@;
    +am__v_CXXLD_1 = 
    +SOURCES = $(libruntests_a_SOURCES) $(runtests_SOURCES) \
    +	$(runtestspp_SOURCES)
    +DIST_SOURCES = $(libruntests_a_SOURCES) $(runtests_SOURCES) \
    +	$(runtestspp_SOURCES)
    +RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
    +	ctags-recursive dvi-recursive html-recursive info-recursive \
    +	install-data-recursive install-dvi-recursive \
    +	install-exec-recursive install-html-recursive \
    +	install-info-recursive install-pdf-recursive \
    +	install-ps-recursive install-recursive installcheck-recursive \
    +	installdirs-recursive pdf-recursive ps-recursive \
    +	tags-recursive uninstall-recursive
    +am__can_run_installinfo = \
    +  case $$AM_UPDATE_INFO_DIR in \
    +    n|no|NO) false;; \
    +    *) (install-info --version) >/dev/null 2>&1;; \
    +  esac
    +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive	\
    +  distclean-recursive maintainer-clean-recursive
    +am__recursive_targets = \
    +  $(RECURSIVE_TARGETS) \
    +  $(RECURSIVE_CLEAN_TARGETS) \
    +  $(am__extra_recursive_targets)
    +AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
    +	check recheck distdir
    +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
    +# Read a list of newline-separated strings from the standard input,
    +# and print each of them once, without duplicates.  Input order is
    +# *not* preserved.
    +am__uniquify_input = $(AWK) '\
    +  BEGIN { nonempty = 0; } \
    +  { items[$$0] = 1; nonempty = 1; } \
    +  END { if (nonempty) { for (i in items) print i; }; } \
    +'
    +# Make sure the list of sources is unique.  This is necessary because,
    +# e.g., the same source file might be shared among _SOURCES variables
    +# for different programs/libraries.
    +am__define_uniq_tagged_files = \
    +  list='$(am__tagged_files)'; \
    +  unique=`for i in $$list; do \
    +    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
    +  done | $(am__uniquify_input)`
    +ETAGS = etags
    +CTAGS = ctags
    +am__tty_colors_dummy = \
    +  mgn= red= grn= lgn= blu= brg= std=; \
    +  am__color_tests=no
    +am__tty_colors = { \
    +  $(am__tty_colors_dummy); \
    +  if test "X$(AM_COLOR_TESTS)" = Xno; then \
    +    am__color_tests=no; \
    +  elif test "X$(AM_COLOR_TESTS)" = Xalways; then \
    +    am__color_tests=yes; \
    +  elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \
    +    am__color_tests=yes; \
    +  fi; \
    +  if test $$am__color_tests = yes; then \
    +    red=''; \
    +    grn=''; \
    +    lgn=''; \
    +    blu=''; \
    +    mgn=''; \
    +    brg=''; \
    +    std=''; \
    +  fi; \
    +}
    +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
    +am__vpath_adj = case $$p in \
    +    $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
    +    *) f=$$p;; \
    +  esac;
    +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
    +am__install_max = 40
    +am__nobase_strip_setup = \
    +  srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
    +am__nobase_strip = \
    +  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
    +am__nobase_list = $(am__nobase_strip_setup); \
    +  for p in $$list; do echo "$$p $$p"; done | \
    +  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
    +  $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
    +    if (++n[$$2] == $(am__install_max)) \
    +      { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
    +    END { for (dir in files) print dir, files[dir] }'
    +am__base_list = \
    +  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
    +  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
    +am__uninstall_files_from_dir = { \
    +  test -z "$$files" \
    +    || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
    +    || { echo " ( cd '$$dir' && rm -f" $$files ")"; \
    +         $(am__cd) "$$dir" && rm -f $$files; }; \
    +  }
    +am__recheck_rx = ^[ 	]*:recheck:[ 	]*
    +am__global_test_result_rx = ^[ 	]*:global-test-result:[ 	]*
    +am__copy_in_global_log_rx = ^[ 	]*:copy-in-global-log:[ 	]*
    +# A command that, given a newline-separated list of test names on the
    +# standard input, print the name of the tests that are to be re-run
    +# upon "make recheck".
    +am__list_recheck_tests = $(AWK) '{ \
    +  recheck = 1; \
    +  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
    +    { \
    +      if (rc < 0) \
    +        { \
    +          if ((getline line2 < ($$0 ".log")) < 0) \
    +	    recheck = 0; \
    +          break; \
    +        } \
    +      else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \
    +        { \
    +          recheck = 0; \
    +          break; \
    +        } \
    +      else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \
    +        { \
    +          break; \
    +        } \
    +    }; \
    +  if (recheck) \
    +    print $$0; \
    +  close ($$0 ".trs"); \
    +  close ($$0 ".log"); \
    +}'
    +# A command that, given a newline-separated list of test names on the
    +# standard input, create the global log from their .trs and .log files.
    +am__create_global_log = $(AWK) ' \
    +function fatal(msg) \
    +{ \
    +  print "fatal: making $@: " msg | "cat >&2"; \
    +  exit 1; \
    +} \
    +function rst_section(header) \
    +{ \
    +  print header; \
    +  len = length(header); \
    +  for (i = 1; i <= len; i = i + 1) \
    +    printf "="; \
    +  printf "\n\n"; \
    +} \
    +{ \
    +  copy_in_global_log = 1; \
    +  global_test_result = "RUN"; \
    +  while ((rc = (getline line < ($$0 ".trs"))) != 0) \
    +    { \
    +      if (rc < 0) \
    +         fatal("failed to read from " $$0 ".trs"); \
    +      if (line ~ /$(am__global_test_result_rx)/) \
    +        { \
    +          sub("$(am__global_test_result_rx)", "", line); \
    +          sub("[ 	]*$$", "", line); \
    +          global_test_result = line; \
    +        } \
    +      else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \
    +        copy_in_global_log = 0; \
    +    }; \
    +  if (copy_in_global_log) \
    +    { \
    +      rst_section(global_test_result ": " $$0); \
    +      while ((rc = (getline line < ($$0 ".log"))) != 0) \
    +      { \
    +        if (rc < 0) \
    +          fatal("failed to read from " $$0 ".log"); \
    +        print line; \
    +      }; \
    +      printf "\n"; \
    +    }; \
    +  close ($$0 ".trs"); \
    +  close ($$0 ".log"); \
    +}'
    +# Restructured Text title.
    +am__rst_title = { sed 's/.*/   &   /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; }
    +# Solaris 10 'make', and several other traditional 'make' implementations,
    +# pass "-e" to $(SHELL), and POSIX 2008 even requires this.  Work around it
    +# by disabling -e (using the XSI extension "set +e") if it's set.
    +am__sh_e_setup = case $$- in *e*) set +e;; esac
    +# Default flags passed to test drivers.
    +am__common_driver_flags = \
    +  --color-tests "$$am__color_tests" \
    +  --enable-hard-errors "$$am__enable_hard_errors" \
    +  --expect-failure "$$am__expect_failure"
    +# To be inserted before the command running the test.  Creates the
    +# directory for the log if needed.  Stores in $dir the directory
    +# containing $f, in $tst the test, in $log the log.  Executes the
    +# developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and
    +# passes TESTS_ENVIRONMENT.  Set up options for the wrapper that
    +# will run the test scripts (or their associated LOG_COMPILER, if
    +# thy have one).
    +am__check_pre = \
    +$(am__sh_e_setup);					\
    +$(am__vpath_adj_setup) $(am__vpath_adj)			\
    +$(am__tty_colors);					\
    +srcdir=$(srcdir); export srcdir;			\
    +case "$@" in						\
    +  */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;;	\
    +    *) am__odir=.;; 					\
    +esac;							\
    +test "x$$am__odir" = x"." || test -d "$$am__odir" 	\
    +  || $(MKDIR_P) "$$am__odir" || exit $$?;		\
    +if test -f "./$$f"; then dir=./;			\
    +elif test -f "$$f"; then dir=;				\
    +else dir="$(srcdir)/"; fi;				\
    +tst=$$dir$$f; log='$@'; 				\
    +if test -n '$(DISABLE_HARD_ERRORS)'; then		\
    +  am__enable_hard_errors=no; 				\
    +else							\
    +  am__enable_hard_errors=yes; 				\
    +fi; 							\
    +case " $(XFAIL_TESTS) " in				\
    +  *[\ \	]$$f[\ \	]* | *[\ \	]$$dir$$f[\ \	]*) \
    +    am__expect_failure=yes;;				\
    +  *)							\
    +    am__expect_failure=no;;				\
    +esac; 							\
    +$(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT)
    +# A shell command to get the names of the tests scripts with any registered
    +# extension removed (i.e., equivalently, the names of the test logs, with
    +# the '.log' extension removed).  The result is saved in the shell variable
    +# '$bases'.  This honors runtime overriding of TESTS and TEST_LOGS.  Sadly,
    +# we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)",
    +# since that might cause problem with VPATH rewrites for suffix-less tests.
    +# See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'.
    +am__set_TESTS_bases = \
    +  bases='$(TEST_LOGS)'; \
    +  bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \
    +  bases=`echo $$bases`
    +RECHECK_LOGS = $(TEST_LOGS)
    +TEST_SUITE_LOG = test-suite.log
    +TEST_EXTENSIONS = @EXEEXT@ .test
    +LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS)
    +am__set_b = \
    +  case '$@' in \
    +    */*) \
    +      case '$*' in \
    +        */*) b='$*';; \
    +          *) b=`echo '$@' | sed 's/\.log$$//'`; \
    +       esac;; \
    +    *) \
    +      b='$*';; \
    +  esac
    +am__test_logs1 = $(TESTS:=.log)
    +am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log)
    +TEST_LOGS = $(am__test_logs2:.test.log=.log)
    +TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/conftools/test-driver
    +TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \
    +	$(TEST_LOG_FLAGS)
    +DIST_SUBDIRS = $(SUBDIRS)
    +am__DIST_COMMON = $(srcdir)/Makefile.in \
    +	$(top_srcdir)/conftools/depcomp \
    +	$(top_srcdir)/conftools/test-driver
    +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
    +am__relativize = \
    +  dir0=`pwd`; \
    +  sed_first='s,^\([^/]*\)/.*$$,\1,'; \
    +  sed_rest='s,^[^/]*/*,,'; \
    +  sed_last='s,^.*/\([^/]*\)$$,\1,'; \
    +  sed_butlast='s,/*[^/]*$$,,'; \
    +  while test -n "$$dir1"; do \
    +    first=`echo "$$dir1" | sed -e "$$sed_first"`; \
    +    if test "$$first" != "."; then \
    +      if test "$$first" = ".."; then \
    +        dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
    +        dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
    +      else \
    +        first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
    +        if test "$$first2" = "$$first"; then \
    +          dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
    +        else \
    +          dir2="../$$dir2"; \
    +        fi; \
    +        dir0="$$dir0"/"$$first"; \
    +      fi; \
    +    fi; \
    +    dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
    +  done; \
    +  reldir="$$dir2"
    +ACLOCAL = @ACLOCAL@
    +AMTAR = @AMTAR@
    +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
    +AR = @AR@
    +AS = @AS@
    +AUTOCONF = @AUTOCONF@
    +AUTOHEADER = @AUTOHEADER@
    +AUTOMAKE = @AUTOMAKE@
    +AWK = @AWK@
    +CC = @CC@
    +CCDEPMODE = @CCDEPMODE@
    +CFLAGS = @CFLAGS@
    +CPP = @CPP@
    +CPPFLAGS = @CPPFLAGS@
    +CXX = @CXX@
    +CXXCPP = @CXXCPP@
    +CXXDEPMODE = @CXXDEPMODE@
    +CXXFLAGS = @CXXFLAGS@
    +CYGPATH_W = @CYGPATH_W@
    +DEFS = @DEFS@
    +DEPDIR = @DEPDIR@
    +DLLTOOL = @DLLTOOL@
    +DOCBOOK_TO_MAN = @DOCBOOK_TO_MAN@
    +DSYMUTIL = @DSYMUTIL@
    +DUMPBIN = @DUMPBIN@
    +ECHO_C = @ECHO_C@
    +ECHO_N = @ECHO_N@
    +ECHO_T = @ECHO_T@
    +EGREP = @EGREP@
    +EXEEXT = @EXEEXT@
    +FGREP = @FGREP@
    +FILEMAP = @FILEMAP@
    +GREP = @GREP@
    +INSTALL = @INSTALL@
    +INSTALL_DATA = @INSTALL_DATA@
    +INSTALL_PROGRAM = @INSTALL_PROGRAM@
    +INSTALL_SCRIPT = @INSTALL_SCRIPT@
    +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
    +LD = @LD@
    +LDFLAGS = @LDFLAGS@
    +LIBAGE = @LIBAGE@
    +LIBCURRENT = @LIBCURRENT@
    +LIBOBJS = @LIBOBJS@
    +LIBREVISION = @LIBREVISION@
    +LIBS = @LIBS@
    +LIBTOOL = @LIBTOOL@
    +LIPO = @LIPO@
    +LN_S = @LN_S@
    +LTLIBOBJS = @LTLIBOBJS@
    +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
    +MAKEINFO = @MAKEINFO@
    +MANIFEST_TOOL = @MANIFEST_TOOL@
    +MKDIR_P = @MKDIR_P@
    +NM = @NM@
    +NMEDIT = @NMEDIT@
    +OBJDUMP = @OBJDUMP@
    +OBJEXT = @OBJEXT@
    +OTOOL = @OTOOL@
    +OTOOL64 = @OTOOL64@
    +PACKAGE = @PACKAGE@
    +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
    +PACKAGE_NAME = @PACKAGE_NAME@
    +PACKAGE_STRING = @PACKAGE_STRING@
    +PACKAGE_TARNAME = @PACKAGE_TARNAME@
    +PACKAGE_URL = @PACKAGE_URL@
    +PACKAGE_VERSION = @PACKAGE_VERSION@
    +PATH_SEPARATOR = @PATH_SEPARATOR@
    +RANLIB = @RANLIB@
    +SED = @SED@
    +SET_MAKE = @SET_MAKE@
    +SHELL = @SHELL@
    +STRIP = @STRIP@
    +VERSION = @VERSION@
    +abs_builddir = @abs_builddir@
    +abs_srcdir = @abs_srcdir@
    +abs_top_builddir = @abs_top_builddir@
    +abs_top_srcdir = @abs_top_srcdir@
    +ac_ct_AR = @ac_ct_AR@
    +ac_ct_CC = @ac_ct_CC@
    +ac_ct_CXX = @ac_ct_CXX@
    +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
    +am__include = @am__include@
    +am__leading_dot = @am__leading_dot@
    +am__quote = @am__quote@
    +am__tar = @am__tar@
    +am__untar = @am__untar@
    +bindir = @bindir@
    +build = @build@
    +build_alias = @build_alias@
    +build_cpu = @build_cpu@
    +build_os = @build_os@
    +build_vendor = @build_vendor@
    +builddir = @builddir@
    +datadir = @datadir@
    +datarootdir = @datarootdir@
    +docdir = @docdir@
    +dvidir = @dvidir@
    +exec_prefix = @exec_prefix@
    +host = @host@
    +host_alias = @host_alias@
    +host_cpu = @host_cpu@
    +host_os = @host_os@
    +host_vendor = @host_vendor@
    +htmldir = @htmldir@
    +includedir = @includedir@
    +infodir = @infodir@
    +install_sh = @install_sh@
    +libdir = @libdir@
    +libexecdir = @libexecdir@
    +localedir = @localedir@
    +localstatedir = @localstatedir@
    +mandir = @mandir@
    +mkdir_p = @mkdir_p@
    +oldincludedir = @oldincludedir@
    +pdfdir = @pdfdir@
    +prefix = @prefix@
    +program_transform_name = @program_transform_name@
    +psdir = @psdir@
    +sbindir = @sbindir@
    +sharedstatedir = @sharedstatedir@
    +srcdir = @srcdir@
    +sysconfdir = @sysconfdir@
    +target_alias = @target_alias@
    +top_build_prefix = @top_build_prefix@
    +top_builddir = @top_builddir@
    +top_srcdir = @top_srcdir@
    +SUBDIRS = . benchmark
    +AM_CPPFLAGS = -I$(srcdir)/../lib
    +noinst_LIBRARIES = libruntests.a
    +
    +# To support MinGW and Non-MinGW at the same time:
    +LOG_DRIVER = $(srcdir)/../test-driver-wrapper.sh
    +libruntests_a_SOURCES = \
    +    chardata.c \
    +    structdata.c \
    +    memcheck.c \
    +    minicheck.c
    +
    +runtests_SOURCES = \
    +    runtests.c
    +
    +runtestspp_SOURCES = \
    +    runtestspp.cpp
    +
    +runtests_LDADD = libruntests.a ../lib/libexpat.la
    +runtestspp_LDADD = libruntests.a ../lib/libexpat.la
    +EXTRA_DIST = \
    +    chardata.h \
    +    structdata.h \
    +    minicheck.h \
    +    memcheck.h \
    +    README.txt \
    +    udiffer.py \
    +    xmltest.log.expected \
    +    xmltest.sh
    +
    +all: all-recursive
    +
    +.SUFFIXES:
    +.SUFFIXES: .c .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs
    +$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
    +	@for dep in $?; do \
    +	  case '$(am__configure_deps)' in \
    +	    *$$dep*) \
    +	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
    +	        && { if test -f $@; then exit 0; else break; fi; }; \
    +	      exit 1;; \
    +	  esac; \
    +	done; \
    +	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu tests/Makefile'; \
    +	$(am__cd) $(top_srcdir) && \
    +	  $(AUTOMAKE) --gnu tests/Makefile
    +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
    +	@case '$?' in \
    +	  *config.status*) \
    +	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
    +	  *) \
    +	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
    +	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
    +	esac;
    +
    +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +
    +$(top_srcdir)/configure:  $(am__configure_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(am__aclocal_m4_deps):
    +
    +clean-noinstLIBRARIES:
    +	-test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
    +
    +libruntests.a: $(libruntests_a_OBJECTS) $(libruntests_a_DEPENDENCIES) $(EXTRA_libruntests_a_DEPENDENCIES) 
    +	$(AM_V_at)-rm -f libruntests.a
    +	$(AM_V_AR)$(libruntests_a_AR) libruntests.a $(libruntests_a_OBJECTS) $(libruntests_a_LIBADD)
    +	$(AM_V_at)$(RANLIB) libruntests.a
    +
    +clean-checkPROGRAMS:
    +	@list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list || exit $$?; \
    +	test -n "$(EXEEXT)" || exit 0; \
    +	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list
    +
    +runtests$(EXEEXT): $(runtests_OBJECTS) $(runtests_DEPENDENCIES) $(EXTRA_runtests_DEPENDENCIES) 
    +	@rm -f runtests$(EXEEXT)
    +	$(AM_V_CCLD)$(LINK) $(runtests_OBJECTS) $(runtests_LDADD) $(LIBS)
    +
    +runtestspp$(EXEEXT): $(runtestspp_OBJECTS) $(runtestspp_DEPENDENCIES) $(EXTRA_runtestspp_DEPENDENCIES) 
    +	@rm -f runtestspp$(EXEEXT)
    +	$(AM_V_CXXLD)$(CXXLINK) $(runtestspp_OBJECTS) $(runtestspp_LDADD) $(LIBS)
    +
    +mostlyclean-compile:
    +	-rm -f *.$(OBJEXT)
    +
    +distclean-compile:
    +	-rm -f *.tab.c
    +
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chardata.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/memcheck.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minicheck.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/runtests.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/runtestspp.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/structdata.Po@am__quote@
    +
    +.c.o:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
    +
    +.c.obj:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
    +
    +.c.lo:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
    +
    +.cpp.o:
    +@am__fastdepCXX_TRUE@	$(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCXX_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCXX_FALSE@	$(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCXX_FALSE@	DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCXX_FALSE@	$(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $<
    +
    +.cpp.obj:
    +@am__fastdepCXX_TRUE@	$(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
    +@am__fastdepCXX_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCXX_FALSE@	$(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCXX_FALSE@	DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCXX_FALSE@	$(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
    +
    +.cpp.lo:
    +@am__fastdepCXX_TRUE@	$(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCXX_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
    +@AMDEP_TRUE@@am__fastdepCXX_FALSE@	$(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCXX_FALSE@	DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCXX_FALSE@	$(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $<
    +
    +mostlyclean-libtool:
    +	-rm -f *.lo
    +
    +clean-libtool:
    +	-rm -rf .libs _libs
    +
    +# This directory's subdirectories are mostly independent; you can cd
    +# into them and run 'make' without going through this Makefile.
    +# To change the values of 'make' variables: instead of editing Makefiles,
    +# (1) if the variable is set in 'config.status', edit 'config.status'
    +#     (which will cause the Makefiles to be regenerated when you run 'make');
    +# (2) otherwise, pass the desired values on the 'make' command line.
    +$(am__recursive_targets):
    +	@fail=; \
    +	if $(am__make_keepgoing); then \
    +	  failcom='fail=yes'; \
    +	else \
    +	  failcom='exit 1'; \
    +	fi; \
    +	dot_seen=no; \
    +	target=`echo $@ | sed s/-recursive//`; \
    +	case "$@" in \
    +	  distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
    +	  *) list='$(SUBDIRS)' ;; \
    +	esac; \
    +	for subdir in $$list; do \
    +	  echo "Making $$target in $$subdir"; \
    +	  if test "$$subdir" = "."; then \
    +	    dot_seen=yes; \
    +	    local_target="$$target-am"; \
    +	  else \
    +	    local_target="$$target"; \
    +	  fi; \
    +	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
    +	  || eval $$failcom; \
    +	done; \
    +	if test "$$dot_seen" = "no"; then \
    +	  $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
    +	fi; test -z "$$fail"
    +
    +ID: $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); mkid -fID $$unique
    +tags: tags-recursive
    +TAGS: tags
    +
    +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	set x; \
    +	here=`pwd`; \
    +	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
    +	  include_option=--etags-include; \
    +	  empty_fix=.; \
    +	else \
    +	  include_option=--include; \
    +	  empty_fix=; \
    +	fi; \
    +	list='$(SUBDIRS)'; for subdir in $$list; do \
    +	  if test "$$subdir" = .; then :; else \
    +	    test ! -f $$subdir/TAGS || \
    +	      set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
    +	  fi; \
    +	done; \
    +	$(am__define_uniq_tagged_files); \
    +	shift; \
    +	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
    +	  test -n "$$unique" || unique=$$empty_fix; \
    +	  if test $$# -gt 0; then \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      "$$@" $$unique; \
    +	  else \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      $$unique; \
    +	  fi; \
    +	fi
    +ctags: ctags-recursive
    +
    +CTAGS: ctags
    +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); \
    +	test -z "$(CTAGS_ARGS)$$unique" \
    +	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
    +	     $$unique
    +
    +GTAGS:
    +	here=`$(am__cd) $(top_builddir) && pwd` \
    +	  && $(am__cd) $(top_srcdir) \
    +	  && gtags -i $(GTAGS_ARGS) "$$here"
    +cscopelist: cscopelist-recursive
    +
    +cscopelist-am: $(am__tagged_files)
    +	list='$(am__tagged_files)'; \
    +	case "$(srcdir)" in \
    +	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
    +	  *) sdir=$(subdir)/$(srcdir) ;; \
    +	esac; \
    +	for i in $$list; do \
    +	  if test -f "$$i"; then \
    +	    echo "$(subdir)/$$i"; \
    +	  else \
    +	    echo "$$sdir/$$i"; \
    +	  fi; \
    +	done >> $(top_builddir)/cscope.files
    +
    +distclean-tags:
    +	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
    +
    +# Recover from deleted '.trs' file; this should ensure that
    +# "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create
    +# both 'foo.log' and 'foo.trs'.  Break the recipe in two subshells
    +# to avoid problems with "make -n".
    +.log.trs:
    +	rm -f $< $@
    +	$(MAKE) $(AM_MAKEFLAGS) $<
    +
    +# Leading 'am--fnord' is there to ensure the list of targets does not
    +# expand to empty, as could happen e.g. with make check TESTS=''.
    +am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck)
    +am--force-recheck:
    +	@:
    +
    +$(TEST_SUITE_LOG): $(TEST_LOGS)
    +	@$(am__set_TESTS_bases); \
    +	am__f_ok () { test -f "$$1" && test -r "$$1"; }; \
    +	redo_bases=`for i in $$bases; do \
    +	              am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \
    +	            done`; \
    +	if test -n "$$redo_bases"; then \
    +	  redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \
    +	  redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \
    +	  if $(am__make_dryrun); then :; else \
    +	    rm -f $$redo_logs && rm -f $$redo_results || exit 1; \
    +	  fi; \
    +	fi; \
    +	if test -n "$$am__remaking_logs"; then \
    +	  echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \
    +	       "recursion detected" >&2; \
    +	elif test -n "$$redo_logs"; then \
    +	  am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \
    +	fi; \
    +	if $(am__make_dryrun); then :; else \
    +	  st=0;  \
    +	  errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \
    +	  for i in $$redo_bases; do \
    +	    test -f $$i.trs && test -r $$i.trs \
    +	      || { echo "$$errmsg $$i.trs" >&2; st=1; }; \
    +	    test -f $$i.log && test -r $$i.log \
    +	      || { echo "$$errmsg $$i.log" >&2; st=1; }; \
    +	  done; \
    +	  test $$st -eq 0 || exit 1; \
    +	fi
    +	@$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \
    +	ws='[ 	]'; \
    +	results=`for b in $$bases; do echo $$b.trs; done`; \
    +	test -n "$$results" || results=/dev/null; \
    +	all=`  grep "^$$ws*:test-result:"           $$results | wc -l`; \
    +	pass=` grep "^$$ws*:test-result:$$ws*PASS"  $$results | wc -l`; \
    +	fail=` grep "^$$ws*:test-result:$$ws*FAIL"  $$results | wc -l`; \
    +	skip=` grep "^$$ws*:test-result:$$ws*SKIP"  $$results | wc -l`; \
    +	xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \
    +	xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \
    +	error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \
    +	if test `expr $$fail + $$xpass + $$error` -eq 0; then \
    +	  success=true; \
    +	else \
    +	  success=false; \
    +	fi; \
    +	br='==================='; br=$$br$$br$$br$$br; \
    +	result_count () \
    +	{ \
    +	    if test x"$$1" = x"--maybe-color"; then \
    +	      maybe_colorize=yes; \
    +	    elif test x"$$1" = x"--no-color"; then \
    +	      maybe_colorize=no; \
    +	    else \
    +	      echo "$@: invalid 'result_count' usage" >&2; exit 4; \
    +	    fi; \
    +	    shift; \
    +	    desc=$$1 count=$$2; \
    +	    if test $$maybe_colorize = yes && test $$count -gt 0; then \
    +	      color_start=$$3 color_end=$$std; \
    +	    else \
    +	      color_start= color_end=; \
    +	    fi; \
    +	    echo "$${color_start}# $$desc $$count$${color_end}"; \
    +	}; \
    +	create_testsuite_report () \
    +	{ \
    +	  result_count $$1 "TOTAL:" $$all   "$$brg"; \
    +	  result_count $$1 "PASS: " $$pass  "$$grn"; \
    +	  result_count $$1 "SKIP: " $$skip  "$$blu"; \
    +	  result_count $$1 "XFAIL:" $$xfail "$$lgn"; \
    +	  result_count $$1 "FAIL: " $$fail  "$$red"; \
    +	  result_count $$1 "XPASS:" $$xpass "$$red"; \
    +	  result_count $$1 "ERROR:" $$error "$$mgn"; \
    +	}; \
    +	{								\
    +	  echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" |	\
    +	    $(am__rst_title);						\
    +	  create_testsuite_report --no-color;				\
    +	  echo;								\
    +	  echo ".. contents:: :depth: 2";				\
    +	  echo;								\
    +	  for b in $$bases; do echo $$b; done				\
    +	    | $(am__create_global_log);					\
    +	} >$(TEST_SUITE_LOG).tmp || exit 1;				\
    +	mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG);			\
    +	if $$success; then						\
    +	  col="$$grn";							\
    +	 else								\
    +	  col="$$red";							\
    +	  test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG);		\
    +	fi;								\
    +	echo "$${col}$$br$${std}"; 					\
    +	echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}";	\
    +	echo "$${col}$$br$${std}"; 					\
    +	create_testsuite_report --maybe-color;				\
    +	echo "$$col$$br$$std";						\
    +	if $$success; then :; else					\
    +	  echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}";		\
    +	  if test -n "$(PACKAGE_BUGREPORT)"; then			\
    +	    echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}";	\
    +	  fi;								\
    +	  echo "$$col$$br$$std";					\
    +	fi;								\
    +	$$success || exit 1
    +
    +check-TESTS:
    +	@list='$(RECHECK_LOGS)';           test -z "$$list" || rm -f $$list
    +	@list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list
    +	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
    +	@set +e; $(am__set_TESTS_bases); \
    +	log_list=`for i in $$bases; do echo $$i.log; done`; \
    +	trs_list=`for i in $$bases; do echo $$i.trs; done`; \
    +	log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \
    +	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \
    +	exit $$?;
    +recheck: all $(check_PROGRAMS)
    +	@test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
    +	@set +e; $(am__set_TESTS_bases); \
    +	bases=`for i in $$bases; do echo $$i; done \
    +	         | $(am__list_recheck_tests)` || exit 1; \
    +	log_list=`for i in $$bases; do echo $$i.log; done`; \
    +	log_list=`echo $$log_list`; \
    +	$(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \
    +	        am__force_recheck=am--force-recheck \
    +	        TEST_LOGS="$$log_list"; \
    +	exit $$?
    +runtests.log: runtests$(EXEEXT)
    +	@p='runtests$(EXEEXT)'; \
    +	b='runtests'; \
    +	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
    +	--log-file $$b.log --trs-file $$b.trs \
    +	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
    +	"$$tst" $(AM_TESTS_FD_REDIRECT)
    +runtestspp.log: runtestspp$(EXEEXT)
    +	@p='runtestspp$(EXEEXT)'; \
    +	b='runtestspp'; \
    +	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
    +	--log-file $$b.log --trs-file $$b.trs \
    +	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
    +	"$$tst" $(AM_TESTS_FD_REDIRECT)
    +.test.log:
    +	@p='$<'; \
    +	$(am__set_b); \
    +	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
    +	--log-file $$b.log --trs-file $$b.trs \
    +	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
    +	"$$tst" $(AM_TESTS_FD_REDIRECT)
    +@am__EXEEXT_TRUE@.test$(EXEEXT).log:
    +@am__EXEEXT_TRUE@	@p='$<'; \
    +@am__EXEEXT_TRUE@	$(am__set_b); \
    +@am__EXEEXT_TRUE@	$(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \
    +@am__EXEEXT_TRUE@	--log-file $$b.log --trs-file $$b.trs \
    +@am__EXEEXT_TRUE@	$(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \
    +@am__EXEEXT_TRUE@	"$$tst" $(AM_TESTS_FD_REDIRECT)
    +
    +distdir: $(DISTFILES)
    +	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	list='$(DISTFILES)'; \
    +	  dist_files=`for file in $$list; do echo $$file; done | \
    +	  sed -e "s|^$$srcdirstrip/||;t" \
    +	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
    +	case $$dist_files in \
    +	  */*) $(MKDIR_P) `echo "$$dist_files" | \
    +			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
    +			   sort -u` ;; \
    +	esac; \
    +	for file in $$dist_files; do \
    +	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
    +	  if test -d $$d/$$file; then \
    +	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
    +	    if test -d "$(distdir)/$$file"; then \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
    +	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
    +	  else \
    +	    test -f "$(distdir)/$$file" \
    +	    || cp -p $$d/$$file "$(distdir)/$$file" \
    +	    || exit 1; \
    +	  fi; \
    +	done
    +	@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
    +	  if test "$$subdir" = .; then :; else \
    +	    $(am__make_dryrun) \
    +	      || test -d "$(distdir)/$$subdir" \
    +	      || $(MKDIR_P) "$(distdir)/$$subdir" \
    +	      || exit 1; \
    +	    dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
    +	    $(am__relativize); \
    +	    new_distdir=$$reldir; \
    +	    dir1=$$subdir; dir2="$(top_distdir)"; \
    +	    $(am__relativize); \
    +	    new_top_distdir=$$reldir; \
    +	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
    +	    echo "     am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
    +	    ($(am__cd) $$subdir && \
    +	      $(MAKE) $(AM_MAKEFLAGS) \
    +	        top_distdir="$$new_top_distdir" \
    +	        distdir="$$new_distdir" \
    +		am__remove_distdir=: \
    +		am__skip_length_check=: \
    +		am__skip_mode_fix=: \
    +	        distdir) \
    +	      || exit 1; \
    +	  fi; \
    +	done
    +check-am: all-am
    +	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
    +	$(MAKE) $(AM_MAKEFLAGS) check-TESTS
    +check: check-recursive
    +all-am: Makefile $(LIBRARIES)
    +installdirs: installdirs-recursive
    +installdirs-am:
    +install: install-recursive
    +install-exec: install-exec-recursive
    +install-data: install-data-recursive
    +uninstall: uninstall-recursive
    +
    +install-am: all-am
    +	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
    +
    +installcheck: installcheck-recursive
    +install-strip:
    +	if test -z '$(STRIP)'; then \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	      install; \
    +	else \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
    +	fi
    +mostlyclean-generic:
    +	-test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS)
    +	-test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs)
    +	-test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG)
    +
    +clean-generic:
    +
    +distclean-generic:
    +	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
    +	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
    +
    +maintainer-clean-generic:
    +	@echo "This command is intended for maintainers to use"
    +	@echo "it deletes files that may require special tools to rebuild."
    +clean: clean-recursive
    +
    +clean-am: clean-checkPROGRAMS clean-generic clean-libtool \
    +	clean-noinstLIBRARIES mostlyclean-am
    +
    +distclean: distclean-recursive
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +distclean-am: clean-am distclean-compile distclean-generic \
    +	distclean-tags
    +
    +dvi: dvi-recursive
    +
    +dvi-am:
    +
    +html: html-recursive
    +
    +html-am:
    +
    +info: info-recursive
    +
    +info-am:
    +
    +install-data-am:
    +
    +install-dvi: install-dvi-recursive
    +
    +install-dvi-am:
    +
    +install-exec-am:
    +
    +install-html: install-html-recursive
    +
    +install-html-am:
    +
    +install-info: install-info-recursive
    +
    +install-info-am:
    +
    +install-man:
    +
    +install-pdf: install-pdf-recursive
    +
    +install-pdf-am:
    +
    +install-ps: install-ps-recursive
    +
    +install-ps-am:
    +
    +installcheck-am:
    +
    +maintainer-clean: maintainer-clean-recursive
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +maintainer-clean-am: distclean-am maintainer-clean-generic
    +
    +mostlyclean: mostlyclean-recursive
    +
    +mostlyclean-am: mostlyclean-compile mostlyclean-generic \
    +	mostlyclean-libtool
    +
    +pdf: pdf-recursive
    +
    +pdf-am:
    +
    +ps: ps-recursive
    +
    +ps-am:
    +
    +uninstall-am:
    +
    +.MAKE: $(am__recursive_targets) check-am install-am install-strip
    +
    +.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
    +	check-TESTS check-am clean clean-checkPROGRAMS clean-generic \
    +	clean-libtool clean-noinstLIBRARIES cscopelist-am ctags \
    +	ctags-am distclean distclean-compile distclean-generic \
    +	distclean-libtool distclean-tags distdir dvi dvi-am html \
    +	html-am info info-am install install-am install-data \
    +	install-data-am install-dvi install-dvi-am install-exec \
    +	install-exec-am install-html install-html-am install-info \
    +	install-info-am install-man install-pdf install-pdf-am \
    +	install-ps install-ps-am install-strip installcheck \
    +	installcheck-am installdirs installdirs-am maintainer-clean \
    +	maintainer-clean-generic mostlyclean mostlyclean-compile \
    +	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
    +	recheck tags tags-am uninstall uninstall-am
    +
    +.PRECIOUS: Makefile
    +
    +
    +# Tell versions [3.59,3.63) of GNU make to not export all variables.
    +# Otherwise a system limit (for SysV at least) may be exceeded.
    +.NOEXPORT:
    diff --git a/contrib/expat/tests/benchmark/Makefile.am b/contrib/expat/tests/benchmark/Makefile.am
    new file mode 100644
    index 000000000000..f4d7a8e2c3eb
    --- /dev/null
    +++ b/contrib/expat/tests/benchmark/Makefile.am
    @@ -0,0 +1,40 @@
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +AM_CPPFLAGS = -I$(srcdir)/../../lib
    +
    +noinst_PROGRAMS = benchmark
    +
    +benchmark_SOURCES = benchmark.c
    +
    +benchmark_LDADD = ../../lib/libexpat.la
    +
    +EXTRA_DIST = \
    +    README.txt
    diff --git a/contrib/expat/tests/benchmark/Makefile.in b/contrib/expat/tests/benchmark/Makefile.in
    new file mode 100644
    index 000000000000..d21998cc868c
    --- /dev/null
    +++ b/contrib/expat/tests/benchmark/Makefile.in
    @@ -0,0 +1,629 @@
    +# Makefile.in generated by automake 1.15.1 from Makefile.am.
    +# @configure_input@
    +
    +# Copyright (C) 1994-2017 Free Software Foundation, Inc.
    +
    +# This Makefile.in is free software; the Free Software Foundation
    +# gives unlimited permission to copy and/or distribute it,
    +# with or without modifications, as long as this notice is preserved.
    +
    +# This program is distributed in the hope that it will be useful,
    +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
    +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
    +# PARTICULAR PURPOSE.
    +
    +@SET_MAKE@
    +
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +VPATH = @srcdir@
    +am__is_gnu_make = { \
    +  if test -z '$(MAKELEVEL)'; then \
    +    false; \
    +  elif test -n '$(MAKE_HOST)'; then \
    +    true; \
    +  elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
    +    true; \
    +  else \
    +    false; \
    +  fi; \
    +}
    +am__make_running_with_option = \
    +  case $${target_option-} in \
    +      ?) ;; \
    +      *) echo "am__make_running_with_option: internal error: invalid" \
    +              "target option '$${target_option-}' specified" >&2; \
    +         exit 1;; \
    +  esac; \
    +  has_opt=no; \
    +  sane_makeflags=$$MAKEFLAGS; \
    +  if $(am__is_gnu_make); then \
    +    sane_makeflags=$$MFLAGS; \
    +  else \
    +    case $$MAKEFLAGS in \
    +      *\\[\ \	]*) \
    +        bs=\\; \
    +        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
    +          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
    +    esac; \
    +  fi; \
    +  skip_next=no; \
    +  strip_trailopt () \
    +  { \
    +    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
    +  }; \
    +  for flg in $$sane_makeflags; do \
    +    test $$skip_next = yes && { skip_next=no; continue; }; \
    +    case $$flg in \
    +      *=*|--*) continue;; \
    +        -*I) strip_trailopt 'I'; skip_next=yes;; \
    +      -*I?*) strip_trailopt 'I';; \
    +        -*O) strip_trailopt 'O'; skip_next=yes;; \
    +      -*O?*) strip_trailopt 'O';; \
    +        -*l) strip_trailopt 'l'; skip_next=yes;; \
    +      -*l?*) strip_trailopt 'l';; \
    +      -[dEDm]) skip_next=yes;; \
    +      -[JT]) skip_next=yes;; \
    +    esac; \
    +    case $$flg in \
    +      *$$target_option*) has_opt=yes; break;; \
    +    esac; \
    +  done; \
    +  test $$has_opt = yes
    +am__make_dryrun = (target_option=n; $(am__make_running_with_option))
    +am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
    +pkgdatadir = $(datadir)/@PACKAGE@
    +pkgincludedir = $(includedir)/@PACKAGE@
    +pkglibdir = $(libdir)/@PACKAGE@
    +pkglibexecdir = $(libexecdir)/@PACKAGE@
    +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
    +install_sh_DATA = $(install_sh) -c -m 644
    +install_sh_PROGRAM = $(install_sh) -c
    +install_sh_SCRIPT = $(install_sh) -c
    +INSTALL_HEADER = $(INSTALL_DATA)
    +transform = $(program_transform_name)
    +NORMAL_INSTALL = :
    +PRE_INSTALL = :
    +POST_INSTALL = :
    +NORMAL_UNINSTALL = :
    +PRE_UNINSTALL = :
    +POST_UNINSTALL = :
    +build_triplet = @build@
    +host_triplet = @host@
    +noinst_PROGRAMS = benchmark$(EXEEXT)
    +subdir = tests/benchmark
    +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
    +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
    +	$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
    +	$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
    +	$(top_srcdir)/conftools/ac_c_bigendian_cross.m4 \
    +	$(top_srcdir)/configure.ac
    +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
    +	$(ACLOCAL_M4)
    +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON)
    +mkinstalldirs = $(install_sh) -d
    +CONFIG_HEADER = $(top_builddir)/expat_config.h
    +CONFIG_CLEAN_FILES =
    +CONFIG_CLEAN_VPATH_FILES =
    +PROGRAMS = $(noinst_PROGRAMS)
    +am_benchmark_OBJECTS = benchmark.$(OBJEXT)
    +benchmark_OBJECTS = $(am_benchmark_OBJECTS)
    +benchmark_DEPENDENCIES = ../../lib/libexpat.la
    +AM_V_lt = $(am__v_lt_@AM_V@)
    +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
    +am__v_lt_0 = --silent
    +am__v_lt_1 = 
    +AM_V_P = $(am__v_P_@AM_V@)
    +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
    +am__v_P_0 = false
    +am__v_P_1 = :
    +AM_V_GEN = $(am__v_GEN_@AM_V@)
    +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
    +am__v_GEN_0 = @echo "  GEN     " $@;
    +am__v_GEN_1 = 
    +AM_V_at = $(am__v_at_@AM_V@)
    +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
    +am__v_at_0 = @
    +am__v_at_1 = 
    +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
    +depcomp = $(SHELL) $(top_srcdir)/conftools/depcomp
    +am__depfiles_maybe = depfiles
    +am__mv = mv -f
    +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
    +	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
    +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
    +	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
    +	$(AM_CFLAGS) $(CFLAGS)
    +AM_V_CC = $(am__v_CC_@AM_V@)
    +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
    +am__v_CC_0 = @echo "  CC      " $@;
    +am__v_CC_1 = 
    +CCLD = $(CC)
    +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
    +	$(AM_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_CCLD = $(am__v_CCLD_@AM_V@)
    +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
    +am__v_CCLD_0 = @echo "  CCLD    " $@;
    +am__v_CCLD_1 = 
    +SOURCES = $(benchmark_SOURCES)
    +DIST_SOURCES = $(benchmark_SOURCES)
    +am__can_run_installinfo = \
    +  case $$AM_UPDATE_INFO_DIR in \
    +    n|no|NO) false;; \
    +    *) (install-info --version) >/dev/null 2>&1;; \
    +  esac
    +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
    +# Read a list of newline-separated strings from the standard input,
    +# and print each of them once, without duplicates.  Input order is
    +# *not* preserved.
    +am__uniquify_input = $(AWK) '\
    +  BEGIN { nonempty = 0; } \
    +  { items[$$0] = 1; nonempty = 1; } \
    +  END { if (nonempty) { for (i in items) print i; }; } \
    +'
    +# Make sure the list of sources is unique.  This is necessary because,
    +# e.g., the same source file might be shared among _SOURCES variables
    +# for different programs/libraries.
    +am__define_uniq_tagged_files = \
    +  list='$(am__tagged_files)'; \
    +  unique=`for i in $$list; do \
    +    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
    +  done | $(am__uniquify_input)`
    +ETAGS = etags
    +CTAGS = ctags
    +am__DIST_COMMON = $(srcdir)/Makefile.in \
    +	$(top_srcdir)/conftools/depcomp
    +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
    +ACLOCAL = @ACLOCAL@
    +AMTAR = @AMTAR@
    +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
    +AR = @AR@
    +AS = @AS@
    +AUTOCONF = @AUTOCONF@
    +AUTOHEADER = @AUTOHEADER@
    +AUTOMAKE = @AUTOMAKE@
    +AWK = @AWK@
    +CC = @CC@
    +CCDEPMODE = @CCDEPMODE@
    +CFLAGS = @CFLAGS@
    +CPP = @CPP@
    +CPPFLAGS = @CPPFLAGS@
    +CXX = @CXX@
    +CXXCPP = @CXXCPP@
    +CXXDEPMODE = @CXXDEPMODE@
    +CXXFLAGS = @CXXFLAGS@
    +CYGPATH_W = @CYGPATH_W@
    +DEFS = @DEFS@
    +DEPDIR = @DEPDIR@
    +DLLTOOL = @DLLTOOL@
    +DOCBOOK_TO_MAN = @DOCBOOK_TO_MAN@
    +DSYMUTIL = @DSYMUTIL@
    +DUMPBIN = @DUMPBIN@
    +ECHO_C = @ECHO_C@
    +ECHO_N = @ECHO_N@
    +ECHO_T = @ECHO_T@
    +EGREP = @EGREP@
    +EXEEXT = @EXEEXT@
    +FGREP = @FGREP@
    +FILEMAP = @FILEMAP@
    +GREP = @GREP@
    +INSTALL = @INSTALL@
    +INSTALL_DATA = @INSTALL_DATA@
    +INSTALL_PROGRAM = @INSTALL_PROGRAM@
    +INSTALL_SCRIPT = @INSTALL_SCRIPT@
    +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
    +LD = @LD@
    +LDFLAGS = @LDFLAGS@
    +LIBAGE = @LIBAGE@
    +LIBCURRENT = @LIBCURRENT@
    +LIBOBJS = @LIBOBJS@
    +LIBREVISION = @LIBREVISION@
    +LIBS = @LIBS@
    +LIBTOOL = @LIBTOOL@
    +LIPO = @LIPO@
    +LN_S = @LN_S@
    +LTLIBOBJS = @LTLIBOBJS@
    +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
    +MAKEINFO = @MAKEINFO@
    +MANIFEST_TOOL = @MANIFEST_TOOL@
    +MKDIR_P = @MKDIR_P@
    +NM = @NM@
    +NMEDIT = @NMEDIT@
    +OBJDUMP = @OBJDUMP@
    +OBJEXT = @OBJEXT@
    +OTOOL = @OTOOL@
    +OTOOL64 = @OTOOL64@
    +PACKAGE = @PACKAGE@
    +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
    +PACKAGE_NAME = @PACKAGE_NAME@
    +PACKAGE_STRING = @PACKAGE_STRING@
    +PACKAGE_TARNAME = @PACKAGE_TARNAME@
    +PACKAGE_URL = @PACKAGE_URL@
    +PACKAGE_VERSION = @PACKAGE_VERSION@
    +PATH_SEPARATOR = @PATH_SEPARATOR@
    +RANLIB = @RANLIB@
    +SED = @SED@
    +SET_MAKE = @SET_MAKE@
    +SHELL = @SHELL@
    +STRIP = @STRIP@
    +VERSION = @VERSION@
    +abs_builddir = @abs_builddir@
    +abs_srcdir = @abs_srcdir@
    +abs_top_builddir = @abs_top_builddir@
    +abs_top_srcdir = @abs_top_srcdir@
    +ac_ct_AR = @ac_ct_AR@
    +ac_ct_CC = @ac_ct_CC@
    +ac_ct_CXX = @ac_ct_CXX@
    +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
    +am__include = @am__include@
    +am__leading_dot = @am__leading_dot@
    +am__quote = @am__quote@
    +am__tar = @am__tar@
    +am__untar = @am__untar@
    +bindir = @bindir@
    +build = @build@
    +build_alias = @build_alias@
    +build_cpu = @build_cpu@
    +build_os = @build_os@
    +build_vendor = @build_vendor@
    +builddir = @builddir@
    +datadir = @datadir@
    +datarootdir = @datarootdir@
    +docdir = @docdir@
    +dvidir = @dvidir@
    +exec_prefix = @exec_prefix@
    +host = @host@
    +host_alias = @host_alias@
    +host_cpu = @host_cpu@
    +host_os = @host_os@
    +host_vendor = @host_vendor@
    +htmldir = @htmldir@
    +includedir = @includedir@
    +infodir = @infodir@
    +install_sh = @install_sh@
    +libdir = @libdir@
    +libexecdir = @libexecdir@
    +localedir = @localedir@
    +localstatedir = @localstatedir@
    +mandir = @mandir@
    +mkdir_p = @mkdir_p@
    +oldincludedir = @oldincludedir@
    +pdfdir = @pdfdir@
    +prefix = @prefix@
    +program_transform_name = @program_transform_name@
    +psdir = @psdir@
    +sbindir = @sbindir@
    +sharedstatedir = @sharedstatedir@
    +srcdir = @srcdir@
    +sysconfdir = @sysconfdir@
    +target_alias = @target_alias@
    +top_build_prefix = @top_build_prefix@
    +top_builddir = @top_builddir@
    +top_srcdir = @top_srcdir@
    +AM_CPPFLAGS = -I$(srcdir)/../../lib
    +benchmark_SOURCES = benchmark.c
    +benchmark_LDADD = ../../lib/libexpat.la
    +EXTRA_DIST = \
    +    README.txt
    +
    +all: all-am
    +
    +.SUFFIXES:
    +.SUFFIXES: .c .lo .o .obj
    +$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
    +	@for dep in $?; do \
    +	  case '$(am__configure_deps)' in \
    +	    *$$dep*) \
    +	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
    +	        && { if test -f $@; then exit 0; else break; fi; }; \
    +	      exit 1;; \
    +	  esac; \
    +	done; \
    +	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu tests/benchmark/Makefile'; \
    +	$(am__cd) $(top_srcdir) && \
    +	  $(AUTOMAKE) --gnu tests/benchmark/Makefile
    +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
    +	@case '$?' in \
    +	  *config.status*) \
    +	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
    +	  *) \
    +	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
    +	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
    +	esac;
    +
    +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +
    +$(top_srcdir)/configure:  $(am__configure_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(am__aclocal_m4_deps):
    +
    +clean-noinstPROGRAMS:
    +	@list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list || exit $$?; \
    +	test -n "$(EXEEXT)" || exit 0; \
    +	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list
    +
    +benchmark$(EXEEXT): $(benchmark_OBJECTS) $(benchmark_DEPENDENCIES) $(EXTRA_benchmark_DEPENDENCIES) 
    +	@rm -f benchmark$(EXEEXT)
    +	$(AM_V_CCLD)$(LINK) $(benchmark_OBJECTS) $(benchmark_LDADD) $(LIBS)
    +
    +mostlyclean-compile:
    +	-rm -f *.$(OBJEXT)
    +
    +distclean-compile:
    +	-rm -f *.tab.c
    +
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/benchmark.Po@am__quote@
    +
    +.c.o:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
    +
    +.c.obj:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
    +
    +.c.lo:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
    +
    +mostlyclean-libtool:
    +	-rm -f *.lo
    +
    +clean-libtool:
    +	-rm -rf .libs _libs
    +
    +ID: $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); mkid -fID $$unique
    +tags: tags-am
    +TAGS: tags
    +
    +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	set x; \
    +	here=`pwd`; \
    +	$(am__define_uniq_tagged_files); \
    +	shift; \
    +	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
    +	  test -n "$$unique" || unique=$$empty_fix; \
    +	  if test $$# -gt 0; then \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      "$$@" $$unique; \
    +	  else \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      $$unique; \
    +	  fi; \
    +	fi
    +ctags: ctags-am
    +
    +CTAGS: ctags
    +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); \
    +	test -z "$(CTAGS_ARGS)$$unique" \
    +	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
    +	     $$unique
    +
    +GTAGS:
    +	here=`$(am__cd) $(top_builddir) && pwd` \
    +	  && $(am__cd) $(top_srcdir) \
    +	  && gtags -i $(GTAGS_ARGS) "$$here"
    +cscopelist: cscopelist-am
    +
    +cscopelist-am: $(am__tagged_files)
    +	list='$(am__tagged_files)'; \
    +	case "$(srcdir)" in \
    +	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
    +	  *) sdir=$(subdir)/$(srcdir) ;; \
    +	esac; \
    +	for i in $$list; do \
    +	  if test -f "$$i"; then \
    +	    echo "$(subdir)/$$i"; \
    +	  else \
    +	    echo "$$sdir/$$i"; \
    +	  fi; \
    +	done >> $(top_builddir)/cscope.files
    +
    +distclean-tags:
    +	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
    +
    +distdir: $(DISTFILES)
    +	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	list='$(DISTFILES)'; \
    +	  dist_files=`for file in $$list; do echo $$file; done | \
    +	  sed -e "s|^$$srcdirstrip/||;t" \
    +	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
    +	case $$dist_files in \
    +	  */*) $(MKDIR_P) `echo "$$dist_files" | \
    +			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
    +			   sort -u` ;; \
    +	esac; \
    +	for file in $$dist_files; do \
    +	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
    +	  if test -d $$d/$$file; then \
    +	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
    +	    if test -d "$(distdir)/$$file"; then \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
    +	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
    +	  else \
    +	    test -f "$(distdir)/$$file" \
    +	    || cp -p $$d/$$file "$(distdir)/$$file" \
    +	    || exit 1; \
    +	  fi; \
    +	done
    +check-am: all-am
    +check: check-am
    +all-am: Makefile $(PROGRAMS)
    +installdirs:
    +install: install-am
    +install-exec: install-exec-am
    +install-data: install-data-am
    +uninstall: uninstall-am
    +
    +install-am: all-am
    +	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
    +
    +installcheck: installcheck-am
    +install-strip:
    +	if test -z '$(STRIP)'; then \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	      install; \
    +	else \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
    +	fi
    +mostlyclean-generic:
    +
    +clean-generic:
    +
    +distclean-generic:
    +	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
    +	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
    +
    +maintainer-clean-generic:
    +	@echo "This command is intended for maintainers to use"
    +	@echo "it deletes files that may require special tools to rebuild."
    +clean: clean-am
    +
    +clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \
    +	mostlyclean-am
    +
    +distclean: distclean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +distclean-am: clean-am distclean-compile distclean-generic \
    +	distclean-tags
    +
    +dvi: dvi-am
    +
    +dvi-am:
    +
    +html: html-am
    +
    +html-am:
    +
    +info: info-am
    +
    +info-am:
    +
    +install-data-am:
    +
    +install-dvi: install-dvi-am
    +
    +install-dvi-am:
    +
    +install-exec-am:
    +
    +install-html: install-html-am
    +
    +install-html-am:
    +
    +install-info: install-info-am
    +
    +install-info-am:
    +
    +install-man:
    +
    +install-pdf: install-pdf-am
    +
    +install-pdf-am:
    +
    +install-ps: install-ps-am
    +
    +install-ps-am:
    +
    +installcheck-am:
    +
    +maintainer-clean: maintainer-clean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +maintainer-clean-am: distclean-am maintainer-clean-generic
    +
    +mostlyclean: mostlyclean-am
    +
    +mostlyclean-am: mostlyclean-compile mostlyclean-generic \
    +	mostlyclean-libtool
    +
    +pdf: pdf-am
    +
    +pdf-am:
    +
    +ps: ps-am
    +
    +ps-am:
    +
    +uninstall-am:
    +
    +.MAKE: install-am install-strip
    +
    +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \
    +	clean-libtool clean-noinstPROGRAMS cscopelist-am ctags \
    +	ctags-am distclean distclean-compile distclean-generic \
    +	distclean-libtool distclean-tags distdir dvi dvi-am html \
    +	html-am info info-am install install-am install-data \
    +	install-data-am install-dvi install-dvi-am install-exec \
    +	install-exec-am install-html install-html-am install-info \
    +	install-info-am install-man install-pdf install-pdf-am \
    +	install-ps install-ps-am install-strip installcheck \
    +	installcheck-am installdirs maintainer-clean \
    +	maintainer-clean-generic mostlyclean mostlyclean-compile \
    +	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
    +	tags tags-am uninstall uninstall-am
    +
    +.PRECIOUS: Makefile
    +
    +
    +# Tell versions [3.59,3.63) of GNU make to not export all variables.
    +# Otherwise a system limit (for SysV at least) may be exceeded.
    +.NOEXPORT:
    diff --git a/contrib/expat/tests/benchmark/benchmark.c b/contrib/expat/tests/benchmark/benchmark.c
    index 0f0fd18c1d50..0c9155455a47 100644
    --- a/contrib/expat/tests/benchmark/benchmark.c
    +++ b/contrib/expat/tests/benchmark/benchmark.c
    @@ -1,17 +1,51 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     #include 
     #include 
     #include 
     #include 
     #include "expat.h"
     
    -#if defined(__amigaos__) && defined(__USE_INLINE__)
    -#include 
    +#ifdef XML_LARGE_SIZE
    +# define XML_FMT_INT_MOD "ll"
    +#else
    +# define XML_FMT_INT_MOD "l"
     #endif
     
    -#ifdef XML_LARGE_SIZE
    -#define XML_FMT_INT_MOD "ll"
    +#ifdef XML_UNICODE_WCHAR_T
    +# define XML_FMT_STR "ls"
     #else
    -#define XML_FMT_INT_MOD "l"
    +# define XML_FMT_STR "s"
     #endif
     
     static void
    @@ -88,7 +122,8 @@ int main (int argc, char *argv[])
           else
             parseBufferSize = bufferSize;
           if (!XML_Parse (parser, XMLBufPtr, parseBufferSize, isFinal)) {
    -        fprintf (stderr, "error '%s' at line %" XML_FMT_INT_MOD \
    +        fprintf (stderr,
    +                 "error '%" XML_FMT_STR "' at line %" XML_FMT_INT_MOD   \
                          "u character %" XML_FMT_INT_MOD "u\n",
                      XML_ErrorString (XML_GetErrorCode (parser)),
                      XML_GetCurrentLineNumber (parser),
    diff --git a/contrib/expat/tests/benchmark/benchmark.sln b/contrib/expat/tests/benchmark/benchmark.sln
    new file mode 100644
    index 000000000000..bc790bc0c59b
    --- /dev/null
    +++ b/contrib/expat/tests/benchmark/benchmark.sln
    @@ -0,0 +1,25 @@
    +
    +Microsoft Visual Studio Solution File, Format Version 12.00
    +# Visual Studio 2013
    +VisualStudioVersion = 12.0.40629.0
    +MinimumVisualStudioVersion = 10.0.40219.1
    +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "benchmark", "benchmark.vcxproj", "{FF89BA66-62C4-49EC-9189-1E7B603A1FD6}"
    +EndProject
    +Global
    +	GlobalSection(SolutionConfigurationPlatforms) = preSolution
    +		Debug|Win32 = Debug|Win32
    +		Release|Win32 = Release|Win32
    +		Template|Win32 = Template|Win32
    +	EndGlobalSection
    +	GlobalSection(ProjectConfigurationPlatforms) = postSolution
    +		{FF89BA66-62C4-49EC-9189-1E7B603A1FD6}.Debug|Win32.ActiveCfg = Debug|Win32
    +		{FF89BA66-62C4-49EC-9189-1E7B603A1FD6}.Debug|Win32.Build.0 = Debug|Win32
    +		{FF89BA66-62C4-49EC-9189-1E7B603A1FD6}.Release|Win32.ActiveCfg = Release|Win32
    +		{FF89BA66-62C4-49EC-9189-1E7B603A1FD6}.Release|Win32.Build.0 = Release|Win32
    +		{FF89BA66-62C4-49EC-9189-1E7B603A1FD6}.Template|Win32.ActiveCfg = Template|Win32
    +		{FF89BA66-62C4-49EC-9189-1E7B603A1FD6}.Template|Win32.Build.0 = Template|Win32
    +	EndGlobalSection
    +	GlobalSection(SolutionProperties) = preSolution
    +		HideSolutionNode = FALSE
    +	EndGlobalSection
    +EndGlobal
    diff --git a/contrib/expat/tests/chardata.c b/contrib/expat/tests/chardata.c
    index 012499bb8812..53e7333ff172 100644
    --- a/contrib/expat/tests/chardata.c
    +++ b/contrib/expat/tests/chardata.c
    @@ -1,11 +1,37 @@
    -/* Copyright (c) 1998-2003 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
     
    -   chardata.c
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #ifdef HAVE_EXPAT_CONFIG_H
    -#include 
    +# include 
     #endif
     #include "minicheck.h"
     
    @@ -34,25 +60,6 @@ CharData_Init(CharData *storage)
         storage->count = -1;
     }
     
    -void
    -CharData_AppendString(CharData *storage, const char *s)
    -{
    -    int maxchars = sizeof(storage->data) / sizeof(storage->data[0]);
    -    int len;
    -
    -    assert(s != NULL);
    -    len = strlen(s);
    -    if (storage->count < 0)
    -        storage->count = 0;
    -    if ((len + storage->count) > maxchars) {
    -        len = (maxchars - storage->count);
    -    }
    -    if (len + storage->count < (int)sizeof(storage->data)) {
    -        memcpy(storage->data + storage->count, s, len);
    -        storage->count += len;
    -    }
    -}
    -
     void
     CharData_AppendXMLChars(CharData *storage, const XML_Char *s, int len)
     {
    @@ -75,35 +82,6 @@ CharData_AppendXMLChars(CharData *storage, const XML_Char *s, int len)
         }
     }
     
    -int
    -CharData_CheckString(CharData *storage, const char *expected)
    -{
    -    char buffer[1280];
    -    int len;
    -    int count;
    -
    -    assert(storage != NULL);
    -    assert(expected != NULL);
    -    count = (storage->count < 0) ? 0 : storage->count;
    -    len = strlen(expected);
    -    if (len != count) {
    -        if (sizeof(XML_Char) == 1)
    -            sprintf(buffer, "wrong number of data characters:"
    -                    " got %d, expected %d:\n%s", count, len, storage->data);
    -        else
    -            sprintf(buffer,
    -                    "wrong number of data characters: got %d, expected %d",
    -                    count, len);
    -        fail(buffer);
    -        return 0;
    -    }
    -    if (memcmp(expected, storage->data, len) != 0) {
    -        fail("got bad data bytes");
    -        return 0;
    -    }
    -    return 1;
    -}
    -
     int
     CharData_CheckXMLChars(CharData *storage, const XML_Char *expected)
     {
    diff --git a/contrib/expat/tests/chardata.h b/contrib/expat/tests/chardata.h
    index e8dc4ce22c42..d3ad869d83ed 100644
    --- a/contrib/expat/tests/chardata.h
    +++ b/contrib/expat/tests/chardata.h
    @@ -1,7 +1,34 @@
    -/* chardata.h
    -
    -   Interface to some helper routines used to accumulate and check text
    +/* Interface to some helper routines used to accumulate and check text
        and attribute content.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #ifdef __cplusplus
    @@ -18,18 +45,14 @@ extern "C" {
     
     typedef struct {
         int count;                          /* # of chars, < 0 if not set */
    -    XML_Char data[1024];
    +    XML_Char data[2048];
     } CharData;
     
     
     void CharData_Init(CharData *storage);
     
    -void CharData_AppendString(CharData *storage, const char *s);
    -
     void CharData_AppendXMLChars(CharData *storage, const XML_Char *s, int len);
     
    -int CharData_CheckString(CharData *storage, const char *s);
    -
     int CharData_CheckXMLChars(CharData *storage, const XML_Char *s);
     
     
    diff --git a/contrib/expat/tests/memcheck.c b/contrib/expat/tests/memcheck.c
    new file mode 100644
    index 000000000000..23e9fdf43bc6
    --- /dev/null
    +++ b/contrib/expat/tests/memcheck.c
    @@ -0,0 +1,198 @@
    +/* Debug allocators for the Expat test suite
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
    +#include 
    +#include 
    +#include "memcheck.h"
    +
    +
    +/* Structures to keep track of what has been allocated.  Speed isn't a
    + * big issue for the tests this is required for, so we will use a
    + * doubly-linked list to make deletion easier.
    + */
    +
    +typedef struct allocation_entry {
    +    struct allocation_entry * next;
    +    struct allocation_entry * prev;
    +    void * allocation;
    +    size_t num_bytes;
    +} AllocationEntry;
    +
    +static AllocationEntry *alloc_head = NULL;
    +static AllocationEntry *alloc_tail = NULL;
    +
    +static AllocationEntry *find_allocation(void *ptr);
    +
    +
    +/* Allocate some memory and keep track of it. */
    +void *
    +tracking_malloc(size_t size)
    +{
    +    AllocationEntry *entry = malloc(sizeof(AllocationEntry));
    +
    +    if (entry == NULL) {
    +        printf("Allocator failure\n");
    +        return NULL;
    +    }
    +    entry->num_bytes = size;
    +    entry->allocation = malloc(size);
    +    if (entry->allocation == NULL) {
    +        free(entry);
    +        return NULL;
    +    }
    +    entry->next = NULL;
    +
    +    /* Add to the list of allocations */
    +    if (alloc_head == NULL) {
    +        entry->prev = NULL;
    +        alloc_head = alloc_tail = entry;
    +    } else {
    +        entry->prev = alloc_tail;
    +        alloc_tail->next = entry;
    +        alloc_tail = entry;
    +    }
    +
    +    return entry->allocation;
    +}
    +
    +static AllocationEntry *
    +find_allocation(void *ptr)
    +{
    +    AllocationEntry *entry;
    +
    +    for (entry = alloc_head; entry != NULL; entry = entry->next) {
    +        if (entry->allocation == ptr) {
    +            return entry;
    +        }
    +    }
    +    return NULL;
    +}
    +
    +/* Free some memory and remove the tracking for it */
    +void
    +tracking_free(void *ptr)
    +{
    +    AllocationEntry *entry;
    +
    +    if (ptr == NULL) {
    +        /* There won't be an entry for this */
    +        return;
    +    }
    +
    +    entry = find_allocation(ptr);
    +    if (entry != NULL) {
    +        /* This is the relevant allocation.  Unlink it */
    +        if (entry->prev != NULL)
    +            entry->prev->next = entry->next;
    +        else
    +            alloc_head = entry->next;
    +        if (entry->next != NULL)
    +            entry->next->prev = entry->prev;
    +        else
    +            alloc_tail = entry->next;
    +        free(entry);
    +    } else {
    +        printf("Attempting to free unallocated memory at %p\n", ptr);
    +    }
    +    free(ptr);
    +}
    +
    +/* Reallocate some memory and keep track of it */
    +void *
    +tracking_realloc(void *ptr, size_t size)
    +{
    +    AllocationEntry *entry;
    +
    +    if (ptr == NULL) {
    +        /* By definition, this is equivalent to malloc(size) */
    +        return tracking_malloc(size);
    +    }
    +    if (size == 0) {
    +        /* By definition, this is equivalent to free(ptr) */
    +        tracking_free(ptr);
    +        return NULL;
    +    }
    +
    +    /* Find the allocation entry for this memory */
    +    entry = find_allocation(ptr);
    +    if (entry == NULL) {
    +        printf("Attempting to realloc unallocated memory at %p\n", ptr);
    +        entry = malloc(sizeof(AllocationEntry));
    +        if (entry == NULL) {
    +            printf("Reallocator failure\n");
    +            return NULL;
    +        }
    +        entry->allocation = realloc(ptr, size);
    +        if (entry->allocation == NULL) {
    +            free(entry);
    +            return NULL;
    +        }
    +
    +        /* Add to the list of allocations */
    +        entry->next = NULL;
    +        if (alloc_head == NULL) {
    +            entry->prev = NULL;
    +            alloc_head = alloc_tail = entry;
    +        } else {
    +            entry->prev = alloc_tail;
    +            alloc_tail->next = entry;
    +            alloc_tail = entry;
    +        }
    +    } else {
    +        entry->allocation = realloc(ptr, size);
    +        if (entry->allocation == NULL) {
    +            /* Realloc semantics say the original is still allocated */
    +            entry->allocation = ptr;
    +            return NULL;
    +        }
    +    }
    +
    +    entry->num_bytes = size;
    +    return entry->allocation;
    +}
    +
    +int
    +tracking_report(void)
    +{
    +    AllocationEntry *entry;
    +
    +    if (alloc_head == NULL)
    +        return 1;
    +
    +    /* Otherwise we have allocations that haven't been freed */
    +    for (entry = alloc_head; entry != NULL; entry = entry->next)
    +    {
    +        printf("Allocated %lu bytes at %p\n",
    +                (long unsigned)entry->num_bytes, entry->allocation);
    +    }
    +    return 0;
    +}
    diff --git a/contrib/expat/tests/memcheck.h b/contrib/expat/tests/memcheck.h
    new file mode 100644
    index 000000000000..1cc4848280b4
    --- /dev/null
    +++ b/contrib/expat/tests/memcheck.h
    @@ -0,0 +1,57 @@
    +/* Interface to allocation functions that will track what has or has
    +   not been freed.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
    +#ifdef __cplusplus
    +extern "C" {
    +#endif
    +
    +#ifndef XML_MEMCHECK_H
    +#define XML_MEMCHECK_H 1
    +
    +/* Allocation declarations */
    +
    +void *tracking_malloc(size_t size);
    +void tracking_free(void *ptr);
    +void *tracking_realloc(void *ptr, size_t size);
    +
    +/* End-of-test check to see if unfreed allocations remain. Returns
    + * TRUE (1) if there is nothing, otherwise prints a report of the
    + * remaining allocations and returns FALSE (0).
    + */
    +int tracking_report(void);
    +
    +#endif /* XML_MEMCHECK_H */
    +
    +#ifdef __cplusplus
    +}
    +#endif
    diff --git a/contrib/expat/tests/minicheck.c b/contrib/expat/tests/minicheck.c
    index 5a1f5ed0e252..be1e37e761b7 100644
    --- a/contrib/expat/tests/minicheck.c
    +++ b/contrib/expat/tests/minicheck.c
    @@ -1,14 +1,44 @@
     /* Miniature re-implementation of the "check" library.
    - *
    - * This is intended to support just enough of check to run the Expat
    - * tests.  This interface is based entirely on the portion of the
    - * check library being used.
    - */
    +
    +   This is intended to support just enough of check to run the Expat
    +   tests.  This interface is based entirely on the portion of the
    +   check library being used.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
     
     #include 
     #include 
     #include 
     #include 
    +#include 
     
     #include "internal.h"  /* for UNUSED_P only */
     #include "minicheck.h"
    @@ -63,16 +93,39 @@ tcase_add_test(TCase *tc, tcase_test_function test)
             size_t new_size = sizeof(tcase_test_function) * nalloc;
             tcase_test_function *new_tests = realloc(tc->tests, new_size);
             assert(new_tests != NULL);
    -        if (new_tests != tc->tests) {
    -            free(tc->tests);
    -            tc->tests = new_tests;
    -        }
    +        tc->tests = new_tests;
             tc->allocated = nalloc;
         }
         tc->tests[tc->ntests] = test;
         tc->ntests++;
     }
     
    +static void
    +tcase_free(TCase *tc)
    +{
    +    if (! tc) {
    +        return;
    +    }
    +
    +    free(tc->tests);
    +    free(tc);
    +}
    +
    +static void
    +suite_free(Suite *suite)
    +{
    +    if (! suite) {
    +        return;
    +    }
    +
    +    while (suite->tests != NULL) {
    +        TCase *next = suite->tests->next_tcase;
    +        tcase_free(suite->tests);
    +        suite->tests = next;
    +    }
    +    free(suite);
    +}
    +
     SRunner *
     srunner_create(Suite *suite)
     {
    @@ -163,8 +216,10 @@ _fail_unless(int UNUSED_P(condition), const char *UNUSED_P(file), int UNUSED_P(l
            we have a failure, so there's no reason to be quiet about what
            it is.
         */
    -    if (msg != NULL)
    -        printf("%s", msg);
    +    if (msg != NULL) {
    +        const int has_newline = (msg[strlen(msg) - 1] == '\n');
    +        fprintf(stderr, "ERROR: %s%s", msg, has_newline ? "" : "\n");
    +    }
         longjmp(env, 1);
     }
     
    @@ -178,6 +233,10 @@ srunner_ntests_failed(SRunner *runner)
     void
     srunner_free(SRunner *runner)
     {
    -    free(runner->suite);
    +    if (! runner) {
    +        return;
    +    }
    +
    +    suite_free(runner->suite);
         free(runner);
     }
    diff --git a/contrib/expat/tests/minicheck.h b/contrib/expat/tests/minicheck.h
    index 9b06f51a88a7..a2f57ddcad05 100644
    --- a/contrib/expat/tests/minicheck.h
    +++ b/contrib/expat/tests/minicheck.h
    @@ -1,11 +1,40 @@
     /* Miniature re-implementation of the "check" library.
    - *
    - * This is intended to support just enough of check to run the Expat
    - * tests.  This interface is based entirely on the portion of the
    - * check library being used.
    - *
    - * This is *source* compatible, but not necessary *link* compatible.
    - */
    +
    +   This is intended to support just enough of check to run the Expat
    +   tests.  This interface is based entirely on the portion of the
    +   check library being used.
    +
    +   This is *source* compatible, but not necessary *link* compatible.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
     
     #ifdef __cplusplus
     extern "C" {
    @@ -26,11 +55,6 @@ extern "C" {
     #define __func__ __FUNCTION__
     #endif
     
    -/* ISO C90 does not support '__func__' predefined identifier */
    -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ < 199901)
    -# define __func__ "(unknown)"
    -#endif
    -
     #define START_TEST(testname) static void testname(void) { \
         _check_set_test_info(__func__, __FILE__, __LINE__);   \
         {
    diff --git a/contrib/expat/tests/runtests.c b/contrib/expat/tests/runtests.c
    index c0cdea997548..4f4d2687f113 100644
    --- a/contrib/expat/tests/runtests.c
    +++ b/contrib/expat/tests/runtests.c
    @@ -1,39 +1,116 @@
    -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/* Run the Expat test suite
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
     
    -   runtest.c : run the Expat test suite
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
    +#if defined(NDEBUG)
    +# undef NDEBUG  /* because test suite relies on assert(...) at the moment */
    +#endif
    +
     #ifdef HAVE_EXPAT_CONFIG_H
    -#include 
    +# include 
     #endif
     
     #include 
     #include 
     #include 
     #include 
    -#include 
     #include   /* ptrdiff_t */
    -#ifndef __cplusplus
    -# include 
    +#include 
    +#include 
    +
    +
    +#if defined(_WIN32) && defined(_MSC_VER) && (_MSC_VER < 1600)
    +    /* For vs2003/7.1 up to vs2008/9.0; _MSC_VER 1600 is vs2010/10.0 */
    + #if defined(_WIN64)
    +    typedef __int64 intptr_t;
    + #else
    +    typedef __int32 intptr_t;
    + #endif
    +    typedef unsigned __int64 uint64_t;
    +#else
    + #include  /* intptr_t uint64_t */
     #endif
     
    +
    +#if ! defined(__cplusplus)
    +# if defined(_MSC_VER) && (_MSC_VER <= 1700)
    +   /* for vs2012/11.0/1700 and earlier Visual Studio compilers */
    +#  define bool   int
    +#  define false  0
    +#  define true   1
    +# else
    +#  include 
    +# endif
    +#endif
    +
    +
     #include "expat.h"
     #include "chardata.h"
    +#include "structdata.h"
     #include "internal.h"  /* for UNUSED_P only */
     #include "minicheck.h"
    -
    -#if defined(__amigaos__) && defined(__USE_INLINE__)
    -#include 
    -#endif
    +#include "memcheck.h"
    +#include "siphash.h"
    +#include "ascii.h" /* for ASCII_xxx */
     
     #ifdef XML_LARGE_SIZE
    -#define XML_FMT_INT_MOD "ll"
    +# define XML_FMT_INT_MOD "ll"
     #else
    -#define XML_FMT_INT_MOD "l"
    +# define XML_FMT_INT_MOD "l"
     #endif
     
    -static XML_Parser parser;
    +#ifdef XML_UNICODE_WCHAR_T
    +# define XML_FMT_CHAR "lc"
    +# define XML_FMT_STR "ls"
    +# include 
    +# define xcstrlen(s) wcslen(s)
    +# define xcstrcmp(s, t) wcscmp((s), (t))
    +# define xcstrncmp(s, t, n) wcsncmp((s), (t), (n))
    +# define XCS(s) _XCS(s)
    +# define _XCS(s) L ## s
    +#else
    +# ifdef XML_UNICODE
    +#  error "No support for UTF-16 character without wchar_t in tests"
    +# else
    +#  define XML_FMT_CHAR "c"
    +#  define XML_FMT_STR "s"
    +#  define xcstrlen(s) strlen(s)
    +#  define xcstrcmp(s, t) strcmp((s), (t))
    +#  define xcstrncmp(s, t, n) strncmp((s), (t), (n))
    +#  define XCS(s) s
    +# endif /* XML_UNICODE */
    +#endif /* XML_UNICODE_WCHAR_T */
    +
    +
    +static XML_Parser parser = NULL;
     
     
     static void
    @@ -47,8 +124,10 @@ basic_setup(void)
     static void
     basic_teardown(void)
     {
    -    if (parser != NULL)
    +    if (parser != NULL) {
             XML_ParserFree(parser);
    +        parser = NULL;
    +    }
     }
     
     /* Generate a failure using the parser state to create an error message;
    @@ -61,7 +140,8 @@ _xml_failure(XML_Parser parser, const char *file, int line)
         char buffer[1024];
         enum XML_Error err = XML_GetErrorCode(parser);
         sprintf(buffer,
    -            "    %d: %s (line %" XML_FMT_INT_MOD "u, offset %"\
    +            "    %d: %" XML_FMT_STR " (line %"
    +                XML_FMT_INT_MOD "u, offset %"
                     XML_FMT_INT_MOD "u)\n    reported from %s, line %d\n",
                 err,
                 XML_ErrorString(err),
    @@ -98,7 +178,7 @@ static void
     _expect_failure(const char *text, enum XML_Error errorCode, const char *errorMessage,
                     const char *file, int lineno)
     {
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_OK)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_OK)
             /* Hackish use of _fail_unless() macro, but let's us report
                the right filename and line number. */
             _fail_unless(0, file, lineno, errorMessage);
    @@ -113,6 +193,34 @@ _expect_failure(const char *text, enum XML_Error errorCode, const char *errorMes
     /* Dummy handlers for when we need to set a handler to tickle a bug,
        but it doesn't need to do anything.
     */
    +static unsigned long dummy_handler_flags = 0;
    +
    +#define DUMMY_START_DOCTYPE_HANDLER_FLAG        (1UL << 0)
    +#define DUMMY_END_DOCTYPE_HANDLER_FLAG          (1UL << 1)
    +#define DUMMY_ENTITY_DECL_HANDLER_FLAG          (1UL << 2)
    +#define DUMMY_NOTATION_DECL_HANDLER_FLAG        (1UL << 3)
    +#define DUMMY_ELEMENT_DECL_HANDLER_FLAG         (1UL << 4)
    +#define DUMMY_ATTLIST_DECL_HANDLER_FLAG         (1UL << 5)
    +#define DUMMY_COMMENT_HANDLER_FLAG              (1UL << 6)
    +#define DUMMY_PI_HANDLER_FLAG                   (1UL << 7)
    +#define DUMMY_START_ELEMENT_HANDLER_FLAG        (1UL << 8)
    +#define DUMMY_START_CDATA_HANDLER_FLAG          (1UL << 9)
    +#define DUMMY_END_CDATA_HANDLER_FLAG            (1UL << 10)
    +#define DUMMY_UNPARSED_ENTITY_DECL_HANDLER_FLAG (1UL << 11)
    +#define DUMMY_START_NS_DECL_HANDLER_FLAG        (1UL << 12)
    +#define DUMMY_END_NS_DECL_HANDLER_FLAG          (1UL << 13)
    +#define DUMMY_START_DOCTYPE_DECL_HANDLER_FLAG   (1UL << 14)
    +#define DUMMY_END_DOCTYPE_DECL_HANDLER_FLAG     (1UL << 15)
    +#define DUMMY_SKIP_HANDLER_FLAG                 (1UL << 16)
    +#define DUMMY_DEFAULT_HANDLER_FLAG              (1UL << 17)
    +
    +
    +static void XMLCALL
    +dummy_xdecl_handler(void *UNUSED_P(userData),
    +                    const XML_Char *UNUSED_P(version),
    +                    const XML_Char *UNUSED_P(encoding),
    +                    int UNUSED_P(standalone))
    +{}
     
     static void XMLCALL
     dummy_start_doctype_handler(void           *UNUSED_P(userData),
    @@ -120,11 +228,15 @@ dummy_start_doctype_handler(void           *UNUSED_P(userData),
                                 const XML_Char *UNUSED_P(sysid),
                                 const XML_Char *UNUSED_P(pubid),
                                 int            UNUSED_P(has_internal_subset))
    -{}
    +{
    +    dummy_handler_flags |= DUMMY_START_DOCTYPE_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_end_doctype_handler(void *UNUSED_P(userData))
    -{}
    +{
    +    dummy_handler_flags |= DUMMY_END_DOCTYPE_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_entity_decl_handler(void           *UNUSED_P(userData),
    @@ -136,7 +248,9 @@ dummy_entity_decl_handler(void           *UNUSED_P(userData),
                               const XML_Char *UNUSED_P(systemId),
                               const XML_Char *UNUSED_P(publicId),
                               const XML_Char *UNUSED_P(notationName))
    -{}
    +{
    +    dummy_handler_flags |= DUMMY_ENTITY_DECL_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_notation_decl_handler(void *UNUSED_P(userData),
    @@ -144,13 +258,22 @@ dummy_notation_decl_handler(void *UNUSED_P(userData),
                                 const XML_Char *UNUSED_P(base),
                                 const XML_Char *UNUSED_P(systemId),
                                 const XML_Char *UNUSED_P(publicId))
    -{}
    +{
    +    dummy_handler_flags |= DUMMY_NOTATION_DECL_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_element_decl_handler(void *UNUSED_P(userData),
                                const XML_Char *UNUSED_P(name),
    -                           XML_Content *UNUSED_P(model))
    -{}
    +                           XML_Content *model)
    +{
    +    /* The content model must be freed by the handler.  Unfortunately
    +     * we cannot pass the parser as the userData because this is used
    +     * with other handlers that require other userData.
    +     */
    +    XML_FreeContentModel(parser, model);
    +    dummy_handler_flags |= DUMMY_ELEMENT_DECL_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_attlist_decl_handler(void           *UNUSED_P(userData),
    @@ -159,21 +282,185 @@ dummy_attlist_decl_handler(void           *UNUSED_P(userData),
                                const XML_Char *UNUSED_P(att_type),
                                const XML_Char *UNUSED_P(dflt),
                                int            UNUSED_P(isrequired))
    -{}
    +{
    +    dummy_handler_flags |= DUMMY_ATTLIST_DECL_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_comment_handler(void *UNUSED_P(userData), const XML_Char *UNUSED_P(data))
    -{}
    +{
    +    dummy_handler_flags |= DUMMY_COMMENT_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_pi_handler(void *UNUSED_P(userData), const XML_Char *UNUSED_P(target), const XML_Char *UNUSED_P(data))
    -{}
    +{
    +    dummy_handler_flags |= DUMMY_PI_HANDLER_FLAG;
    +}
     
     static void XMLCALL
     dummy_start_element(void *UNUSED_P(userData),
                         const XML_Char *UNUSED_P(name), const XML_Char **UNUSED_P(atts))
    +{
    +    dummy_handler_flags |= DUMMY_START_ELEMENT_HANDLER_FLAG;
    +}
    +
    +static void XMLCALL
    +dummy_end_element(void *UNUSED_P(userData), const XML_Char *UNUSED_P(name))
     {}
     
    +static void XMLCALL
    +dummy_start_cdata_handler(void *UNUSED_P(userData))
    +{
    +    dummy_handler_flags |= DUMMY_START_CDATA_HANDLER_FLAG;
    +}
    +
    +static void XMLCALL
    +dummy_end_cdata_handler(void *UNUSED_P(userData))
    +{
    +    dummy_handler_flags |= DUMMY_END_CDATA_HANDLER_FLAG;
    +}
    +
    +static void XMLCALL
    +dummy_cdata_handler(void *UNUSED_P(userData),
    +                    const XML_Char *UNUSED_P(s),
    +                    int UNUSED_P(len))
    +{}
    +
    +static void XMLCALL
    +dummy_start_namespace_decl_handler(void *UNUSED_P(userData),
    +                                   const XML_Char *UNUSED_P(prefix),
    +                                   const XML_Char *UNUSED_P(uri))
    +{
    +    dummy_handler_flags |= DUMMY_START_NS_DECL_HANDLER_FLAG;
    +}
    +
    +static void XMLCALL
    +dummy_end_namespace_decl_handler(void *UNUSED_P(userData),
    +                                 const XML_Char *UNUSED_P(prefix))
    +{
    +    dummy_handler_flags |= DUMMY_END_NS_DECL_HANDLER_FLAG;
    +}
    +
    +/* This handler is obsolete, but while the code exists we should
    + * ensure that dealing with the handler is covered by tests.
    + */
    +static void XMLCALL
    +dummy_unparsed_entity_decl_handler(void *UNUSED_P(userData),
    +                                   const XML_Char *UNUSED_P(entityName),
    +                                   const XML_Char *UNUSED_P(base),
    +                                   const XML_Char *UNUSED_P(systemId),
    +                                   const XML_Char *UNUSED_P(publicId),
    +                                   const XML_Char *UNUSED_P(notationName))
    +{
    +    dummy_handler_flags |= DUMMY_UNPARSED_ENTITY_DECL_HANDLER_FLAG;
    +}
    +
    +static void XMLCALL
    +dummy_default_handler(void *UNUSED_P(userData),
    +                      const XML_Char *UNUSED_P(s),
    +                      int UNUSED_P(len))
    +{}
    +
    +static void XMLCALL
    +dummy_start_doctype_decl_handler(void *UNUSED_P(userData),
    +                                 const XML_Char *UNUSED_P(doctypeName),
    +                                 const XML_Char *UNUSED_P(sysid),
    +                                 const XML_Char *UNUSED_P(pubid),
    +                                 int UNUSED_P(has_internal_subset))
    +{
    +    dummy_handler_flags |= DUMMY_START_DOCTYPE_DECL_HANDLER_FLAG;
    +}
    +
    +static void XMLCALL
    +dummy_end_doctype_decl_handler(void *UNUSED_P(userData))
    +{
    +    dummy_handler_flags |= DUMMY_END_DOCTYPE_DECL_HANDLER_FLAG;
    +}
    +
    +static void XMLCALL
    +dummy_skip_handler(void *UNUSED_P(userData),
    +                   const XML_Char *UNUSED_P(entityName),
    +                   int UNUSED_P(is_parameter_entity))
    +{
    +    dummy_handler_flags |= DUMMY_SKIP_HANDLER_FLAG;
    +}
    +
    +/* Useful external entity handler */
    +typedef struct ExtOption {
    +    const XML_Char *system_id;
    +    const char *parse_text;
    +} ExtOption;
    +
    +static int XMLCALL
    +external_entity_optioner(XML_Parser parser,
    +                         const XML_Char *context,
    +                         const XML_Char *UNUSED_P(base),
    +                         const XML_Char *systemId,
    +                         const XML_Char *UNUSED_P(publicId))
    +{
    +    ExtOption *options = (ExtOption *)XML_GetUserData(parser);
    +    XML_Parser ext_parser;
    +
    +    while (options->parse_text != NULL) {
    +        if (!xcstrcmp(systemId, options->system_id)) {
    +            enum XML_Status rc;
    +            ext_parser =
    +                XML_ExternalEntityParserCreate(parser, context, NULL);
    +            if (ext_parser == NULL)
    +                return XML_STATUS_ERROR;
    +            rc = _XML_Parse_SINGLE_BYTES(ext_parser, options->parse_text,
    +                                         (int)strlen(options->parse_text),
    +                                         XML_TRUE);
    +            XML_ParserFree(ext_parser);
    +            return rc;
    +        }
    +        options++;
    +    }
    +    fail("No suitable option found");
    +    return XML_STATUS_ERROR;
    +}
    +
    +/*
    + * Parameter entity evaluation support.
    + */
    +#define ENTITY_MATCH_FAIL      (-1)
    +#define ENTITY_MATCH_NOT_FOUND  (0)
    +#define ENTITY_MATCH_SUCCESS    (1)
    +static const XML_Char *entity_name_to_match = NULL;
    +static const XML_Char *entity_value_to_match = NULL;
    +static int entity_match_flag = ENTITY_MATCH_NOT_FOUND;
    +
    +static void XMLCALL
    +param_entity_match_handler(void           *UNUSED_P(userData),
    +                           const XML_Char *entityName,
    +                           int            is_parameter_entity,
    +                           const XML_Char *value,
    +                           int            value_length,
    +                           const XML_Char *UNUSED_P(base),
    +                           const XML_Char *UNUSED_P(systemId),
    +                           const XML_Char *UNUSED_P(publicId),
    +                           const XML_Char *UNUSED_P(notationName))
    +{
    +    if (!is_parameter_entity ||
    +        entity_name_to_match == NULL ||
    +        entity_value_to_match == NULL) {
    +        return;
    +    }
    +    if (!xcstrcmp(entityName, entity_name_to_match)) {
    +        /* The cast here is safe because we control the horizontal and
    +         * the vertical, and we therefore know our strings are never
    +         * going to overflow an int.
    +         */
    +        if (value_length != (int)xcstrlen(entity_value_to_match) ||
    +            xcstrncmp(value, entity_value_to_match, value_length)) {
    +            entity_match_flag = ENTITY_MATCH_FAIL;
    +        } else {
    +            entity_match_flag = ENTITY_MATCH_SUCCESS;
    +        }
    +    }
    +    /* Else leave the match flag alone */
    +}
     
     /*
      * Character & encoding tests.
    @@ -201,12 +488,50 @@ START_TEST(test_u0000_char)
     }
     END_TEST
     
    +START_TEST(test_siphash_self)
    +{
    +    if (! sip24_valid())
    +        fail("SipHash self-test failed");
    +}
    +END_TEST
    +
    +START_TEST(test_siphash_spec)
    +{
    +    /* https://131002.net/siphash/siphash.pdf (page 19, "Test values") */
    +    const char message[] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09"
    +            "\x0a\x0b\x0c\x0d\x0e";
    +    const size_t len = sizeof(message) - 1;
    +    const uint64_t expected = _SIP_ULL(0xa129ca61U, 0x49be45e5U);
    +    struct siphash state;
    +    struct sipkey key;
    +
    +    sip_tokey(&key,
    +            "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09"
    +            "\x0a\x0b\x0c\x0d\x0e\x0f");
    +    sip24_init(&state, &key);
    +
    +    /* Cover spread across calls */
    +    sip24_update(&state, message, 4);
    +    sip24_update(&state, message + 4, len - 4);
    +
    +    /* Cover null length */
    +    sip24_update(&state, message, 0);
    +
    +    if (sip24_final(&state) != expected)
    +        fail("sip24_final failed spec test\n");
    +
    +    /* Cover wrapper */
    +    if (siphash24(message, len, &key) != expected)
    +        fail("siphash24 failed spec test\n");
    +}
    +END_TEST
    +
     START_TEST(test_bom_utf8)
     {
         /* This test is really just making sure we don't core on a UTF-8 BOM. */
         const char *text = "\357\273\277";
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -229,6 +554,16 @@ START_TEST(test_bom_utf16_le)
     }
     END_TEST
     
    +/* Parse whole buffer at once to exercise a different code path */
    +START_TEST(test_nobom_utf16_le)
    +{
    +    char text[] = " \0<\0e\0/\0>\0";
    +
    +    if (XML_Parse(parser, text, sizeof(text)-1, XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
     static void XMLCALL
     accumulate_characters(void *userData, const XML_Char *s, int len)
     {
    @@ -240,15 +575,21 @@ accumulate_attribute(void *userData, const XML_Char *UNUSED_P(name),
                          const XML_Char **atts)
     {
         CharData *storage = (CharData *)userData;
    -    if (storage->count < 0 && atts != NULL && atts[0] != NULL) {
    +
    +    /* Check there are attributes to deal with */
    +    if (atts == NULL)
    +        return;
    +
    +    while (storage->count < 0 && atts[0] != NULL) {
             /* "accumulate" the value of the first attribute we see */
             CharData_AppendXMLChars(storage, atts[1], -1);
    +        atts += 2;
         }
     }
     
     
     static void
    -_run_character_check(const XML_Char *text, const XML_Char *expected,
    +_run_character_check(const char *text, const XML_Char *expected,
                          const char *file, int line)
     {
         CharData storage;
    @@ -256,7 +597,7 @@ _run_character_check(const XML_Char *text, const XML_Char *expected,
         CharData_Init(&storage);
         XML_SetUserData(parser, &storage);
         XML_SetCharacterDataHandler(parser, accumulate_characters);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             _xml_failure(parser, file, line);
         CharData_CheckXMLChars(&storage, expected);
     }
    @@ -265,7 +606,7 @@ _run_character_check(const XML_Char *text, const XML_Char *expected,
             _run_character_check(text, expected, __FILE__, __LINE__)
     
     static void
    -_run_attribute_check(const XML_Char *text, const XML_Char *expected,
    +_run_attribute_check(const char *text, const XML_Char *expected,
                          const char *file, int line)
     {
         CharData storage;
    @@ -273,7 +614,7 @@ _run_attribute_check(const XML_Char *text, const XML_Char *expected,
         CharData_Init(&storage);
         XML_SetUserData(parser, &storage);
         XML_SetStartElementHandler(parser, accumulate_attribute);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             _xml_failure(parser, file, line);
         CharData_CheckXMLChars(&storage, expected);
     }
    @@ -281,14 +622,54 @@ _run_attribute_check(const XML_Char *text, const XML_Char *expected,
     #define run_attribute_check(text, expected) \
             _run_attribute_check(text, expected, __FILE__, __LINE__)
     
    +typedef struct ExtTest {
    +    const char *parse_text;
    +    const XML_Char *encoding;
    +    CharData *storage;
    +} ExtTest;
    +
    +static void XMLCALL
    +ext_accumulate_characters(void *userData, const XML_Char *s, int len)
    +{
    +    ExtTest *test_data = (ExtTest *)userData;
    +    accumulate_characters(test_data->storage, s, len);
    +}
    +
    +static void
    +_run_ext_character_check(const char *text,
    +                         ExtTest *test_data,
    +                         const XML_Char *expected,
    +                         const char *file, int line)
    +{
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    test_data->storage = &storage;
    +    XML_SetUserData(parser, test_data);
    +    XML_SetCharacterDataHandler(parser, ext_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        _xml_failure(parser, file, line);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +
    +#define run_ext_character_check(text, test_data, expected)               \
    +    _run_ext_character_check(text, test_data, expected, __FILE__, __LINE__)
    +
     /* Regression test for SF bug #491986. */
     START_TEST(test_danish_latin1)
     {
         const char *text =
             "\n"
             "J\xF8rgen \xE6\xF8\xE5\xC6\xD8\xC5";
    -    run_character_check(text,
    -             "J\xC3\xB8rgen \xC3\xA6\xC3\xB8\xC3\xA5\xC3\x86\xC3\x98\xC3\x85");
    +#ifdef XML_UNICODE
    +    const XML_Char *expected =
    +        XCS("J\x00f8rgen \x00e6\x00f8\x00e5\x00c6\x00d8\x00c5");
    +#else
    +    const XML_Char *expected =
    +        XCS("J\xC3\xB8rgen \xC3\xA6\xC3\xB8\xC3\xA5\xC3\x86\xC3\x98\xC3\x85");
    +#endif
    +    run_character_check(text, expected);
     }
     END_TEST
     
    @@ -299,8 +680,14 @@ START_TEST(test_french_charref_hexidecimal)
         const char *text =
             "\n"
             "éèàçêÈ";
    -    run_character_check(text,
    -                        "\xC3\xA9\xC3\xA8\xC3\xA0\xC3\xA7\xC3\xAA\xC3\x88");
    +#ifdef XML_UNICODE
    +    const XML_Char *expected =
    +        XCS("\x00e9\x00e8\x00e0\x00e7\x00ea\x00c8");
    +#else
    +    const XML_Char *expected =
    +        XCS("\xC3\xA9\xC3\xA8\xC3\xA0\xC3\xA7\xC3\xAA\xC3\x88");
    +#endif
    +    run_character_check(text, expected);
     }
     END_TEST
     
    @@ -309,8 +696,14 @@ START_TEST(test_french_charref_decimal)
         const char *text =
             "\n"
             "éèàçêÈ";
    -    run_character_check(text,
    -                        "\xC3\xA9\xC3\xA8\xC3\xA0\xC3\xA7\xC3\xAA\xC3\x88");
    +#ifdef XML_UNICODE
    +    const XML_Char *expected =
    +        XCS("\x00e9\x00e8\x00e0\x00e7\x00ea\x00c8");
    +#else
    +    const XML_Char *expected =
    +        XCS("\xC3\xA9\xC3\xA8\xC3\xA0\xC3\xA7\xC3\xAA\xC3\x88");
    +#endif
    +    run_character_check(text, expected);
     }
     END_TEST
     
    @@ -319,8 +712,14 @@ START_TEST(test_french_latin1)
         const char *text =
             "\n"
             "\xE9\xE8\xE0\xE7\xEa\xC8";
    -    run_character_check(text,
    -                        "\xC3\xA9\xC3\xA8\xC3\xA0\xC3\xA7\xC3\xAA\xC3\x88");
    +#ifdef XML_UNICODE
    +    const XML_Char *expected =
    +        XCS("\x00e9\x00e8\x00e0\x00e7\x00ea\x00c8");
    +#else
    +    const XML_Char *expected =
    +        XCS("\xC3\xA9\xC3\xA8\xC3\xA0\xC3\xA7\xC3\xAA\xC3\x88");
    +#endif
    +    run_character_check(text, expected);
     }
     END_TEST
     
    @@ -329,7 +728,12 @@ START_TEST(test_french_utf8)
         const char *text =
             "\n"
             "\xC3\xA9";
    -    run_character_check(text, "\xC3\xA9");
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00e9");
    +#else
    +    const XML_Char *expected = XCS("\xC3\xA9");
    +#endif
    +    run_character_check(text, expected);
     }
     END_TEST
     
    @@ -341,7 +745,12 @@ END_TEST
     START_TEST(test_utf8_false_rejection)
     {
         const char *text = "\xEF\xBA\xBF";
    -    run_character_check(text, "\xEF\xBA\xBF");
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\xfebf");
    +#else
    +    const XML_Char *expected = XCS("\xEF\xBA\xBF");
    +#endif
    +    run_character_check(text, expected);
     }
     END_TEST
     
    @@ -357,7 +766,7 @@ START_TEST(test_illegal_utf8)
     
         for (i = 128; i <= 255; ++i) {
             sprintf(text, "%ccd", i);
    -        if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_OK) {
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_OK) {
                 sprintf(text,
                         "expected token error for '%c' (ordinal %d) in UTF-8 text",
                         i, i);
    @@ -411,15 +820,17 @@ START_TEST(test_utf8_auto_align)
             const char * const fromLimInitially = fromLim;
             ptrdiff_t actualMovementInChars;
     
    -        align_limit_to_full_utf8_characters(cases[i].input, &fromLim);
    +        _INTERNAL_trim_to_complete_utf8_characters(cases[i].input, &fromLim);
     
             actualMovementInChars = (fromLim - fromLimInitially);
             if (actualMovementInChars != cases[i].expectedMovementInChars) {
                 size_t j = 0;
                 success = false;
    -            printf("[-] UTF-8 case %2lu: Expected movement by %2ld chars"
    -                    ", actually moved by %2ld chars: \"",
    -                    i + 1, cases[i].expectedMovementInChars, actualMovementInChars);
    +            printf("[-] UTF-8 case %2u: Expected movement by %2d chars"
    +                    ", actually moved by %2d chars: \"",
    +                    (unsigned)(i + 1),
    +                    (int)cases[i].expectedMovementInChars,
    +                    (int)actualMovementInChars);
                 for (; j < strlen(cases[i].input); j++) {
                     printf("\\x%02x", (unsigned char)cases[i].input[j]);
                 }
    @@ -436,18 +847,31 @@ END_TEST
     START_TEST(test_utf16)
     {
         /* 
    -       some text
    -    */
    +     *  some {A} text
    +     *
    +     * where {A} is U+FF21, FULLWIDTH LATIN CAPITAL LETTER A
    +     */
         char text[] =
             "\000<\000?\000x\000m\000\154\000 \000v\000e\000r\000s\000i\000o"
             "\000n\000=\000'\0001\000.\000\060\000'\000 \000e\000n\000c\000o"
             "\000d\000i\000n\000g\000=\000'\000U\000T\000F\000-\0001\000\066"
             "\000'\000?\000>\000\n"
    -        "\000<\000d\000o\000c\000 \000a\000=\000'\0001\0002\0003\000'"
    -        "\000>\000s\000o\000m\000e\000 \000t\000e\000x\000t\000<\000/"
    -        "\000d\000o\000c\000>";
    +        "\000<\000d\000o\000c\000 \000a\000=\000'\0001\0002\0003\000'\000>"
    +        "\000s\000o\000m\000e\000 \xff\x21\000 \000t\000e\000x\000t\000"
    +        "<\000/\000d\000o\000c\000>";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("some \xff21 text");
    +#else
    +    const XML_Char *expected = XCS("some \357\274\241 text");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
         if (_XML_Parse_SINGLE_BYTES(parser, text, sizeof(text)-1, XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
     }
     END_TEST
     
    @@ -474,6 +898,34 @@ START_TEST(test_utf16_le_epilog_newline)
     }
     END_TEST
     
    +/* Test that an outright lie in the encoding is faulted */
    +START_TEST(test_not_utf16)
    +{
    +    const char *text =
    +        ""
    +        "Hi";
    +
    +    /* Use a handler to provoke the appropriate code paths */
    +    XML_SetXmlDeclHandler(parser, dummy_xdecl_handler);
    +    expect_failure(text,
    +                   XML_ERROR_INCORRECT_ENCODING,
    +                   "UTF-16 declared in UTF-8 not faulted");
    +}
    +END_TEST
    +
    +/* Test that an unknown encoding is rejected */
    +START_TEST(test_bad_encoding)
    +{
    +    const char *text = "Hi";
    +
    +    if (!XML_SetEncoding(parser, XCS("unknown-encoding")))
    +        fail("XML_SetEncoding failed");
    +    expect_failure(text,
    +                   XML_ERROR_UNKNOWN_ENCODING,
    +                   "Unknown encoding not faulted");
    +}
    +END_TEST
    +
     /* Regression test for SF bug #481609, #774028. */
     START_TEST(test_latin1_umlauts)
     {
    @@ -481,13 +933,167 @@ START_TEST(test_latin1_umlauts)
             "\n"
             "\xE4 \xF6 \xFC ä ö ü ä ö ü >";
    -    const char *utf8 =
    -        "\xC3\xA4 \xC3\xB6 \xC3\xBC "
    -        "\xC3\xA4 \xC3\xB6 \xC3\xBC "
    -        "\xC3\xA4 \xC3\xB6 \xC3\xBC >";
    -    run_character_check(text, utf8);
    +#ifdef XML_UNICODE
    +    /* Expected results in UTF-16 */
    +    const XML_Char *expected =
    +        XCS("\x00e4 \x00f6 \x00fc ")
    +        XCS("\x00e4 \x00f6 \x00fc ")
    +        XCS("\x00e4 \x00f6 \x00fc >");
    +#else
    +    /* Expected results in UTF-8 */
    +    const XML_Char *expected =
    +        XCS("\xC3\xA4 \xC3\xB6 \xC3\xBC ")
    +        XCS("\xC3\xA4 \xC3\xB6 \xC3\xBC ")
    +        XCS("\xC3\xA4 \xC3\xB6 \xC3\xBC >");
    +#endif
    +
    +    run_character_check(text, expected);
         XML_ParserReset(parser, NULL);
    -    run_attribute_check(text, utf8);
    +    run_attribute_check(text, expected);
    +    /* Repeat with a default handler */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandler(parser, dummy_default_handler);
    +    run_character_check(text, expected);
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandler(parser, dummy_default_handler);
    +    run_attribute_check(text, expected);
    +}
    +END_TEST
    +
    +/* Test that an element name with a 4-byte UTF-8 character is rejected */
    +START_TEST(test_long_utf8_character)
    +{
    +    const char *text =
    +        "\n"
    +        /* 0xf0 0x90 0x80 0x80 = U+10000, the first Linear B character */
    +        "";
    +    expect_failure(text,
    +                   XML_ERROR_INVALID_TOKEN,
    +                   "4-byte UTF-8 character in element name not faulted");
    +}
    +END_TEST
    +
    +/* Test that a long latin-1 attribute (too long to convert in one go)
    + * is correctly converted
    + */
    +START_TEST(test_long_latin1_attribute)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected =
    +        /* 64 characters per line */
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNO")
    +        XCS("\x00e4");
    +#else
    +    const XML_Char *expected =
    +        /* 64 characters per line */
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNO")
    +        XCS("\xc3\xa4");
    +#endif
    +
    +    run_attribute_check(text, expected);
    +}
    +END_TEST
    +
    +
    +/* Test that a long ASCII attribute (too long to convert in one go)
    + * is correctly converted
    + */
    +START_TEST(test_long_ascii_attribute)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +    const XML_Char *expected =
    +        /* 64 characters per line */
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("01234");
    +
    +    run_attribute_check(text, expected);
     }
     END_TEST
     
    @@ -500,7 +1106,7 @@ START_TEST(test_line_number_after_parse)
             "\n";
         XML_Size lineno;
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_FALSE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_FALSE) == XML_STATUS_ERROR)
             xml_failure(parser);
         lineno = XML_GetCurrentLineNumber(parser);
         if (lineno != 4) {
    @@ -518,7 +1124,7 @@ START_TEST(test_column_number_after_parse)
         const char *text = "";
         XML_Size colno;
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_FALSE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_FALSE) == XML_STATUS_ERROR)
             xml_failure(parser);
         colno = XML_GetCurrentColumnNumber(parser);
         if (colno != 11) {
    @@ -530,33 +1136,27 @@ START_TEST(test_column_number_after_parse)
     }
     END_TEST
     
    +#define STRUCT_START_TAG 0
    +#define STRUCT_END_TAG 1
     static void XMLCALL
     start_element_event_handler2(void *userData, const XML_Char *name,
     			     const XML_Char **UNUSED_P(attr))
     {
    -    CharData *storage = (CharData *) userData;
    -    char buffer[100];
    -
    -    sprintf(buffer,
    -        "<%s> at col:%" XML_FMT_INT_MOD "u line:%"\
    -            XML_FMT_INT_MOD "u\n", name,
    -	    XML_GetCurrentColumnNumber(parser),
    -	    XML_GetCurrentLineNumber(parser));
    -    CharData_AppendString(storage, buffer);
    +    StructData *storage = (StructData *) userData;
    +    StructData_AddItem(storage, name,
    +                       XML_GetCurrentColumnNumber(parser),
    +                       XML_GetCurrentLineNumber(parser),
    +                       STRUCT_START_TAG);
     }
     
     static void XMLCALL
     end_element_event_handler2(void *userData, const XML_Char *name)
     {
    -    CharData *storage = (CharData *) userData;
    -    char buffer[100];
    -
    -    sprintf(buffer,
    -        " at col:%" XML_FMT_INT_MOD "u line:%"\
    -            XML_FMT_INT_MOD "u\n", name,
    -	    XML_GetCurrentColumnNumber(parser),
    -	    XML_GetCurrentLineNumber(parser));
    -    CharData_AppendString(storage, buffer);
    +    StructData *storage = (StructData *) userData;
    +    StructData_AddItem(storage, name,
    +                       XML_GetCurrentColumnNumber(parser),
    +                       XML_GetCurrentLineNumber(parser),
    +                       STRUCT_END_TAG);
     }
     
     /* Regression test #3 for SF bug #653180. */
    @@ -571,27 +1171,30 @@ START_TEST(test_line_and_column_numbers_inside_handlers)
             "    \n"
             "  \n"
             "";
    -    const char *expected =
    -        " at col:0 line:1\n"
    -        " at col:2 line:2\n"
    -        " at col:4 line:3\n"
    -        " at col:8 line:3\n"
    -        " at col:2 line:4\n"
    -        " at col:2 line:5\n"
    -        " at col:4 line:6\n"
    -        " at col:8 line:6\n"
    -        " at col:2 line:7\n"
    -        " at col:0 line:8\n";
    -    CharData storage;
    +    const StructDataEntry expected[] = {
    +        { XCS("a"), 0, 1, STRUCT_START_TAG },
    +        { XCS("b"), 2, 2, STRUCT_START_TAG },
    +        { XCS("c"), 4, 3, STRUCT_START_TAG },
    +        { XCS("c"), 8, 3, STRUCT_END_TAG },
    +        { XCS("b"), 2, 4, STRUCT_END_TAG },
    +        { XCS("d"), 2, 5, STRUCT_START_TAG },
    +        { XCS("f"), 4, 6, STRUCT_START_TAG },
    +        { XCS("f"), 8, 6, STRUCT_END_TAG },
    +        { XCS("d"), 2, 7, STRUCT_END_TAG },
    +        { XCS("a"), 0, 8, STRUCT_END_TAG }
    +    };
    +    const int expected_count = sizeof(expected) / sizeof(StructDataEntry);
    +    StructData storage;
     
    -    CharData_Init(&storage);
    +    StructData_Init(&storage);
         XML_SetUserData(parser, &storage);
         XML_SetStartElementHandler(parser, start_element_event_handler2);
         XML_SetEndElementHandler(parser, end_element_event_handler2);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     
    -    CharData_CheckString(&storage, expected); 
    +    StructData_CheckItems(&storage, expected, expected_count);
    +    StructData_Dispose(&storage);
     }
     END_TEST
     
    @@ -603,7 +1206,7 @@ START_TEST(test_line_number_after_error)
             "  \n"
             "  ";  /* missing  */
         XML_Size lineno;
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_FALSE) != XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_FALSE) != XML_STATUS_ERROR)
             fail("Expected a parse error");
     
         lineno = XML_GetCurrentLineNumber(parser);
    @@ -623,7 +1226,7 @@ START_TEST(test_column_number_after_error)
             "  \n"
             "  ";  /* missing  */
         XML_Size colno;
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_FALSE) != XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_FALSE) != XML_STATUS_ERROR)
             fail("Expected a parse error");
     
         colno = XML_GetCurrentColumnNumber(parser);
    @@ -666,7 +1269,51 @@ START_TEST(test_really_long_lines)
             "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
             "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
             "";
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test cdata processing across a buffer boundary */
    +START_TEST(test_really_long_encoded_lines)
    +{
    +    /* As above, except that we want to provoke an output buffer
    +     * overflow with a non-trivial encoding.  For this we need to pass
    +     * the whole cdata in one go, not byte-by-byte.
    +     */
    +    void *buffer;
    +    const char *text =
    +        ""
    +        ""
    +        /* 64 chars */
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        /* until we have at least 1024 characters on the line: */
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+"
    +        "";
    +    int parse_len = (int)strlen(text);
    +
    +    /* Need a cdata handler to provoke the code path we want to test */
    +    XML_SetCharacterDataHandler(parser, dummy_cdata_handler);
    +    buffer = XML_GetBuffer(parser, parse_len);
    +    if (buffer == NULL)
    +        fail("Could not allocate parse buffer");
    +    memcpy(buffer, text, parse_len);
    +    if (XML_ParseBuffer(parser, parse_len, XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -676,26 +1323,34 @@ END_TEST
      * Element event tests.
      */
     
    +static void XMLCALL
    +start_element_event_handler(void *userData,
    +                            const XML_Char *name,
    +                            const XML_Char **UNUSED_P(atts))
    +{
    +    CharData_AppendXMLChars((CharData *)userData, name, -1);
    +}
    +
     static void XMLCALL
     end_element_event_handler(void *userData, const XML_Char *name)
     {
         CharData *storage = (CharData *) userData;
    -    CharData_AppendString(storage, "/");
    +    CharData_AppendXMLChars(storage, XCS("/"), 1);
         CharData_AppendXMLChars(storage, name, -1);
     }
     
     START_TEST(test_end_element_events)
     {
         const char *text = "";
    -    const char *expected = "/c/b/f/d/a";
    +    const XML_Char *expected = XCS("/c/b/f/d/a");
         CharData storage;
     
         CharData_Init(&storage);
         XML_SetUserData(parser, &storage);
         XML_SetEndElementHandler(parser, end_element_event_handler);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
    -    CharData_CheckString(&storage, expected);
    +    CharData_CheckXMLChars(&storage, expected);
     }
     END_TEST
     
    @@ -719,9 +1374,9 @@ is_whitespace_normalized(const XML_Char *s, int is_cdata)
         int blanks = 0;
         int at_start = 1;
         while (*s) {
    -        if (*s == ' ')
    +        if (*s == XCS(' '))
                 ++blanks;
    -        else if (*s == '\t' || *s == '\n' || *s == '\r')
    +        else if (*s == XCS('\t') || *s == XCS('\n') || *s == XCS('\r'))
                 return 0;
             else {
                 if (at_start) {
    @@ -745,25 +1400,25 @@ is_whitespace_normalized(const XML_Char *s, int is_cdata)
     static void
     testhelper_is_whitespace_normalized(void)
     {
    -    assert(is_whitespace_normalized("abc", 0));
    -    assert(is_whitespace_normalized("abc", 1));
    -    assert(is_whitespace_normalized("abc def ghi", 0));
    -    assert(is_whitespace_normalized("abc def ghi", 1));
    -    assert(!is_whitespace_normalized(" abc def ghi", 0));
    -    assert(is_whitespace_normalized(" abc def ghi", 1));
    -    assert(!is_whitespace_normalized("abc  def ghi", 0));
    -    assert(is_whitespace_normalized("abc  def ghi", 1));
    -    assert(!is_whitespace_normalized("abc def ghi ", 0));
    -    assert(is_whitespace_normalized("abc def ghi ", 1));
    -    assert(!is_whitespace_normalized(" ", 0));
    -    assert(is_whitespace_normalized(" ", 1));
    -    assert(!is_whitespace_normalized("\t", 0));
    -    assert(!is_whitespace_normalized("\t", 1));
    -    assert(!is_whitespace_normalized("\n", 0));
    -    assert(!is_whitespace_normalized("\n", 1));
    -    assert(!is_whitespace_normalized("\r", 0));
    -    assert(!is_whitespace_normalized("\r", 1));
    -    assert(!is_whitespace_normalized("abc\t def", 1));
    +    assert(is_whitespace_normalized(XCS("abc"), 0));
    +    assert(is_whitespace_normalized(XCS("abc"), 1));
    +    assert(is_whitespace_normalized(XCS("abc def ghi"), 0));
    +    assert(is_whitespace_normalized(XCS("abc def ghi"), 1));
    +    assert(!is_whitespace_normalized(XCS(" abc def ghi"), 0));
    +    assert(is_whitespace_normalized(XCS(" abc def ghi"), 1));
    +    assert(!is_whitespace_normalized(XCS("abc  def ghi"), 0));
    +    assert(is_whitespace_normalized(XCS("abc  def ghi"), 1));
    +    assert(!is_whitespace_normalized(XCS("abc def ghi "), 0));
    +    assert(is_whitespace_normalized(XCS("abc def ghi "), 1));
    +    assert(!is_whitespace_normalized(XCS(" "), 0));
    +    assert(is_whitespace_normalized(XCS(" "), 1));
    +    assert(!is_whitespace_normalized(XCS("\t"), 0));
    +    assert(!is_whitespace_normalized(XCS("\t"), 1));
    +    assert(!is_whitespace_normalized(XCS("\n"), 0));
    +    assert(!is_whitespace_normalized(XCS("\n"), 1));
    +    assert(!is_whitespace_normalized(XCS("\r"), 0));
    +    assert(!is_whitespace_normalized(XCS("\r"), 1));
    +    assert(!is_whitespace_normalized(XCS("abc\t def"), 1));
     }
     
     static void XMLCALL
    @@ -775,12 +1430,13 @@ check_attr_contains_normalized_whitespace(void *UNUSED_P(userData),
         for (i = 0; atts[i] != NULL; i += 2) {
             const XML_Char *attrname = atts[i];
             const XML_Char *value = atts[i + 1];
    -        if (strcmp("attr", attrname) == 0
    -            || strcmp("ents", attrname) == 0
    -            || strcmp("refs", attrname) == 0) {
    +        if (xcstrcmp(XCS("attr"), attrname) == 0
    +            || xcstrcmp(XCS("ents"), attrname) == 0
    +            || xcstrcmp(XCS("refs"), attrname) == 0) {
                 if (!is_whitespace_normalized(value, 0)) {
                     char buffer[256];
    -                sprintf(buffer, "attribute value not normalized: %s='%s'",
    +                sprintf(buffer, "attribute value not normalized: %"
    +                        XML_FMT_STR "='%" XML_FMT_STR "'",
                             attrname, value);
                     fail(buffer);
                 }
    @@ -806,7 +1462,7 @@ START_TEST(test_attr_whitespace_normalization)
     
         XML_SetStartElementHandler(parser,
                                    check_attr_contains_normalized_whitespace);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -826,11 +1482,36 @@ START_TEST(test_xmldecl_misplaced)
     }
     END_TEST
     
    +START_TEST(test_xmldecl_invalid)
    +{
    +    expect_failure("\n",
    +                   XML_ERROR_XML_DECL,
    +                   "Failed to report invalid XML declaration");
    +}
    +END_TEST
    +
    +START_TEST(test_xmldecl_missing_attr)
    +{
    +    expect_failure("\n\n",
    +                   XML_ERROR_XML_DECL,
    +                   "Failed to report missing XML declaration attribute");
    +}
    +END_TEST
    +
    +START_TEST(test_xmldecl_missing_value)
    +{
    +    expect_failure("\n"
    +                   "",
    +                   XML_ERROR_XML_DECL,
    +                   "Failed to report missing attribute value");
    +}
    +END_TEST
    +
     /* Regression test for SF bug #584832. */
     static int XMLCALL
     UnknownEncodingHandler(void *UNUSED_P(data),const XML_Char *encoding,XML_Encoding *info)
     {
    -    if (strcmp(encoding,"unsupported-encoding") == 0) {
    +    if (xcstrcmp(encoding, XCS("unsupported-encoding")) == 0) {
             int i;
             for (i = 0; i < 256; ++i)
                 info->map[i] = i;
    @@ -850,51 +1531,218 @@ START_TEST(test_unknown_encoding_internal_entity)
             "";
     
         XML_SetUnknownEncodingHandler(parser, UnknownEncodingHandler, NULL);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
     
    +/* Test unrecognised encoding handler */
    +static void dummy_release(void *UNUSED_P(data))
    +{
    +}
    +
    +static int XMLCALL
    +UnrecognisedEncodingHandler(void *UNUSED_P(data),
    +                            const XML_Char *UNUSED_P(encoding),
    +                            XML_Encoding *info)
    +{
    +    info->data = NULL;
    +    info->convert = NULL;
    +    info->release = dummy_release;
    +    return XML_STATUS_ERROR;
    +}
    +
    +START_TEST(test_unrecognised_encoding_internal_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +
    +    XML_SetUnknownEncodingHandler(parser,
    +                                  UnrecognisedEncodingHandler,
    +                                  NULL);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Unrecognised encoding not rejected");
    +}
    +END_TEST
    +
     /* Regression test for SF bug #620106. */
     static int XMLCALL
    -external_entity_loader_set_encoding(XML_Parser parser,
    -                                    const XML_Char *context,
    -                                    const XML_Char *UNUSED_P(base),
    -                                    const XML_Char *UNUSED_P(systemId),
    -                                    const XML_Char *UNUSED_P(publicId))
    +external_entity_loader(XML_Parser parser,
    +                       const XML_Char *context,
    +                       const XML_Char *UNUSED_P(base),
    +                       const XML_Char *UNUSED_P(systemId),
    +                       const XML_Char *UNUSED_P(publicId))
     {
    -    /* This text says it's an unsupported encoding, but it's really
    -       UTF-8, which we tell Expat using XML_SetEncoding().
    -    */
    -    const char *text =
    -        ""
    -        "\xC3\xA9";
    +    ExtTest *test_data = (ExtTest *)XML_GetUserData(parser);
         XML_Parser extparser;
     
         extparser = XML_ExternalEntityParserCreate(parser, context, NULL);
         if (extparser == NULL)
             fail("Could not create external entity parser.");
    -    if (!XML_SetEncoding(extparser, "utf-8"))
    -        fail("XML_SetEncoding() ignored for external entity");
    -    if (  _XML_Parse_SINGLE_BYTES(extparser, text, strlen(text), XML_TRUE)
    -          == XML_STATUS_ERROR) {
    -        xml_failure(parser);
    -        return 0;
    +    if (test_data->encoding != NULL) {
    +        if (!XML_SetEncoding(extparser, test_data->encoding))
    +            fail("XML_SetEncoding() ignored for external entity");
         }
    -    return 1;
    +    if ( _XML_Parse_SINGLE_BYTES(extparser,
    +                                 test_data->parse_text,
    +                                 (int)strlen(test_data->parse_text),
    +                                 XML_TRUE)
    +          == XML_STATUS_ERROR) {
    +        xml_failure(extparser);
    +        return XML_STATUS_ERROR;
    +    }
    +    XML_ParserFree(extparser);
    +    return XML_STATUS_OK;
     }
     
     START_TEST(test_ext_entity_set_encoding)
     {
         const char *text =
             "\n"
    +        "  \n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest test_data = {
    +        /* This text says it's an unsupported encoding, but it's really
    +           UTF-8, which we tell Expat using XML_SetEncoding().
    +        */
    +        "\xC3\xA9",
    +        XCS("utf-8"),
    +        NULL
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00e9");
    +#else
    +    const XML_Char *expected = XCS("\xc3\xa9");
    +#endif
    +
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    run_ext_character_check(text, &test_data, expected);
    +}
    +END_TEST
    +
    +/* Test external entities with no handler */
    +START_TEST(test_ext_entity_no_handler)
    +{
    +    const char *text =
    +        "\n"
             "]>\n"
             "&en;";
     
    -    XML_SetExternalEntityRefHandler(parser,
    -                                    external_entity_loader_set_encoding);
    -    run_character_check(text, "\xC3\xA9");
    +    XML_SetDefaultHandler(parser, dummy_default_handler);
    +    run_character_check(text, XCS(""));
    +}
    +END_TEST
    +
    +/* Test UTF-8 BOM is accepted */
    +START_TEST(test_ext_entity_set_bom)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest test_data = {
    +        "\xEF\xBB\xBF" /* BOM */
    +        ""
    +        "\xC3\xA9",
    +        XCS("utf-8"),
    +        NULL
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00e9");
    +#else
    +    const XML_Char *expected = XCS("\xc3\xa9");
    +#endif
    +
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    run_ext_character_check(text, &test_data, expected);
    +}
    +END_TEST
    +
    +
    +/* Test that bad encodings are faulted */
    +typedef struct ext_faults
    +{
    +    const char *parse_text;
    +    const char *fail_text;
    +    const XML_Char *encoding;
    +    enum XML_Error error;
    +} ExtFaults;
    +
    +static int XMLCALL
    +external_entity_faulter(XML_Parser parser,
    +                        const XML_Char *context,
    +                        const XML_Char *UNUSED_P(base),
    +                        const XML_Char *UNUSED_P(systemId),
    +                        const XML_Char *UNUSED_P(publicId))
    +{
    +    XML_Parser ext_parser;
    +    ExtFaults *fault = (ExtFaults *)XML_GetUserData(parser);
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (fault->encoding != NULL) {
    +        if (!XML_SetEncoding(ext_parser, fault->encoding))
    +            fail("XML_SetEncoding failed");
    +    }
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser,
    +                                fault->parse_text,
    +                                (int)strlen(fault->parse_text),
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail(fault->fail_text);
    +    if (XML_GetErrorCode(ext_parser) != fault->error)
    +        xml_failure(ext_parser);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_ERROR;
    +}
    +
    +START_TEST(test_ext_entity_bad_encoding)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtFaults fault = {
    +        "u",
    +        "Unsupported encoding not faulted",
    +        XCS("unknown"),
    +        XML_ERROR_UNKNOWN_ENCODING
    +    };
    +
    +    XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +    XML_SetUserData(parser, &fault);
    +    expect_failure(text,
    +                   XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Bad encoding should not have been accepted");
    +}
    +END_TEST
    +
    +/* Try handing an invalid encoding to an external entity parser */
    +START_TEST(test_ext_entity_bad_encoding_2)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +    ExtFaults fault = {
    +        "",
    +        "Unknown encoding not faulted",
    +        XCS("unknown-encoding"),
    +        XML_ERROR_UNKNOWN_ENCODING
    +    };
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +    XML_SetUserData(parser, &fault);
    +    expect_failure(text, XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Bad encoding not faulted in external entity handler");
     }
     END_TEST
     
    @@ -906,7 +1754,7 @@ START_TEST(test_wfc_undeclared_entity_unread_external_subset) {
             "\n"
             "&entity;";
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -936,27 +1784,6 @@ START_TEST(test_wfc_undeclared_entity_standalone) {
     }
     END_TEST
     
    -static int XMLCALL
    -external_entity_loader(XML_Parser parser,
    -                       const XML_Char *context,
    -                       const XML_Char *UNUSED_P(base),
    -                       const XML_Char *UNUSED_P(systemId),
    -                       const XML_Char *UNUSED_P(publicId))
    -{
    -    char *text = (char *)XML_GetUserData(parser);
    -    XML_Parser extparser;
    -
    -    extparser = XML_ExternalEntityParserCreate(parser, context, NULL);
    -    if (extparser == NULL)
    -        fail("Could not create external entity parser.");
    -    if (  _XML_Parse_SINGLE_BYTES(extparser, text, strlen(text), XML_TRUE)
    -          == XML_STATUS_ERROR) {
    -        xml_failure(parser);
    -        return XML_STATUS_ERROR;
    -    }
    -    return XML_STATUS_OK;
    -}
    -
     /* Test that an error is reported for unknown entities if we have read
        an external subset, and standalone is true.
     */
    @@ -965,11 +1792,14 @@ START_TEST(test_wfc_undeclared_entity_with_external_subset_standalone) {
             "\n"
             "\n"
             "&entity;";
    -    char foo_text[] =
    -        "";
    +    ExtTest test_data = {
    +        "",
    +        NULL,
    +        NULL
    +    };
     
         XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    -    XML_SetUserData(parser, foo_text);
    +    XML_SetUserData(parser, &test_data);
         XML_SetExternalEntityRefHandler(parser, external_entity_loader);
         expect_failure(text,
                        XML_ERROR_UNDEFINED_ENTITY,
    @@ -977,6 +1807,26 @@ START_TEST(test_wfc_undeclared_entity_with_external_subset_standalone) {
     }
     END_TEST
     
    +/* Test that external entity handling is not done if the parsing flag
    + * is set to UNLESS_STANDALONE
    + */
    +START_TEST(test_entity_with_external_subset_unless_standalone) {
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +    ExtTest test_data = { "", NULL, NULL };
    +
    +    XML_SetParamEntityParsing(parser,
    +                              XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    expect_failure(text,
    +                   XML_ERROR_UNDEFINED_ENTITY,
    +                   "Parser did not report undefined entity");
    +}
    +END_TEST
    +
     /* Test that no error is reported for unknown entities if we have read
        an external subset, and standalone is false.
     */
    @@ -985,14 +1835,80 @@ START_TEST(test_wfc_undeclared_entity_with_external_subset) {
             "\n"
             "\n"
             "&entity;";
    -    char foo_text[] =
    -        "";
    +    ExtTest test_data = {
    +        "",
    +        NULL,
    +        NULL
    +    };
     
         XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    -    XML_SetUserData(parser, foo_text);
         XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    -        xml_failure(parser);
    +    run_ext_character_check(text, &test_data, XCS(""));
    +}
    +END_TEST
    +
    +/* Test that an error is reported if our NotStandalone handler fails */
    +static int XMLCALL
    +reject_not_standalone_handler(void *UNUSED_P(userData))
    +{
    +    return XML_STATUS_ERROR;
    +}
    +
    +START_TEST(test_not_standalone_handler_reject)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +    ExtTest test_data = {
    +        "",
    +        NULL,
    +        NULL
    +    };
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    XML_SetNotStandaloneHandler(parser, reject_not_standalone_handler);
    +    expect_failure(text, XML_ERROR_NOT_STANDALONE,
    +                   "NotStandalone handler failed to reject");
    +
    +    /* Try again but without external entity handling */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetNotStandaloneHandler(parser, reject_not_standalone_handler);
    +    expect_failure(text, XML_ERROR_NOT_STANDALONE,
    +                   "NotStandalone handler failed to reject");
    +}
    +END_TEST
    +
    +/* Test that no error is reported if our NotStandalone handler succeeds */
    +static int XMLCALL
    +accept_not_standalone_handler(void *UNUSED_P(userData))
    +{
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_not_standalone_handler_accept)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +    ExtTest test_data = {
    +        "",
    +        NULL,
    +        NULL
    +    };
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    XML_SetNotStandaloneHandler(parser, accept_not_standalone_handler);
    +    run_ext_character_check(text, &test_data, XCS(""));
    +
    +    /* Repeat wtihout the external entity handler */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetNotStandaloneHandler(parser, accept_not_standalone_handler);
    +    run_character_check(text, XCS(""));
     }
     END_TEST
     
    @@ -1010,13 +1926,57 @@ START_TEST(test_wfc_no_recursive_entity_refs)
     }
     END_TEST
     
    +/* Test incomplete external entities are faulted */
    +START_TEST(test_ext_entity_invalid_parse)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    const ExtFaults faults[] = {
    +        {
    +            "<",
    +            "Incomplete element declaration not faulted",
    +            NULL,
    +            XML_ERROR_UNCLOSED_TOKEN
    +        },
    +        {
    +            "<\xe2\x82", /* First two bytes of a three-byte char */
    +            "Incomplete character not faulted",
    +            NULL,
    +            XML_ERROR_PARTIAL_CHAR
    +        },
    +        {
    +            "\xe2\x82",
    +            "Incomplete character in CDATA not faulted",
    +            NULL,
    +            XML_ERROR_PARTIAL_CHAR
    +        },
    +        { NULL, NULL, NULL, XML_ERROR_NONE }
    +    };
    +    const ExtFaults *fault = faults;
    +
    +    for (; fault->parse_text != NULL; fault++) {
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +        XML_SetUserData(parser, (void *)fault);
    +        expect_failure(text,
    +                       XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                       "Parser did not report external entity error");
    +        XML_ParserReset(parser, NULL);
    +    }
    +}
    +END_TEST
    +
    +
     /* Regression test for SF bug #483514. */
     START_TEST(test_dtd_default_handling)
     {
         const char *text =
             "\n"
    -        "\n"
    +        "\n"
    +        "\n"
             "\n"
             "\n"
             "\n"
    @@ -1024,16 +1984,122 @@ START_TEST(test_dtd_default_handling)
             "]>";
     
         XML_SetDefaultHandler(parser, accumulate_characters);
    -    XML_SetDoctypeDeclHandler(parser,
    -                              dummy_start_doctype_handler,
    -                              dummy_end_doctype_handler);
    +    XML_SetStartDoctypeDeclHandler(parser, dummy_start_doctype_handler);
    +    XML_SetEndDoctypeDeclHandler(parser, dummy_end_doctype_handler);
         XML_SetEntityDeclHandler(parser, dummy_entity_decl_handler);
         XML_SetNotationDeclHandler(parser, dummy_notation_decl_handler);
         XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
         XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
         XML_SetProcessingInstructionHandler(parser, dummy_pi_handler);
         XML_SetCommentHandler(parser, dummy_comment_handler);
    -    run_character_check(text, "\n\n\n\n\n\n\n");
    +    XML_SetStartCdataSectionHandler(parser, dummy_start_cdata_handler);
    +    XML_SetEndCdataSectionHandler(parser, dummy_end_cdata_handler);
    +    run_character_check(text, XCS("\n\n\n\n\n\n\n"));
    +}
    +END_TEST
    +
    +/* Test handling of attribute declarations */
    +typedef struct AttTest {
    +    const char *definition;
    +    const XML_Char *element_name;
    +    const XML_Char *attr_name;
    +    const XML_Char *attr_type;
    +    const XML_Char *default_value;
    +    int is_required;
    +} AttTest;
    +
    +static void XMLCALL
    +verify_attlist_decl_handler(void *userData,
    +                            const XML_Char *element_name,
    +                            const XML_Char *attr_name,
    +                            const XML_Char *attr_type,
    +                            const XML_Char *default_value,
    +                            int is_required)
    +{
    +    AttTest *at = (AttTest *)userData;
    +
    +    if (xcstrcmp(element_name, at->element_name))
    +        fail("Unexpected element name in attribute declaration");
    +    if (xcstrcmp(attr_name, at->attr_name))
    +        fail("Unexpected attribute name in attribute declaration");
    +    if (xcstrcmp(attr_type, at->attr_type))
    +        fail("Unexpected attribute type in attribute declaration");
    +    if ((default_value == NULL && at->default_value != NULL) ||
    +        (default_value != NULL && at->default_value == NULL) ||
    +        (default_value != NULL && xcstrcmp(default_value, at->default_value)))
    +        fail("Unexpected default value in attribute declaration");
    +    if (is_required != at->is_required)
    +        fail("Requirement mismatch in attribute declaration");
    +}
    +
    +START_TEST(test_dtd_attr_handling)
    +{
    +    const char *prolog =
    +        "\n";
    +    AttTest attr_data[] = {
    +        {
    +            "\n"
    +            "]>"
    +            "",
    +            XCS("doc"),
    +            XCS("a"),
    +            XCS("(one|two|three)"), /* Extraneous spaces will be removed */
    +            NULL,
    +            XML_TRUE
    +        },
    +        {
    +            "\n"
    +            "\n"
    +            "]>"
    +            "",
    +            XCS("doc"),
    +            XCS("a"),
    +            XCS("NOTATION(foo)"),
    +            NULL,
    +            XML_FALSE
    +        },
    +        {
    +            "\n"
    +            "]>"
    +            "",
    +            XCS("doc"),
    +            XCS("a"),
    +            XCS("NOTATION(foo)"),
    +            XCS("bar"),
    +            XML_FALSE
    +        },
    +        {
    +            "\n"
    +            "]>"
    +            "",
    +            XCS("doc"),
    +            XCS("a"),
    +            XCS("CDATA"),
    +#ifdef XML_UNICODE
    +            XCS("\x06f2"),
    +#else
    +            XCS("\xdb\xb2"),
    +#endif
    +            XML_FALSE
    +        },
    +        { NULL, NULL, NULL, NULL, NULL, XML_FALSE }
    +    };
    +    AttTest *test;
    +
    +    for (test = attr_data; test->definition != NULL; test++) {
    +        XML_SetAttlistDeclHandler(parser, verify_attlist_decl_handler);
    +        XML_SetUserData(parser, test);
    +        if (_XML_Parse_SINGLE_BYTES(parser, prolog, (int)strlen(prolog),
    +                                    XML_FALSE) == XML_STATUS_ERROR)
    +            xml_failure(parser);
    +        if (_XML_Parse_SINGLE_BYTES(parser,
    +                                    test->definition,
    +                                    (int)strlen(test->definition),
    +                                    XML_TRUE) == XML_STATUS_ERROR)
    +            xml_failure(parser);
    +        XML_ParserReset(parser, NULL);
    +    }
     }
     END_TEST
     
    @@ -1046,11 +2112,11 @@ END_TEST
     START_TEST(test_empty_ns_without_namespaces)
     {
         const char *text =
    -        "\n"
    +        "\n"
             "  \n"
             "";
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -1064,11 +2130,11 @@ START_TEST(test_ns_in_attribute_default_without_namespaces)
         const char *text =
             "\n"
    +        "    xmlns:e CDATA 'http://example.org/'>\n"
             "      ]>\n"
             "";
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -1121,7 +2187,7 @@ START_TEST(test_stop_parser_between_char_data_calls)
     
         XML_SetCharacterDataHandler(parser, clearing_aborting_character_handler);
         resumable = XML_FALSE;
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
             xml_failure(parser);
         if (XML_GetErrorCode(parser) != XML_ERROR_ABORTED)
             xml_failure(parser);
    @@ -1142,24 +2208,103 @@ START_TEST(test_suspend_parser_between_char_data_calls)
     
         XML_SetCharacterDataHandler(parser, clearing_aborting_character_handler);
         resumable = XML_TRUE;
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) != XML_STATUS_SUSPENDED)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_SUSPENDED)
             xml_failure(parser);
         if (XML_GetErrorCode(parser) != XML_ERROR_NONE)
             xml_failure(parser);
    +    /* Try parsing directly */
    +    if (XML_Parse(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Attempt to continue parse while suspended not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_SUSPENDED)
    +        fail("Suspended parse not faulted with correct error");
     }
     END_TEST
     
    +
    +static XML_Bool abortable = XML_FALSE;
    +
    +static void
    +parser_stop_character_handler(void *UNUSED_P(userData),
    +                              const XML_Char *UNUSED_P(s),
    +                              int UNUSED_P(len))
    +{
    +    XML_StopParser(parser, resumable);
    +    XML_SetCharacterDataHandler(parser, NULL);
    +    if (!resumable) {
    +        /* Check that aborting an aborted parser is faulted */
    +        if (XML_StopParser(parser, XML_FALSE) != XML_STATUS_ERROR)
    +            fail("Aborting aborted parser not faulted");
    +        if (XML_GetErrorCode(parser) != XML_ERROR_FINISHED)
    +            xml_failure(parser);
    +    } else if (abortable) {
    +        /* Check that aborting a suspended parser works */
    +        if (XML_StopParser(parser, XML_FALSE) == XML_STATUS_ERROR)
    +            xml_failure(parser);
    +    } else {
    +        /* Check that suspending a suspended parser works */
    +        if (XML_StopParser(parser, XML_TRUE) != XML_STATUS_ERROR)
    +            fail("Suspending suspended parser not faulted");
    +        if (XML_GetErrorCode(parser) != XML_ERROR_SUSPENDED)
    +            xml_failure(parser);
    +    }
    +}
    +
    +/* Test repeated calls to XML_StopParser are handled correctly */
    +START_TEST(test_repeated_stop_parser_between_char_data_calls)
    +{
    +    const char *text = long_character_data_text;
    +
    +    XML_SetCharacterDataHandler(parser, parser_stop_character_handler);
    +    resumable = XML_FALSE;
    +    abortable = XML_FALSE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Failed to double-stop parser");
    +
    +    XML_ParserReset(parser, NULL);
    +    XML_SetCharacterDataHandler(parser, parser_stop_character_handler);
    +    resumable = XML_TRUE;
    +    abortable = XML_FALSE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_SUSPENDED)
    +        fail("Failed to double-suspend parser");
    +
    +    XML_ParserReset(parser, NULL);
    +    XML_SetCharacterDataHandler(parser, parser_stop_character_handler);
    +    resumable = XML_TRUE;
    +    abortable = XML_TRUE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Failed to suspend-abort parser");
    +}
    +END_TEST
    +
    +
     START_TEST(test_good_cdata_ascii)
     {
         const char *text = "Hello, world!]]>";
    -    const char *expected = "Hello, world!";
    +    const XML_Char *expected = XCS("Hello, world!");
     
         CharData storage;
         CharData_Init(&storage);
         XML_SetUserData(parser, &storage);
         XML_SetCharacterDataHandler(parser, accumulate_characters);
    +    /* Add start and end handlers for coverage */
    +    XML_SetStartCdataSectionHandler(parser, dummy_start_cdata_handler);
    +    XML_SetEndCdataSectionHandler(parser, dummy_end_cdata_handler);
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +
    +    /* Try again, this time with a default handler */
    +    XML_ParserReset(parser, NULL);
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
    +    XML_SetDefaultHandler(parser, dummy_default_handler);
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
         CharData_CheckXMLChars(&storage, expected);
     }
    @@ -1177,19 +2322,185 @@ START_TEST(test_good_cdata_utf16)
                     " \0e\0n\0c\0o\0d\0i\0n\0g\0=\0'\0u\0t\0f\0-\0""1\0""6\0'"
                     "\0?\0>\0\n"
                 "\0<\0a\0>\0<\0!\0[\0C\0D\0A\0T\0A\0[\0h\0e\0l\0l\0o\0]\0]\0>\0<\0/\0a\0>";
    -    const char *expected = "hello";
    +    const XML_Char *expected = XCS("hello");
     
         CharData storage;
         CharData_Init(&storage);
         XML_SetUserData(parser, &storage);
         XML_SetCharacterDataHandler(parser, accumulate_characters);
     
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, sizeof(text) - 1, XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text) - 1, XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
         CharData_CheckXMLChars(&storage, expected);
     }
     END_TEST
     
    +START_TEST(test_good_cdata_utf16_le)
    +{
    +    /* Test data is:
    +     *   
    +     *   
    +     */
    +    const char text[] =
    +            "<\0?\0x\0m\0l\0"
    +                " \0v\0e\0r\0s\0i\0o\0n\0=\0'\0\x31\0.\0\x30\0'\0"
    +                " \0e\0n\0c\0o\0d\0i\0n\0g\0=\0'\0u\0t\0f\0-\0""1\0""6\0'"
    +                "\0?\0>\0\n"
    +            "\0<\0a\0>\0<\0!\0[\0C\0D\0A\0T\0A\0[\0h\0e\0l\0l\0o\0]\0]\0>\0<\0/\0a\0>\0";
    +    const XML_Char *expected = XCS("hello");
    +
    +    CharData storage;
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text) - 1, XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test UTF16 conversion of a long cdata string */
    +
    +/* 16 characters: handy macro to reduce visual clutter */
    +#define A_TO_P_IN_UTF16 "\0A\0B\0C\0D\0E\0F\0G\0H\0I\0J\0K\0L\0M\0N\0O\0P"
    +
    +START_TEST(test_long_cdata_utf16)
    +{
    +    /* Test data is:
    +     * 
    +     * 
    +     */
    +    const char text[] =
    +        "\0<\0?\0x\0m\0l\0 "
    +        "\0v\0e\0r\0s\0i\0o\0n\0=\0'\0\x31\0.\0\x30\0'\0 "
    +        "\0e\0n\0c\0o\0d\0i\0n\0g\0=\0'\0u\0t\0f\0-\0\x31\0\x36\0'\0?\0>"
    +        "\0<\0a\0>\0<\0!\0[\0C\0D\0A\0T\0A\0["
    +        /* 64 characters per line */
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16  A_TO_P_IN_UTF16
    +        A_TO_P_IN_UTF16
    +        "\0]\0]\0>\0<\0/\0a\0>";
    +    const XML_Char *expected =
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP")
    +        XCS("ABCDEFGHIJKLMNOP";)
    +    CharData storage;
    +    void *buffer;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
    +    buffer = XML_GetBuffer(parser, sizeof(text) - 1);
    +    if (buffer == NULL)
    +        fail("Could not allocate parse buffer");
    +    memcpy(buffer, text, sizeof(text) - 1);
    +    if (XML_ParseBuffer(parser,
    +                        sizeof(text) - 1,
    +                        XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test handling of multiple unit UTF-16 characters */
    +START_TEST(test_multichar_cdata_utf16)
    +{
    +    /* Test data is:
    +     *   
    +     *   
    +     *
    +     * where {MINIM} is U+1d15e (a minim or half-note)
    +     *   UTF-16: 0xd834 0xdd5e
    +     *   UTF-8:  0xf0 0x9d 0x85 0x9e
    +     * and {CROTCHET} is U+1d15f (a crotchet or quarter-note)
    +     *   UTF-16: 0xd834 0xdd5f
    +     *   UTF-8:  0xf0 0x9d 0x85 0x9f
    +     */
    +    const char text[] =
    +        "\0<\0?\0x\0m\0l\0"
    +        " \0v\0e\0r\0s\0i\0o\0n\0=\0'\0\x31\0.\0\x30\0'\0"
    +        " \0e\0n\0c\0o\0d\0i\0n\0g\0=\0'\0u\0t\0f\0-\0""1\0""6\0'"
    +        "\0?\0>\0\n"
    +        "\0<\0a\0>\0<\0!\0[\0C\0D\0A\0T\0A\0["
    +        "\xd8\x34\xdd\x5e\xd8\x34\xdd\x5f"
    +        "\0]\0]\0>\0<\0/\0a\0>";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\xd834\xdd5e\xd834\xdd5f");
    +#else
    +    const XML_Char *expected = XCS("\xf0\x9d\x85\x9e\xf0\x9d\x85\x9f");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text) - 1, XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test that an element name with a UTF-16 surrogate pair is rejected */
    +START_TEST(test_utf16_bad_surrogate_pair)
    +{
    +    /* Test data is:
    +     *   
    +     *   
    +     *
    +     * where {BADLINB} is U+10000 (the first Linear B character)
    +     * with the UTF-16 surrogate pair in the wrong order, i.e.
    +     *   0xdc00 0xd800
    +     */
    +    const char text[] =
    +        "\0<\0?\0x\0m\0l\0"
    +        " \0v\0e\0r\0s\0i\0o\0n\0=\0'\0\x31\0.\0\x30\0'\0"
    +        " \0e\0n\0c\0o\0d\0i\0n\0g\0=\0'\0u\0t\0f\0-\0""1\0""6\0'"
    +        "\0?\0>\0\n"
    +        "\0<\0a\0>\0<\0!\0[\0C\0D\0A\0T\0A\0["
    +        "\xdc\x00\xd8\x00"
    +        "\0]\0]\0>\0<\0/\0a\0>";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text) - 1,
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Reversed UTF-16 surrogate pair not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_INVALID_TOKEN)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +
     START_TEST(test_bad_cdata)
     {
         struct CaseData {
    @@ -1227,7 +2538,7 @@ START_TEST(test_bad_cdata)
         size_t i = 0;
         for (; i < sizeof(cases) / sizeof(struct CaseData); i++) {
             const enum XML_Status actualStatus = _XML_Parse_SINGLE_BYTES(
    -                parser, cases[i].text, strlen(cases[i].text), XML_TRUE);
    +                parser, cases[i].text, (int)strlen(cases[i].text), XML_TRUE);
             const enum XML_Error actualError = XML_GetErrorCode(parser);
     
             assert(actualStatus == XML_STATUS_ERROR);
    @@ -1244,6 +2555,4561 @@ START_TEST(test_bad_cdata)
     }
     END_TEST
     
    +/* Test failures in UTF-16 CDATA */
    +START_TEST(test_bad_cdata_utf16)
    +{
    +    struct CaseData {
    +        size_t text_bytes;
    +        const char *text;
    +        enum XML_Error expected_error;
    +    };
    +
    +    const char prolog[] =
    +        "\0<\0?\0x\0m\0l\0"
    +        " \0v\0e\0r\0s\0i\0o\0n\0=\0'\0\x31\0.\0\x30\0'\0"
    +        " \0e\0n\0c\0o\0d\0i\0n\0g\0=\0'\0u\0t\0f\0-\0""1\0""6\0'"
    +        "\0?\0>\0\n"
    +        "\0<\0a\0>";
    +    struct CaseData cases[] = {
    +        {1, "\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {2, "\0<", XML_ERROR_UNCLOSED_TOKEN},
    +        {3, "\0<\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {4, "\0<\0!", XML_ERROR_UNCLOSED_TOKEN},
    +        {5, "\0<\0!\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {6, "\0<\0!\0[", XML_ERROR_UNCLOSED_TOKEN},
    +        {7, "\0<\0!\0[\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {8, "\0<\0!\0[\0C", XML_ERROR_UNCLOSED_TOKEN},
    +        {9, "\0<\0!\0[\0C\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {10, "\0<\0!\0[\0C\0D", XML_ERROR_UNCLOSED_TOKEN},
    +        {11, "\0<\0!\0[\0C\0D\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {12, "\0<\0!\0[\0C\0D\0A", XML_ERROR_UNCLOSED_TOKEN},
    +        {13, "\0<\0!\0[\0C\0D\0A\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {14, "\0<\0!\0[\0C\0D\0A\0T", XML_ERROR_UNCLOSED_TOKEN},
    +        {15, "\0<\0!\0[\0C\0D\0A\0T\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {16, "\0<\0!\0[\0C\0D\0A\0T\0A", XML_ERROR_UNCLOSED_TOKEN},
    +        {17, "\0<\0!\0[\0C\0D\0A\0T\0A\0", XML_ERROR_UNCLOSED_TOKEN},
    +        {18, "\0<\0!\0[\0C\0D\0A\0T\0A\0[",
    +         XML_ERROR_UNCLOSED_CDATA_SECTION},
    +        {19, "\0<\0!\0[\0C\0D\0A\0T\0A\0[\0",
    +         XML_ERROR_UNCLOSED_CDATA_SECTION},
    +        {20, "\0<\0!\0[\0C\0D\0A\0T\0A\0[\0Z",
    +         XML_ERROR_UNCLOSED_CDATA_SECTION},
    +        /* Now add a four-byte UTF-16 character */
    +        {21, "\0<\0!\0[\0C\0D\0A\0T\0A\0[\0Z\xd8",
    +         XML_ERROR_UNCLOSED_CDATA_SECTION},
    +        {22, "\0<\0!\0[\0C\0D\0A\0T\0A\0[\0Z\xd8\x34",
    +         XML_ERROR_PARTIAL_CHAR},
    +        {23, "\0<\0!\0[\0C\0D\0A\0T\0A\0[\0Z\xd8\x34\xdd",
    +         XML_ERROR_PARTIAL_CHAR},
    +        {24, "\0<\0!\0[\0C\0D\0A\0T\0A\0[\0Z\xd8\x34\xdd\x5e",
    +         XML_ERROR_UNCLOSED_CDATA_SECTION}
    +    };
    +    size_t i;
    +
    +    for (i = 0; i < sizeof(cases)/sizeof(struct CaseData); i++) {
    +        enum XML_Status actual_status;
    +        enum XML_Error actual_error;
    +
    +        if (_XML_Parse_SINGLE_BYTES(parser, prolog, (int)sizeof(prolog)-1,
    +                                    XML_FALSE) == XML_STATUS_ERROR)
    +            xml_failure(parser);
    +        actual_status = _XML_Parse_SINGLE_BYTES(parser,
    +                                                cases[i].text,
    +                                                (int)cases[i].text_bytes,
    +                                                XML_TRUE);
    +        assert(actual_status == XML_STATUS_ERROR);
    +        actual_error = XML_GetErrorCode(parser);
    +        if (actual_error != cases[i].expected_error) {
    +            char message[1024];
    +
    +            sprintf(message,
    +                    "Expected error %d (%" XML_FMT_STR
    +                    "), got %d (%" XML_FMT_STR ") for case %lu\n",
    +                    cases[i].expected_error,
    +                    XML_ErrorString(cases[i].expected_error),
    +                    actual_error,
    +                    XML_ErrorString(actual_error),
    +                    (long unsigned)(i+1));
    +            fail(message);
    +        }
    +        XML_ParserReset(parser, NULL);
    +    }
    +}
    +END_TEST
    +
    +static const char *long_cdata_text =
    +    "";
    +
    +/* Test stopping the parser in cdata handler */
    +START_TEST(test_stop_parser_between_cdata_calls)
    +{
    +    const char *text = long_cdata_text;
    +
    +    XML_SetCharacterDataHandler(parser,
    +                                clearing_aborting_character_handler);
    +    resumable = XML_FALSE;
    +    expect_failure(text, XML_ERROR_ABORTED,
    +                   "Parse not aborted in CDATA handler");
    +}
    +END_TEST
    +
    +/* Test suspending the parser in cdata handler */
    +START_TEST(test_suspend_parser_between_cdata_calls)
    +{
    +    const char *text = long_cdata_text;
    +    enum XML_Status result;
    +
    +    XML_SetCharacterDataHandler(parser,
    +                                clearing_aborting_character_handler);
    +    resumable = XML_TRUE;
    +    result = _XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE);
    +    if (result != XML_STATUS_SUSPENDED) {
    +        if (result == XML_STATUS_ERROR)
    +            xml_failure(parser);
    +        fail("Parse not suspended in CDATA handler");
    +    }
    +    if (XML_GetErrorCode(parser) != XML_ERROR_NONE)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test memory allocation functions */
    +START_TEST(test_memory_allocation)
    +{
    +    char *buffer = (char *)XML_MemMalloc(parser, 256);
    +    char *p;
    +
    +    if (buffer == NULL) {
    +        fail("Allocation failed");
    +    } else {
    +        /* Try writing to memory; some OSes try to cheat! */
    +        buffer[0] = 'T';
    +        buffer[1] = 'E';
    +        buffer[2] = 'S';
    +        buffer[3] = 'T';
    +        buffer[4] = '\0';
    +        if (strcmp(buffer, "TEST") != 0) {
    +            fail("Memory not writable");
    +        } else {
    +            p = (char *)XML_MemRealloc(parser, buffer, 512);
    +            if (p == NULL) {
    +                fail("Reallocation failed");
    +            } else {
    +                /* Write again, just to be sure */
    +                buffer = p;
    +                buffer[0] = 'V';
    +                if (strcmp(buffer, "VEST") != 0) {
    +                    fail("Reallocated memory not writable");
    +                }
    +            }
    +        }
    +        XML_MemFree(parser, buffer);
    +    }
    +}
    +END_TEST
    +
    +static void XMLCALL
    +record_default_handler(void *userData,
    +                       const XML_Char *UNUSED_P(s),
    +                       int UNUSED_P(len))
    +{
    +    CharData_AppendXMLChars((CharData *)userData, XCS("D"), 1);
    +}
    +
    +static void XMLCALL
    +record_cdata_handler(void *userData,
    +                     const XML_Char *UNUSED_P(s),
    +                     int UNUSED_P(len))
    +{
    +    CharData_AppendXMLChars((CharData *)userData, XCS("C"), 1);
    +    XML_DefaultCurrent(parser);
    +}
    +
    +static void XMLCALL
    +record_cdata_nodefault_handler(void *userData,
    +                     const XML_Char *UNUSED_P(s),
    +                     int UNUSED_P(len))
    +{
    +    CharData_AppendXMLChars((CharData *)userData, XCS("c"), 1);
    +}
    +
    +static void XMLCALL
    +record_skip_handler(void *userData,
    +                    const XML_Char *UNUSED_P(entityName),
    +                    int is_parameter_entity)
    +{
    +    CharData_AppendXMLChars((CharData *)userData,
    +                            is_parameter_entity ? XCS("E") : XCS("e"), 1);
    +}
    +
    +/* Test XML_DefaultCurrent() passes handling on correctly */
    +START_TEST(test_default_current)
    +{
    +    const char *text = "hell]";
    +    const char *entity_text =
    +        "\n"
    +        "]>\n"
    +        "&entity;";
    +    CharData storage;
    +
    +    XML_SetDefaultHandler(parser, record_default_handler);
    +    XML_SetCharacterDataHandler(parser, record_cdata_handler);
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, XCS("DCDCDCDCDCDD"));
    +
    +    /* Again, without the defaulting */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandler(parser, record_default_handler);
    +    XML_SetCharacterDataHandler(parser, record_cdata_nodefault_handler);
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, XCS("DcccccD"));
    +
    +    /* Now with an internal entity to complicate matters */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandler(parser, record_default_handler);
    +    XML_SetCharacterDataHandler(parser, record_cdata_handler);
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, entity_text, (int)strlen(entity_text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    /* The default handler suppresses the entity */
    +    CharData_CheckXMLChars(&storage, XCS("DDDDDDDDDDDDDDDDDDD"));
    +
    +    /* Again, with a skip handler */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandler(parser, record_default_handler);
    +    XML_SetCharacterDataHandler(parser, record_cdata_handler);
    +    XML_SetSkippedEntityHandler(parser, record_skip_handler);
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, entity_text, (int)strlen(entity_text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    /* The default handler suppresses the entity */
    +    CharData_CheckXMLChars(&storage, XCS("DDDDDDDDDDDDDDDDDeD"));
    +
    +    /* This time, allow the entity through */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandlerExpand(parser, record_default_handler);
    +    XML_SetCharacterDataHandler(parser, record_cdata_handler);
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, entity_text, (int)strlen(entity_text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, XCS("DDDDDDDDDDDDDDDDDCDD"));
    +
    +    /* Finally, without passing the cdata to the default handler */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandlerExpand(parser, record_default_handler);
    +    XML_SetCharacterDataHandler(parser, record_cdata_nodefault_handler);
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, entity_text, (int)strlen(entity_text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, XCS("DDDDDDDDDDDDDDDDDcD"));
    +}
    +END_TEST
    +
    +/* Test DTD element parsing code paths */
    +START_TEST(test_dtd_elements)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "Wombats are go";
    +
    +    XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test foreign DTD handling */
    +START_TEST(test_set_foreign_dtd)
    +{
    +    const char *text1 =
    +        "\n";
    +    const char *text2 =
    +        "&entity;";
    +    ExtTest test_data = {
    +        "",
    +        NULL,
    +        NULL
    +    };
    +
    +    /* Check hash salt is passed through too */
    +    XML_SetHashSalt(parser, 0x12345678);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    /* Add a default handler to exercise more code paths */
    +    XML_SetDefaultHandler(parser, dummy_default_handler);
    +    if (XML_UseForeignDTD(parser, XML_TRUE) != XML_ERROR_NONE)
    +        fail("Could not set foreign DTD");
    +    if (_XML_Parse_SINGLE_BYTES(parser, text1, (int)strlen(text1),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    /* Ensure that trying to set the DTD after parsing has started
    +     * is faulted, even if it's the same setting.
    +     */
    +    if (XML_UseForeignDTD(parser, XML_TRUE) !=
    +        XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING)
    +        fail("Failed to reject late foreign DTD setting");
    +    /* Ditto for the hash salt */
    +    if (XML_SetHashSalt(parser, 0x23456789))
    +        fail("Failed to reject late hash salt change");
    +
    +    /* Now finish the parse */
    +    if (_XML_Parse_SINGLE_BYTES(parser, text2, (int)strlen(text2),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test foreign DTD handling with a failing NotStandalone handler */
    +START_TEST(test_foreign_dtd_not_standalone)
    +{
    +    const char *text =
    +        "\n"
    +        "&entity;";
    +    ExtTest test_data = {
    +        "",
    +        NULL,
    +        NULL
    +    };
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    XML_SetNotStandaloneHandler(parser, reject_not_standalone_handler);
    +    if (XML_UseForeignDTD(parser, XML_TRUE) != XML_ERROR_NONE)
    +        fail("Could not set foreign DTD");
    +    expect_failure(text, XML_ERROR_NOT_STANDALONE,
    +                   "NotStandalonehandler failed to reject");
    +}
    +END_TEST
    +
    +/* Test invalid character in a foreign DTD is faulted */
    +START_TEST(test_invalid_foreign_dtd)
    +{
    +    const char *text =
    +        "\n"
    +        "&entity;";
    +    ExtFaults test_data = {
    +        "$",
    +        "Dollar not faulted",
    +        NULL,
    +        XML_ERROR_INVALID_TOKEN
    +    };
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +    XML_UseForeignDTD(parser, XML_TRUE);
    +    expect_failure(text,
    +                   XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Bad DTD should not have been accepted");
    +}
    +END_TEST
    +
    +/* Test foreign DTD use with a doctype */
    +START_TEST(test_foreign_dtd_with_doctype)
    +{
    +    const char *text1 =
    +        "\n"
    +        "]>\n";
    +    const char *text2 =
    +        "&entity;";
    +    ExtTest test_data = {
    +        "",
    +        NULL,
    +        NULL
    +    };
    +
    +    /* Check hash salt is passed through too */
    +    XML_SetHashSalt(parser, 0x12345678);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    /* Add a default handler to exercise more code paths */
    +    XML_SetDefaultHandler(parser, dummy_default_handler);
    +    if (XML_UseForeignDTD(parser, XML_TRUE) != XML_ERROR_NONE)
    +        fail("Could not set foreign DTD");
    +    if (_XML_Parse_SINGLE_BYTES(parser, text1, (int)strlen(text1),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    /* Ensure that trying to set the DTD after parsing has started
    +     * is faulted, even if it's the same setting.
    +     */
    +    if (XML_UseForeignDTD(parser, XML_TRUE) !=
    +        XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING)
    +        fail("Failed to reject late foreign DTD setting");
    +    /* Ditto for the hash salt */
    +    if (XML_SetHashSalt(parser, 0x23456789))
    +        fail("Failed to reject late hash salt change");
    +
    +    /* Now finish the parse */
    +    if (_XML_Parse_SINGLE_BYTES(parser, text2, (int)strlen(text2),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test XML_UseForeignDTD with no external subset present */
    +static int XMLCALL
    +external_entity_null_loader(XML_Parser UNUSED_P(parser),
    +                            const XML_Char *UNUSED_P(context),
    +                            const XML_Char *UNUSED_P(base),
    +                            const XML_Char *UNUSED_P(systemId),
    +                            const XML_Char *UNUSED_P(publicId))
    +{
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_foreign_dtd_without_external_subset)
    +{
    +    const char *text =
    +        "]>\n"
    +        "&foo;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, NULL);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_null_loader);
    +    XML_UseForeignDTD(parser, XML_TRUE);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +START_TEST(test_empty_foreign_dtd)
    +{
    +    const char *text =
    +        "\n"
    +        "&entity;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_null_loader);
    +    XML_UseForeignDTD(parser, XML_TRUE);
    +    expect_failure(text, XML_ERROR_UNDEFINED_ENTITY,
    +                   "Undefined entity not faulted");
    +}
    +END_TEST
    +
    +/* Test XML Base is set and unset appropriately */
    +START_TEST(test_set_base)
    +{
    +    const XML_Char *old_base;
    +    const XML_Char *new_base = XCS("/local/file/name.xml");
    +
    +    old_base = XML_GetBase(parser);
    +    if (XML_SetBase(parser, new_base) != XML_STATUS_OK)
    +        fail("Unable to set base");
    +    if (xcstrcmp(XML_GetBase(parser), new_base) != 0)
    +        fail("Base setting not correct");
    +    if (XML_SetBase(parser, NULL) != XML_STATUS_OK)
    +        fail("Unable to NULL base");
    +    if (XML_GetBase(parser) != NULL)
    +        fail("Base setting not nulled");
    +    XML_SetBase(parser, old_base);
    +}
    +END_TEST
    +
    +/* Test attribute counts, indexing, etc */
    +typedef struct attrInfo {
    +    const XML_Char *name;
    +    const XML_Char *value;
    +} AttrInfo;
    +
    +typedef struct elementInfo {
    +    const XML_Char *name;
    +    int attr_count;
    +    const XML_Char *id_name;
    +    AttrInfo *attributes;
    +} ElementInfo;
    +
    +static void XMLCALL
    +counting_start_element_handler(void *userData,
    +                               const XML_Char *name,
    +                               const XML_Char **atts)
    +{
    +    ElementInfo *info = (ElementInfo *)userData;
    +    AttrInfo *attr;
    +    int count, id, i;
    +
    +    while (info->name != NULL) {
    +        if (!xcstrcmp(name, info->name))
    +            break;
    +        info++;
    +    }
    +    if (info->name == NULL)
    +        fail("Element not recognised");
    +    /* The attribute count is twice what you might expect.  It is a
    +     * count of items in atts, an array which contains alternating
    +     * attribute names and attribute values.  For the naive user this
    +     * is possibly a little unexpected, but it is what the
    +     * documentation in expat.h tells us to expect.
    +     */
    +    count = XML_GetSpecifiedAttributeCount(parser);
    +    if (info->attr_count * 2 != count) {
    +        fail("Not got expected attribute count");
    +        return;
    +    }
    +    id = XML_GetIdAttributeIndex(parser);
    +    if (id == -1 && info->id_name != NULL) {
    +        fail("ID not present");
    +        return;
    +    }
    +    if (id != -1 && xcstrcmp(atts[id], info->id_name)) {
    +        fail("ID does not have the correct name");
    +        return;
    +    }
    +    for (i = 0; i < info->attr_count; i++) {
    +        attr = info->attributes;
    +        while (attr->name != NULL) {
    +            if (!xcstrcmp(atts[0], attr->name))
    +                break;
    +            attr++;
    +        }
    +        if (attr->name == NULL) {
    +            fail("Attribute not recognised");
    +            return;
    +        }
    +        if (xcstrcmp(atts[1], attr->value)) {
    +            fail("Attribute has wrong value");
    +            return;
    +        }
    +        /* Remember, two entries in atts per attribute (see above) */
    +        atts += 2;
    +    }
    +}
    +
    +START_TEST(test_attributes)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>"
    +        ""
    +        ""
    +        "";
    +    AttrInfo doc_info[] = {
    +        { XCS("a"),  XCS("1") },
    +        { XCS("b"),  XCS("2") },
    +        { XCS("id"), XCS("one") },
    +        { NULL, NULL }
    +    };
    +    AttrInfo tag_info[] = {
    +        { XCS("c"),  XCS("3") },
    +        { NULL, NULL }
    +    };
    +    ElementInfo info[] = {
    +        { XCS("doc"), 3, XCS("id"), NULL },
    +        { XCS("tag"), 1, NULL, NULL },
    +        { NULL, 0, NULL, NULL }
    +    };
    +    info[0].attributes = doc_info;
    +    info[1].attributes = tag_info;
    +
    +    XML_SetStartElementHandler(parser, counting_start_element_handler);
    +    XML_SetUserData(parser, info);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test reset works correctly in the middle of processing an internal
    + * entity.  Exercises some obscure code in XML_ParserReset().
    + */
    +START_TEST(test_reset_in_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "&entity;";
    +    XML_ParsingStatus status;
    +
    +    resumable = XML_TRUE;
    +    XML_SetCharacterDataHandler(parser, clearing_aborting_character_handler);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    XML_GetParsingStatus(parser, &status);
    +    if (status.parsing != XML_SUSPENDED)
    +        fail("Parsing status not SUSPENDED");
    +    XML_ParserReset(parser, NULL);
    +    XML_GetParsingStatus(parser, &status);
    +    if (status.parsing != XML_INITIALIZED)
    +        fail("Parsing status doesn't reset to INITIALIZED");
    +}
    +END_TEST
    +
    +/* Test that resume correctly passes through parse errors */
    +START_TEST(test_resume_invalid_parse)
    +{
    +    const char *text = "Hello");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetDefaultHandler(parser, accumulate_characters);
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test resetting a subordinate parser does exactly nothing */
    +static int XMLCALL
    +external_entity_resetter(XML_Parser parser,
    +                         const XML_Char *context,
    +                         const XML_Char *UNUSED_P(base),
    +                         const XML_Char *UNUSED_P(systemId),
    +                         const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "";
    +    XML_Parser ext_parser;
    +    XML_ParsingStatus status;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_GetParsingStatus(ext_parser, &status);
    +    if (status.parsing != XML_INITIALIZED) {
    +        fail("Parsing status is not INITIALIZED");
    +        return XML_STATUS_ERROR;
    +    }
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR) {
    +        xml_failure(parser);
    +        return XML_STATUS_ERROR;
    +    }
    +    XML_GetParsingStatus(ext_parser, &status);
    +    if (status.parsing != XML_FINISHED) {
    +        fail("Parsing status is not FINISHED");
    +        return XML_STATUS_ERROR;
    +    }
    +    /* Check we can't parse here */
    +    if (XML_Parse(ext_parser, text, (int)strlen(text),
    +                  XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Parsing when finished not faulted");
    +    if (XML_GetErrorCode(ext_parser) != XML_ERROR_FINISHED)
    +        fail("Parsing when finished faulted with wrong code");
    +    XML_ParserReset(ext_parser, NULL);
    +    XML_GetParsingStatus(ext_parser, &status);
    +    if (status.parsing != XML_FINISHED) {
    +        fail("Parsing status not still FINISHED");
    +        return XML_STATUS_ERROR;
    +    }
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_subordinate_reset)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_resetter);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +
    +/* Test suspending a subordinate parser */
    +
    +static void XMLCALL
    +entity_suspending_decl_handler(void *userData,
    +                               const XML_Char *UNUSED_P(name),
    +                               XML_Content *model)
    +{
    +    XML_Parser ext_parser = (XML_Parser)userData;
    +
    +    if (XML_StopParser(ext_parser, XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Attempting to suspend a subordinate parser not faulted");
    +    if (XML_GetErrorCode(ext_parser) != XML_ERROR_SUSPEND_PE)
    +        fail("Suspending subordinate parser get wrong code");
    +    XML_SetElementDeclHandler(ext_parser, NULL);
    +    XML_FreeContentModel(parser, model);
    +}
    +
    +static int XMLCALL
    +external_entity_suspender(XML_Parser parser,
    +                          const XML_Char *context,
    +                          const XML_Char *UNUSED_P(base),
    +                          const XML_Char *UNUSED_P(systemId),
    +                          const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_SetElementDeclHandler(ext_parser, entity_suspending_decl_handler);
    +    XML_SetUserData(ext_parser, ext_parser);
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR) {
    +        xml_failure(ext_parser);
    +        return XML_STATUS_ERROR;
    +    }
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_subordinate_suspend)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_suspender);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test suspending a subordinate parser from an XML declaration */
    +/* Increases code coverage of the tests */
    +static void XMLCALL
    +entity_suspending_xdecl_handler(void *userData,
    +                                const XML_Char *UNUSED_P(version),
    +                                const XML_Char *UNUSED_P(encoding),
    +                                int UNUSED_P(standalone))
    +{
    +    XML_Parser ext_parser = (XML_Parser)userData;
    +
    +    XML_StopParser(ext_parser, resumable);
    +    XML_SetXmlDeclHandler(ext_parser, NULL);
    +}
    +
    +static int XMLCALL
    +external_entity_suspend_xmldecl(XML_Parser parser,
    +                                const XML_Char *context,
    +                                const XML_Char *UNUSED_P(base),
    +                                const XML_Char *UNUSED_P(systemId),
    +                                const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "";
    +    XML_Parser ext_parser;
    +    XML_ParsingStatus status;
    +    enum XML_Status rc;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_SetXmlDeclHandler(ext_parser, entity_suspending_xdecl_handler);
    +    XML_SetUserData(ext_parser, ext_parser);
    +    rc = _XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text), XML_TRUE);
    +    XML_GetParsingStatus(ext_parser, &status);
    +    if (resumable) {
    +        if (rc == XML_STATUS_ERROR)
    +            xml_failure(ext_parser);
    +        if (status.parsing != XML_SUSPENDED)
    +            fail("Ext Parsing status not SUSPENDED");
    +    } else {
    +        if (rc != XML_STATUS_ERROR)
    +            fail("Ext parsing not aborted");
    +        if (XML_GetErrorCode(ext_parser) != XML_ERROR_ABORTED)
    +            xml_failure(ext_parser);
    +        if (status.parsing != XML_FINISHED)
    +            fail("Ext Parsing status not FINISHED");
    +    }
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_subordinate_xdecl_suspend)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&entity;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_suspend_xmldecl);
    +    resumable = XML_TRUE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +START_TEST(test_subordinate_xdecl_abort)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&entity;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_suspend_xmldecl);
    +    resumable = XML_FALSE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test external entity fault handling with suspension */
    +static int XMLCALL
    +external_entity_suspending_faulter(XML_Parser parser,
    +                                   const XML_Char *context,
    +                                   const XML_Char *UNUSED_P(base),
    +                                   const XML_Char *UNUSED_P(systemId),
    +                                   const XML_Char *UNUSED_P(publicId))
    +{
    +    XML_Parser ext_parser;
    +    ExtFaults *fault = (ExtFaults *)XML_GetUserData(parser);
    +    void *buffer;
    +    int parse_len = (int)strlen(fault->parse_text);
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_SetXmlDeclHandler(ext_parser, entity_suspending_xdecl_handler);
    +    XML_SetUserData(ext_parser, ext_parser);
    +    resumable = XML_TRUE;
    +    buffer = XML_GetBuffer(ext_parser, parse_len);
    +    if (buffer == NULL)
    +        fail("Could not allocate parse buffer");
    +    memcpy(buffer, fault->parse_text, parse_len);
    +    if (XML_ParseBuffer(ext_parser, parse_len,
    +                        XML_FALSE) != XML_STATUS_SUSPENDED)
    +        fail("XML declaration did not suspend");
    +    if (XML_ResumeParser(ext_parser) != XML_STATUS_OK)
    +        xml_failure(ext_parser);
    +    if (XML_ParseBuffer(ext_parser, 0, XML_TRUE) != XML_STATUS_ERROR)
    +        fail(fault->fail_text);
    +    if (XML_GetErrorCode(ext_parser) != fault->error)
    +        xml_failure(ext_parser);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_ERROR;
    +}
    +
    +START_TEST(test_ext_entity_invalid_suspended_parse)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtFaults faults[] = {
    +        {
    +            "<",
    +            "Incomplete element declaration not faulted",
    +            NULL,
    +            XML_ERROR_UNCLOSED_TOKEN
    +        },
    +        {
    +            /* First two bytes of a three-byte char */
    +            "\xe2\x82",
    +            "Incomplete character not faulted",
    +            NULL,
    +            XML_ERROR_PARTIAL_CHAR
    +        },
    +        { NULL, NULL, NULL, XML_ERROR_NONE }
    +    };
    +    ExtFaults *fault;
    +
    +    for (fault = &faults[0]; fault->parse_text != NULL; fault++) {
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser,
    +                                        external_entity_suspending_faulter);
    +        XML_SetUserData(parser, fault);
    +        expect_failure(text,
    +                       XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                       "Parser did not report external entity error");
    +        XML_ParserReset(parser, NULL);
    +    }
    +}
    +END_TEST
    +
    +
    +
    +/* Test setting an explicit encoding */
    +START_TEST(test_explicit_encoding)
    +{
    +    const char *text1 = "Hello ";
    +    const char *text2 = " World";
    +
    +    /* Just check that we can set the encoding to NULL before starting */
    +    if (XML_SetEncoding(parser, NULL) != XML_STATUS_OK)
    +        fail("Failed to initialise encoding to NULL");
    +    /* Say we are UTF-8 */
    +    if (XML_SetEncoding(parser, XCS("utf-8")) != XML_STATUS_OK)
    +        fail("Failed to set explicit encoding");
    +    if (_XML_Parse_SINGLE_BYTES(parser, text1, (int)strlen(text1),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    /* Try to switch encodings mid-parse */
    +    if (XML_SetEncoding(parser, XCS("us-ascii")) != XML_STATUS_ERROR)
    +        fail("Allowed encoding change");
    +    if (_XML_Parse_SINGLE_BYTES(parser, text2, (int)strlen(text2),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    /* Try now the parse is over */
    +    if (XML_SetEncoding(parser, NULL) != XML_STATUS_OK)
    +        fail("Failed to unset encoding");
    +}
    +END_TEST
    +
    +
    +/* Test handling of trailing CR (rather than newline) */
    +static void XMLCALL
    +cr_cdata_handler(void *userData, const XML_Char *s, int len)
    +{
    +    int *pfound = (int *)userData;
    +
    +    /* Internal processing turns the CR into a newline for the
    +     * character data handler, but not for the default handler
    +     */
    +    if (len == 1 && (*s == XCS('\n') || *s == XCS('\r')))
    +        *pfound = 1;
    +}
    +
    +START_TEST(test_trailing_cr)
    +{
    +    const char *text = "\r";
    +    int found_cr;
    +
    +    /* Try with a character handler, for code coverage */
    +    XML_SetCharacterDataHandler(parser, cr_cdata_handler);
    +    XML_SetUserData(parser, &found_cr);
    +    found_cr = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_OK)
    +        fail("Failed to fault unclosed doc");
    +    if (found_cr == 0)
    +        fail("Did not catch the carriage return");
    +    XML_ParserReset(parser, NULL);
    +
    +    /* Now with a default handler instead */
    +    XML_SetDefaultHandler(parser, cr_cdata_handler);
    +    XML_SetUserData(parser, &found_cr);
    +    found_cr = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_OK)
    +        fail("Failed to fault unclosed doc");
    +    if (found_cr == 0)
    +        fail("Did not catch default carriage return");
    +}
    +END_TEST
    +
    +/* Test trailing CR in an external entity parse */
    +static int XMLCALL
    +external_entity_cr_catcher(XML_Parser parser,
    +                           const XML_Char *context,
    +                           const XML_Char *UNUSED_P(base),
    +                           const XML_Char *UNUSED_P(systemId),
    +                           const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "\r";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_SetCharacterDataHandler(ext_parser, cr_cdata_handler);
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(ext_parser);
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +static int XMLCALL
    +external_entity_bad_cr_catcher(XML_Parser parser,
    +                               const XML_Char *context,
    +                               const XML_Char *UNUSED_P(base),
    +                               const XML_Char *UNUSED_P(systemId),
    +                               const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "\r";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_SetCharacterDataHandler(ext_parser, cr_cdata_handler);
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_OK)
    +        fail("Async entity error not caught");
    +    if (XML_GetErrorCode(ext_parser) != XML_ERROR_ASYNC_ENTITY)
    +        xml_failure(ext_parser);
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ext_entity_trailing_cr)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    int found_cr;
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_cr_catcher);
    +    XML_SetUserData(parser, &found_cr);
    +    found_cr = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_OK)
    +        xml_failure(parser);
    +    if (found_cr == 0)
    +        fail("No carriage return found");
    +    XML_ParserReset(parser, NULL);
    +
    +    /* Try again with a different trailing CR */
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_bad_cr_catcher);
    +    XML_SetUserData(parser, &found_cr);
    +    found_cr = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_OK)
    +        xml_failure(parser);
    +    if (found_cr == 0)
    +        fail("No carriage return found");
    +}
    +END_TEST
    +
    +/* Test handling of trailing square bracket */
    +static void XMLCALL
    +rsqb_handler(void *userData, const XML_Char *s, int len)
    +{
    +    int *pfound = (int *)userData;
    +
    +    if (len == 1 && *s == XCS(']'))
    +        *pfound = 1;
    +}
    +
    +START_TEST(test_trailing_rsqb)
    +{
    +    const char *text8 = "]";
    +    const char text16[] = "\xFF\xFE<\000d\000o\000c\000>\000]\000";
    +    int found_rsqb;
    +    int text8_len = (int)strlen(text8);
    +
    +    XML_SetCharacterDataHandler(parser, rsqb_handler);
    +    XML_SetUserData(parser, &found_rsqb);
    +    found_rsqb = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text8, text8_len,
    +                                XML_TRUE) == XML_STATUS_OK)
    +        fail("Failed to fault unclosed doc");
    +    if (found_rsqb == 0)
    +        fail("Did not catch the right square bracket");
    +
    +    /* Try again with a different encoding */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetCharacterDataHandler(parser, rsqb_handler);
    +    XML_SetUserData(parser, &found_rsqb);
    +    found_rsqb = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text16, (int)sizeof(text16)-1,
    +                                XML_TRUE) == XML_STATUS_OK)
    +        fail("Failed to fault unclosed doc");
    +    if (found_rsqb == 0)
    +        fail("Did not catch the right square bracket");
    +
    +    /* And finally with a default handler */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetDefaultHandler(parser, rsqb_handler);
    +    XML_SetUserData(parser, &found_rsqb);
    +    found_rsqb = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text16, (int)sizeof(text16)-1,
    +                                XML_TRUE) == XML_STATUS_OK)
    +        fail("Failed to fault unclosed doc");
    +    if (found_rsqb == 0)
    +        fail("Did not catch the right square bracket");
    +}
    +END_TEST
    +
    +/* Test trailing right square bracket in an external entity parse */
    +static int XMLCALL
    +external_entity_rsqb_catcher(XML_Parser parser,
    +                             const XML_Char *context,
    +                             const XML_Char *UNUSED_P(base),
    +                             const XML_Char *UNUSED_P(systemId),
    +                             const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "]";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_SetCharacterDataHandler(ext_parser, rsqb_handler);
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Async entity error not caught");
    +    if (XML_GetErrorCode(ext_parser) != XML_ERROR_ASYNC_ENTITY)
    +        xml_failure(ext_parser);
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ext_entity_trailing_rsqb)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    int found_rsqb;
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_rsqb_catcher);
    +    XML_SetUserData(parser, &found_rsqb);
    +    found_rsqb = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_OK)
    +        xml_failure(parser);
    +    if (found_rsqb == 0)
    +        fail("No right square bracket found");
    +}
    +END_TEST
    +
    +/* Test CDATA handling in an external entity */
    +static int XMLCALL
    +external_entity_good_cdata_ascii(XML_Parser parser,
    +                                 const XML_Char *context,
    +                                 const XML_Char *UNUSED_P(base),
    +                                 const XML_Char *UNUSED_P(systemId),
    +                                 const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text =
    +        "Hello, world!]]>";
    +    const XML_Char *expected = XCS("Hello, world!");
    +    CharData storage;
    +    XML_Parser ext_parser;
    +
    +    CharData_Init(&storage);
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    XML_SetUserData(ext_parser, &storage);
    +    XML_SetCharacterDataHandler(ext_parser, accumulate_characters);
    +
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(ext_parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ext_entity_good_cdata)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_good_cdata_ascii);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_OK)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test user parameter settings */
    +/* Variable holding the expected handler userData */
    +static void *handler_data = NULL;
    +/* Count of the number of times the comment handler has been invoked */
    +static int comment_count = 0;
    +/* Count of the number of skipped entities */
    +static int skip_count = 0;
    +/* Count of the number of times the XML declaration handler is invoked */
    +static int xdecl_count = 0;
    +
    +static void XMLCALL
    +xml_decl_handler(void *userData,
    +                 const XML_Char *UNUSED_P(version),
    +                 const XML_Char *UNUSED_P(encoding),
    +                 int standalone)
    +{
    +    if (userData != handler_data)
    +        fail("User data (xml decl) not correctly set");
    +    if (standalone != -1)
    +        fail("Standalone not flagged as not present in XML decl");
    +    xdecl_count++;
    +}
    +
    +static void XMLCALL
    +param_check_skip_handler(void *userData,
    +                         const XML_Char *UNUSED_P(entityName),
    +                         int UNUSED_P(is_parameter_entity))
    +{
    +    if (userData != handler_data)
    +        fail("User data (skip) not correctly set");
    +    skip_count++;
    +}
    +
    +static void XMLCALL
    +data_check_comment_handler(void *userData, const XML_Char *UNUSED_P(data))
    +{
    +    /* Check that the userData passed through is what we expect */
    +    if (userData != handler_data)
    +        fail("User data (parser) not correctly set");
    +    /* Check that the user data in the parser is appropriate */
    +    if (XML_GetUserData(userData) != (void *)1)
    +        fail("User data in parser not correctly set");
    +    comment_count++;
    +}
    +
    +static int XMLCALL
    +external_entity_param_checker(XML_Parser parser,
    +                              const XML_Char *context,
    +                              const XML_Char *UNUSED_P(base),
    +                              const XML_Char *UNUSED_P(systemId),
    +                              const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    handler_data = ext_parser;
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR) {
    +        xml_failure(parser);
    +        return XML_STATUS_ERROR;
    +    }
    +    handler_data = parser;
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_user_parameters)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "&entity;";
    +    const char *epilog =
    +        "\n"
    +        "";
    +
    +    comment_count = 0;
    +    skip_count = 0;
    +    xdecl_count = 0;
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetXmlDeclHandler(parser, xml_decl_handler);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_param_checker);
    +    XML_SetCommentHandler(parser, data_check_comment_handler);
    +    XML_SetSkippedEntityHandler(parser, param_check_skip_handler);
    +    XML_UseParserAsHandlerArg(parser);
    +    XML_SetUserData(parser, (void *)1);
    +    handler_data = parser;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (comment_count != 2)
    +        fail("Comment handler not invoked enough times");
    +    /* Ensure we can't change policy mid-parse */
    +    if (XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_NEVER))
    +        fail("Changed param entity parsing policy while parsing");
    +    if (_XML_Parse_SINGLE_BYTES(parser, epilog, (int)strlen(epilog),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (comment_count != 3)
    +        fail("Comment handler not invoked enough times");
    +    if (skip_count != 1)
    +        fail("Skip handler not invoked enough times");
    +    if (xdecl_count != 1)
    +        fail("XML declaration handler not invoked");
    +}
    +END_TEST
    +
    +/* Test that an explicit external entity handler argument replaces
    + * the parser as the first argument.
    + *
    + * We do not call the first parameter to the external entity handler
    + * 'parser' for once, since the first time the handler is called it
    + * will actually be a text string.  We need to be able to access the
    + * global 'parser' variable to create our external entity parser from,
    + * since there are code paths we need to ensure get executed.
    + */
    +static int XMLCALL
    +external_entity_ref_param_checker(XML_Parser parameter,
    +                                  const XML_Char *context,
    +                                  const XML_Char *UNUSED_P(base),
    +                                  const XML_Char *UNUSED_P(systemId),
    +                                  const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "";
    +    XML_Parser ext_parser;
    +
    +    if ((void *)parameter != handler_data)
    +        fail("External entity ref handler parameter not correct");
    +
    +    /* Here we use the global 'parser' variable */
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(ext_parser);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ext_entity_ref_parameter)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_ref_param_checker);
    +    /* Set a handler arg that is not NULL and not parser (which is
    +     * what NULL would cause to be passed.
    +     */
    +    XML_SetExternalEntityRefHandlerArg(parser, (void *)text);
    +    handler_data = (void *)text;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    /* Now try again with unset args */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_ref_param_checker);
    +    XML_SetExternalEntityRefHandlerArg(parser, NULL);
    +    handler_data = (void *)parser;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test the parsing of an empty string */
    +START_TEST(test_empty_parse)
    +{
    +    const char *text = "";
    +    const char *partial = "";
    +
    +    if (XML_Parse(parser, NULL, 0, XML_FALSE) == XML_STATUS_ERROR)
    +        fail("Parsing empty string faulted");
    +    if (XML_Parse(parser, NULL, 0, XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Parsing final empty string not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_NO_ELEMENTS)
    +        fail("Parsing final empty string faulted for wrong reason");
    +
    +    /* Now try with valid text before the empty end */
    +    XML_ParserReset(parser, NULL);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (XML_Parse(parser, NULL, 0, XML_TRUE) == XML_STATUS_ERROR)
    +        fail("Parsing final empty string faulted");
    +
    +    /* Now try with invalid text before the empty end */
    +    XML_ParserReset(parser, NULL);
    +    if (_XML_Parse_SINGLE_BYTES(parser, partial, (int)strlen(partial),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (XML_Parse(parser, NULL, 0, XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Parsing final incomplete empty string not faulted");
    +}
    +END_TEST
    +
    +/* Test odd corners of the XML_GetBuffer interface */
    +static enum XML_Status
    +get_feature(enum XML_FeatureEnum feature_id, long *presult)
    +{
    +    const XML_Feature *feature = XML_GetFeatureList();
    +
    +    if (feature == NULL)
    +        return XML_STATUS_ERROR;
    +    for (; feature->feature != XML_FEATURE_END; feature++) {
    +        if (feature->feature == feature_id) {
    +            *presult = feature->value;
    +            return XML_STATUS_OK;
    +        }
    +    }
    +    return XML_STATUS_ERROR;
    +}
    +
    +/* Having an element name longer than 1024 characters exercises some
    + * of the pool allocation code in the parser that otherwise does not
    + * get executed.  The count at the end of the line is the number of
    + * characters (bytes) in the element name by that point.x
    + */
    +static const char *get_buffer_test_text =
    +        "\n"
    +START_TEST(test_byte_info_at_error)
    +{
    +    const char *text = PRE_ERROR_STR POST_ERROR_STR;
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_OK)
    +        fail("Syntax error not faulted");
    +    if (XML_GetCurrentByteCount(parser) != 0)
    +        fail("Error byte count incorrect");
    +    if (XML_GetCurrentByteIndex(parser) != strlen(PRE_ERROR_STR))
    +        fail("Error byte index incorrect");
    +}
    +END_TEST
    +#undef PRE_ERROR_STR
    +#undef POST_ERROR_STR
    +
    +/* Test position information in handler */
    +typedef struct ByteTestData {
    +    int start_element_len;
    +    int cdata_len;
    +    int total_string_len;
    +} ByteTestData;
    +
    +static void
    +byte_character_handler(void *userData,
    +                       const XML_Char *UNUSED_P(s),
    +                       int len)
    +{
    +#ifdef XML_CONTEXT_BYTES
    +    int offset, size;
    +    const char *buffer;
    +    ByteTestData *data = (ByteTestData *)userData;
    +
    +    buffer = XML_GetInputContext(parser, &offset, &size);
    +    if (buffer == NULL)
    +        fail("Failed to get context buffer");
    +    if (offset != data->start_element_len)
    +        fail("Context offset in unexpected position");
    +    if (len != data->cdata_len)
    +        fail("CDATA length reported incorrectly");
    +    if (size != data->total_string_len)
    +        fail("Context size is not full buffer");
    +    if (XML_GetCurrentByteIndex(parser) != offset)
    +        fail("Character byte index incorrect");
    +    if (XML_GetCurrentByteCount(parser) != len)
    +        fail("Character byte count incorrect");
    +#else
    +    (void)userData;
    +    (void)len;
    +#endif
    +}
    +
    +#define START_ELEMENT ""
    +#define CDATA_TEXT    "Hello"
    +#define END_ELEMENT   ""
    +START_TEST(test_byte_info_at_cdata)
    +{
    +    const char *text = START_ELEMENT CDATA_TEXT END_ELEMENT;
    +    int offset, size;
    +    ByteTestData data;
    +
    +    /* Check initial context is empty */
    +    if (XML_GetInputContext(parser, &offset, &size) != NULL)
    +        fail("Unexpected context at start of parse");
    +
    +    data.start_element_len = (int)strlen(START_ELEMENT);
    +    data.cdata_len = (int)strlen(CDATA_TEXT);
    +    data.total_string_len = (int)strlen(text);
    +    XML_SetCharacterDataHandler(parser, byte_character_handler);
    +    XML_SetUserData(parser, &data);
    +    if (XML_Parse(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_OK)
    +        xml_failure(parser);
    +}
    +END_TEST
    +#undef START_ELEMENT
    +#undef CDATA_TEXT
    +#undef END_ELEMENT
    +
    +/* Test predefined entities are correctly recognised */
    +START_TEST(test_predefined_entities)
    +{
    +    const char *text = "<>&"'";
    +    const XML_Char *expected = XCS("<>&"'");
    +    const XML_Char *result = XCS("<>&\"'");
    +    CharData storage;
    +
    +    XML_SetDefaultHandler(parser, accumulate_characters);
    +    /* run_character_check uses XML_SetCharacterDataHandler(), which
    +     * unfortunately heads off a code path that we need to exercise.
    +     */
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    /* The default handler doesn't translate the entities */
    +    CharData_CheckXMLChars(&storage, expected);
    +
    +    /* Now try again and check the translation */
    +    XML_ParserReset(parser, NULL);
    +    run_character_check(text, result);
    +}
    +END_TEST
    +
    +/* Regression test that an invalid tag in an external parameter
    + * reference in an external DTD is correctly faulted.
    + *
    + * Only a few specific tags are legal in DTDs ignoring comments and
    + * processing instructions, all of which begin with an exclamation
    + * mark.  "" is not one of them, so the parser should raise an
    + * error on encountering it.
    + */
    +static int XMLCALL
    +external_entity_param(XML_Parser parser,
    +                      const XML_Char *context,
    +                      const XML_Char *UNUSED_P(base),
    +                      const XML_Char *systemId,
    +                      const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text1 =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "%e1;\n";
    +    const char *text2 =
    +        "\n"
    +        "\n";
    +    XML_Parser ext_parser;
    +
    +    if (systemId == NULL)
    +        return XML_STATUS_OK;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +
    +    if (!xcstrcmp(systemId, XCS("004-1.ent"))) {
    +        if (_XML_Parse_SINGLE_BYTES(ext_parser, text1, (int)strlen(text1),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            fail("Inner DTD with invalid tag not rejected");
    +        if (XML_GetErrorCode(ext_parser) != XML_ERROR_EXTERNAL_ENTITY_HANDLING)
    +            xml_failure(ext_parser);
    +    }
    +    else if (!xcstrcmp(systemId, XCS("004-2.ent"))) {
    +        if (_XML_Parse_SINGLE_BYTES(ext_parser, text2, (int)strlen(text2),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            fail("Invalid tag in external param not rejected");
    +        if (XML_GetErrorCode(ext_parser) != XML_ERROR_SYNTAX)
    +            xml_failure(ext_parser);
    +    } else {
    +        fail("Unknown system ID");
    +    }
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_ERROR;
    +}
    +
    +START_TEST(test_invalid_tag_in_dtd)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_param);
    +    expect_failure(text, XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Invalid tag IN DTD external param not rejected");
    +}
    +END_TEST
    +
    +/* Test entities not quite the predefined ones are not mis-recognised */
    +START_TEST(test_not_predefined_entities)
    +{
    +    const char *text[] = {
    +        "&pt;",
    +        "&amo;",
    +        "&quid;",
    +        "&apod;",
    +        NULL
    +    };
    +    int i = 0;
    +
    +    while (text[i] != NULL) {
    +        expect_failure(text[i], XML_ERROR_UNDEFINED_ENTITY,
    +                       "Undefined entity not rejected");
    +        XML_ParserReset(parser, NULL);
    +        i++;
    +    }
    +}
    +END_TEST
    +
    +/* Test conditional inclusion (IGNORE) */
    +static int XMLCALL
    +external_entity_load_ignore(XML_Parser parser,
    +                            const XML_Char *context,
    +                            const XML_Char *UNUSED_P(base),
    +                            const XML_Char *UNUSED_P(systemId),
    +                            const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = "]]>";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ignore_section)
    +{
    +    const char *text =
    +        "\n"
    +        "&entity;";
    +    const XML_Char *expected =
    +        XCS("]]>\n&entity;");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_load_ignore);
    +    XML_SetDefaultHandler(parser, accumulate_characters);
    +    XML_SetStartDoctypeDeclHandler(parser, dummy_start_doctype_handler);
    +    XML_SetEndDoctypeDeclHandler(parser, dummy_end_doctype_handler);
    +    XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +    XML_SetStartElementHandler(parser, dummy_start_element);
    +    XML_SetEndElementHandler(parser, dummy_end_element);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +static int XMLCALL
    +external_entity_load_ignore_utf16(XML_Parser parser,
    +                                  const XML_Char *context,
    +                                  const XML_Char *UNUSED_P(base),
    +                                  const XML_Char *UNUSED_P(systemId),
    +                                  const XML_Char *UNUSED_P(publicId))
    +{
    +    const char text[] =
    +        /* ]]> */
    +        "<\0!\0[\0I\0G\0N\0O\0R\0E\0[\0"
    +        "<\0!\0E\0L\0E\0M\0E\0N\0T\0 \0e\0 \0"
    +        "(\0#\0P\0C\0D\0A\0T\0A\0)\0*\0>\0]\0]\0>\0";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ignore_section_utf16)
    +{
    +    const char text[] =
    +        /*  */
    +        "<\0!\0D\0O\0C\0T\0Y\0P\0E\0 \0d\0 "
    +        "\0S\0Y\0S\0T\0E\0M\0 \0'\0s\0'\0>\0\n\0"
    +        /* &en; */
    +        "<\0d\0>\0<\0e\0>\0&\0e\0n\0;\0<\0/\0e\0>\0<\0/\0d\0>\0";
    +    const XML_Char *expected =
    +        XCS("]]>\n&en;");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_load_ignore_utf16);
    +    XML_SetDefaultHandler(parser, accumulate_characters);
    +    XML_SetStartDoctypeDeclHandler(parser, dummy_start_doctype_handler);
    +    XML_SetEndDoctypeDeclHandler(parser, dummy_end_doctype_handler);
    +    XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +    XML_SetStartElementHandler(parser, dummy_start_element);
    +    XML_SetEndElementHandler(parser, dummy_end_element);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +static int XMLCALL
    +external_entity_load_ignore_utf16_be(XML_Parser parser,
    +                                     const XML_Char *context,
    +                                     const XML_Char *UNUSED_P(base),
    +                                     const XML_Char *UNUSED_P(systemId),
    +                                     const XML_Char *UNUSED_P(publicId))
    +{
    +    const char text[] =
    +        /* ]]> */
    +        "\0<\0!\0[\0I\0G\0N\0O\0R\0E\0["
    +        "\0<\0!\0E\0L\0E\0M\0E\0N\0T\0 \0e\0 "
    +        "\0(\0#\0P\0C\0D\0A\0T\0A\0)\0*\0>\0]\0]\0>";
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ignore_section_utf16_be)
    +{
    +    const char text[] =
    +        /*  */
    +        "\0<\0!\0D\0O\0C\0T\0Y\0P\0E\0 \0d\0 "
    +        "\0S\0Y\0S\0T\0E\0M\0 \0'\0s\0'\0>\0\n"
    +        /* &en; */
    +        "\0<\0d\0>\0<\0e\0>\0&\0e\0n\0;\0<\0/\0e\0>\0<\0/\0d\0>";
    +    const XML_Char *expected =
    +        XCS("]]>\n&en;");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_load_ignore_utf16_be);
    +    XML_SetDefaultHandler(parser, accumulate_characters);
    +    XML_SetStartDoctypeDeclHandler(parser, dummy_start_doctype_handler);
    +    XML_SetEndDoctypeDeclHandler(parser, dummy_end_doctype_handler);
    +    XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +    XML_SetStartElementHandler(parser, dummy_start_element);
    +    XML_SetEndElementHandler(parser, dummy_end_element);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test mis-formatted conditional exclusion */
    +START_TEST(test_bad_ignore_section)
    +{
    +    const char *text =
    +        "\n"
    +        "&entity;";
    +    ExtFaults faults[] = {
    +        {
    +            "",
    +            "Invalid XML character not faulted",
    +            NULL,
    +            XML_ERROR_INVALID_TOKEN
    +        },
    +        {
    +            /* FIrst two bytes of a three-byte char */
    +            "parse_text != NULL; fault++) {
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +        XML_SetUserData(parser, fault);
    +        expect_failure(text, XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                       "Incomplete IGNORE section not failed");
    +        XML_ParserReset(parser, NULL);
    +    }
    +}
    +END_TEST
    +
    +/* Test recursive parsing */
    +static int XMLCALL
    +external_entity_valuer(XML_Parser parser,
    +                       const XML_Char *context,
    +                       const XML_Char *UNUSED_P(base),
    +                       const XML_Char *systemId,
    +                       const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text1 =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "%e1;\n";
    +    XML_Parser ext_parser;
    +
    +    if (systemId == NULL)
    +        return XML_STATUS_OK;
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (!xcstrcmp(systemId, XCS("004-1.ent"))) {
    +        if (_XML_Parse_SINGLE_BYTES(ext_parser, text1, (int)strlen(text1),
    +                                    XML_TRUE) == XML_STATUS_ERROR)
    +            xml_failure(ext_parser);
    +    }
    +    else if (!xcstrcmp(systemId, XCS("004-2.ent"))) {
    +        ExtFaults *fault = (ExtFaults *)XML_GetUserData(parser);
    +        enum XML_Status status;
    +        enum XML_Error error;
    +
    +        status = _XML_Parse_SINGLE_BYTES(ext_parser,
    +                                         fault->parse_text,
    +                                         (int)strlen(fault->parse_text),
    +                                         XML_TRUE);
    +        if (fault->error == XML_ERROR_NONE) {
    +            if (status == XML_STATUS_ERROR)
    +                xml_failure(ext_parser);
    +        } else {
    +            if (status != XML_STATUS_ERROR)
    +                fail(fault->fail_text);
    +            error = XML_GetErrorCode(ext_parser);
    +            if (error != fault->error &&
    +                (fault->error != XML_ERROR_XML_DECL ||
    +                 error != XML_ERROR_TEXT_DECL))
    +                xml_failure(ext_parser);
    +        }
    +    }
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_external_entity_values)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +    ExtFaults data_004_2[] = {
    +        {
    +            "",
    +            NULL,
    +            NULL,
    +            XML_ERROR_NONE
    +        },
    +        {
    +            "",
    +            "Invalid token not faulted",
    +            NULL,
    +            XML_ERROR_INVALID_TOKEN
    +        },
    +        {
    +            "'wombat",
    +            "Unterminated string not faulted",
    +            NULL,
    +            XML_ERROR_UNCLOSED_TOKEN
    +        },
    +        {
    +            "\xe2\x82",
    +            "Partial UTF-8 character not faulted",
    +            NULL,
    +            XML_ERROR_PARTIAL_CHAR
    +        },
    +        {
    +            "\n",
    +            NULL,
    +            NULL,
    +            XML_ERROR_NONE
    +        },
    +        {
    +            "",
    +            "Malformed XML declaration not faulted",
    +            NULL,
    +            XML_ERROR_XML_DECL
    +        },
    +        {
    +            /* UTF-8 BOM */
    +            "\xEF\xBB\xBF",
    +            NULL,
    +            NULL,
    +            XML_ERROR_NONE
    +        },
    +        {
    +            "\n$",
    +            "Invalid token after text declaration not faulted",
    +            NULL,
    +            XML_ERROR_INVALID_TOKEN
    +        },
    +        {
    +            "\n'wombat",
    +            "Unterminated string after text decl not faulted",
    +            NULL,
    +            XML_ERROR_UNCLOSED_TOKEN
    +        },
    +        {
    +            "\n\xe2\x82",
    +            "Partial UTF-8 character after text decl not faulted",
    +            NULL,
    +            XML_ERROR_PARTIAL_CHAR
    +        },
    +        {
    +            "%e1;",
    +            "Recursive parameter entity not faulted",
    +            NULL,
    +            XML_ERROR_RECURSIVE_ENTITY_REF
    +        },
    +        { NULL, NULL, NULL, XML_ERROR_NONE }
    +    };
    +    int i;
    +
    +    for (i = 0; data_004_2[i].parse_text != NULL; i++) {
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_valuer);
    +        XML_SetUserData(parser, &data_004_2[i]);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) == XML_STATUS_ERROR)
    +            xml_failure(parser);
    +        XML_ParserReset(parser, NULL);
    +    }
    +}
    +END_TEST
    +
    +/* Test the recursive parse interacts with a not standalone handler */
    +static int XMLCALL
    +external_entity_not_standalone(XML_Parser parser,
    +                               const XML_Char *context,
    +                               const XML_Char *UNUSED_P(base),
    +                               const XML_Char *systemId,
    +                               const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text1 =
    +        "\n"
    +        "\n"
    +        "%e1;\n";
    +    const char *text2 = "";
    +    XML_Parser ext_parser;
    +
    +    if (systemId == NULL)
    +        return XML_STATUS_OK;
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (!xcstrcmp(systemId, XCS("foo"))) {
    +        XML_SetNotStandaloneHandler(ext_parser,
    +                                    reject_not_standalone_handler);
    +        if (_XML_Parse_SINGLE_BYTES(ext_parser, text1, (int)strlen(text1),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            fail("Expected not standalone rejection");
    +        if (XML_GetErrorCode(ext_parser) != XML_ERROR_NOT_STANDALONE)
    +            xml_failure(ext_parser);
    +        XML_SetNotStandaloneHandler(ext_parser, NULL);
    +        XML_ParserFree(ext_parser);
    +        return XML_STATUS_ERROR;
    +    }
    +    else if (!xcstrcmp(systemId, XCS("bar"))) {
    +        if (_XML_Parse_SINGLE_BYTES(ext_parser, text2, (int)strlen(text2),
    +                                    XML_TRUE) == XML_STATUS_ERROR)
    +            xml_failure(ext_parser);
    +    }
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ext_entity_not_standalone)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_not_standalone);
    +    expect_failure(text, XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Standalone rejection not caught");
    +}
    +END_TEST
    +
    +static int XMLCALL
    +external_entity_value_aborter(XML_Parser parser,
    +                              const XML_Char *context,
    +                              const XML_Char *UNUSED_P(base),
    +                              const XML_Char *systemId,
    +                              const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text1 =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "%e1;\n";
    +    const char *text2 =
    +        "";
    +    XML_Parser ext_parser;
    +
    +    if (systemId == NULL)
    +        return XML_STATUS_OK;
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +    if (!xcstrcmp(systemId, XCS("004-1.ent"))) {
    +        if (_XML_Parse_SINGLE_BYTES(ext_parser, text1, (int)strlen(text1),
    +                                    XML_TRUE) == XML_STATUS_ERROR)
    +            xml_failure(ext_parser);
    +    }
    +    if (!xcstrcmp(systemId, XCS("004-2.ent"))) {
    +        XML_SetXmlDeclHandler(ext_parser, entity_suspending_xdecl_handler);
    +        XML_SetUserData(ext_parser, ext_parser);
    +        if (_XML_Parse_SINGLE_BYTES(ext_parser, text2, (int)strlen(text2),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            fail("Aborted parse not faulted");
    +        if (XML_GetErrorCode(ext_parser) != XML_ERROR_ABORTED)
    +            xml_failure(ext_parser);
    +    }
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_ext_entity_value_abort)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_value_aborter);
    +    resumable = XML_FALSE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +START_TEST(test_bad_public_doctype)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "";
    +
    +    /* Setting a handler provokes a particular code path */
    +    XML_SetDoctypeDeclHandler(parser,
    +                              dummy_start_doctype_handler,
    +                              dummy_end_doctype_handler);
    +    expect_failure(text, XML_ERROR_PUBLICID, "Bad Public ID not failed");
    +}
    +END_TEST
    +
    +/* Test based on ibm/valid/P32/ibm32v04.xml */
    +START_TEST(test_attribute_enum_value)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "This is a \n      \n\nyellow tiger";
    +    ExtTest dtd_data = {
    +        "\n"
    +        "\n"
    +        "",
    +        NULL,
    +        NULL
    +    };
    +    const XML_Char *expected = XCS("This is a \n      \n\nyellow tiger");
    +
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    XML_SetUserData(parser, &dtd_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    /* An attribute list handler provokes a different code path */
    +    XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
    +    run_ext_character_check(text, &dtd_data, expected);
    +}
    +END_TEST
    +
    +/* Slightly bizarrely, the library seems to silently ignore entity
    + * definitions for predefined entities, even when they are wrong.  The
    + * language of the XML 1.0 spec is somewhat unhelpful as to what ought
    + * to happen, so this is currently treated as acceptable.
    + */
    +START_TEST(test_predefined_entity_redefinition)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "'";
    +    run_character_check(text, XCS("'"));
    +}
    +END_TEST
    +
    +/* Test that the parser stops processing the DTD after an unresolved
    + * parameter entity is encountered.
    + */
    +START_TEST(test_dtd_stop_processing)
    +{
    +    const char *text =
    +        "\n"
    +        "]>";
    +
    +    XML_SetEntityDeclHandler(parser, dummy_entity_decl_handler);
    +    dummy_handler_flags = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (dummy_handler_flags != 0)
    +        fail("DTD processing still going after undefined PE");
    +}
    +END_TEST
    +
    +/* Test public notations with no system ID */
    +START_TEST(test_public_notation_no_sysid)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>\n";
    +
    +    dummy_handler_flags = 0;
    +    XML_SetNotationDeclHandler(parser, dummy_notation_decl_handler);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (dummy_handler_flags != DUMMY_NOTATION_DECL_HANDLER_FLAG)
    +        fail("Notation declaration handler not called");
    +}
    +END_TEST
    +
    +static void XMLCALL
    +record_element_start_handler(void *userData,
    +                             const XML_Char *name,
    +                             const XML_Char **UNUSED_P(atts))
    +{
    +    CharData_AppendXMLChars((CharData *)userData, name, (int)xcstrlen(name));
    +}
    +
    +START_TEST(test_nested_groups)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "]>\n"
    +        "";
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +    XML_SetStartElementHandler(parser, record_element_start_handler);
    +    XML_SetUserData(parser, &storage);
    +    dummy_handler_flags = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, XCS("doce"));
    +    if (dummy_handler_flags != DUMMY_ELEMENT_DECL_HANDLER_FLAG)
    +        fail("Element handler not fired");
    +}
    +END_TEST
    +
    +START_TEST(test_group_choice)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "\n"
    +        "This is a foo\n"
    +        "\n"
    +        "\n";
    +
    +    XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +    dummy_handler_flags = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (dummy_handler_flags != DUMMY_ELEMENT_DECL_HANDLER_FLAG)
    +        fail("Element handler flag not raised");
    +}
    +END_TEST
    +
    +static int XMLCALL
    +external_entity_public(XML_Parser parser,
    +                       const XML_Char *context,
    +                       const XML_Char *UNUSED_P(base),
    +                       const XML_Char *systemId,
    +                       const XML_Char *publicId)
    +{
    +    const char *text1 = (const char *)XML_GetUserData(parser);
    +    const char *text2 = "";
    +    const char *text = NULL;
    +    XML_Parser ext_parser;
    +    int parse_res;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        return XML_STATUS_ERROR;
    +    if (systemId != NULL && !xcstrcmp(systemId, XCS("http://example.org/"))) {
    +        text = text1;
    +    }
    +    else if (publicId != NULL && !xcstrcmp(publicId, XCS("foo"))) {
    +        text = text2;
    +    }
    +    else
    +        fail("Unexpected parameters to external entity parser");
    +    parse_res = _XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                   XML_TRUE);
    +    XML_ParserFree(ext_parser);
    +    return parse_res;
    +}
    +
    +START_TEST(test_standalone_parameter_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "'>\n"
    +        "%entity;\n"
    +        "]>\n"
    +        "";
    +    char dtd_data[] =
    +        "\n";
    +
    +    XML_SetUserData(parser, dtd_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_public);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test skipping of parameter entity in an external DTD */
    +/* Derived from ibm/invalid/P69/ibm69i01.xml */
    +START_TEST(test_skipped_parameter_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "";
    +    ExtTest dtd_data = { "%pe2;", NULL, NULL };
    +
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    XML_SetUserData(parser, &dtd_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetSkippedEntityHandler(parser, dummy_skip_handler);
    +    dummy_handler_flags = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (dummy_handler_flags != DUMMY_SKIP_HANDLER_FLAG)
    +        fail("Skip handler not executed");
    +}
    +END_TEST
    +
    +/* Test recursive parameter entity definition rejected in external DTD */
    +START_TEST(test_recursive_external_parameter_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "";
    +    ExtFaults dtd_data = {
    +        "\n%pe2;",
    +        "Recursive external parameter entity not faulted",
    +        NULL,
    +        XML_ERROR_RECURSIVE_ENTITY_REF
    +    };
    +
    +    XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +    XML_SetUserData(parser, &dtd_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    expect_failure(text,
    +                   XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Recursive external parameter not spotted");
    +}
    +END_TEST
    +
    +/* Test undefined parameter entity in external entity handler */
    +static int XMLCALL
    +external_entity_devaluer(XML_Parser parser,
    +                         const XML_Char *context,
    +                         const XML_Char *UNUSED_P(base),
    +                         const XML_Char *systemId,
    +                         const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "%e1;\n";
    +    XML_Parser ext_parser;
    +    intptr_t clear_handler = (intptr_t)XML_GetUserData(parser);
    +
    +    if (systemId == NULL || !xcstrcmp(systemId, XCS("bar")))
    +        return XML_STATUS_OK;
    +    if (xcstrcmp(systemId, XCS("foo")))
    +        fail("Unexpected system ID");
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could note create external entity parser");
    +    if (clear_handler)
    +        XML_SetExternalEntityRefHandler(ext_parser, NULL);
    +    if (_XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(ext_parser);
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_undefined_ext_entity_in_external_dtd)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_devaluer);
    +    XML_SetUserData(parser, (void *)(intptr_t)XML_FALSE);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    /* Now repeat without the external entity ref handler invoking
    +     * another copy of itself.
    +     */
    +    XML_ParserReset(parser, NULL);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_devaluer);
    +    XML_SetUserData(parser, (void *)(intptr_t)XML_TRUE);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +
    +static void XMLCALL
    +aborting_xdecl_handler(void           *UNUSED_P(userData),
    +                       const XML_Char *UNUSED_P(version),
    +                       const XML_Char *UNUSED_P(encoding),
    +                       int             UNUSED_P(standalone))
    +{
    +    XML_StopParser(parser, resumable);
    +    XML_SetXmlDeclHandler(parser, NULL);
    +}
    +
    +/* Test suspending the parse on receiving an XML declaration works */
    +START_TEST(test_suspend_xdecl)
    +{
    +    const char *text = long_character_data_text;
    +
    +    XML_SetXmlDeclHandler(parser, aborting_xdecl_handler);
    +    resumable = XML_TRUE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_SUSPENDED)
    +        xml_failure(parser);
    +    if (XML_GetErrorCode(parser) != XML_ERROR_NONE)
    +        xml_failure(parser);
    +    /* Attempt to start a new parse while suspended */
    +    if (XML_Parse(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Attempt to parse while suspended not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_SUSPENDED)
    +        fail("Suspended parse not faulted with correct error");
    +}
    +END_TEST
    +
    +/* Test aborting the parse in an epilog works */
    +static void XMLCALL
    +selective_aborting_default_handler(void *userData,
    +                                   const XML_Char *s,
    +                                   int len)
    +{
    +    const XML_Char *match = (const XML_Char *)userData;
    +
    +    if (match == NULL ||
    +        (xcstrlen(match) == (unsigned)len &&
    +         !xcstrncmp(match, s, len))) {
    +        XML_StopParser(parser, resumable);
    +        XML_SetDefaultHandler(parser, NULL);
    +    }
    +}
    +
    +START_TEST(test_abort_epilog)
    +{
    +    const char *text = "\n\r\n";
    +    XML_Char match[] = XCS("\r");
    +
    +    XML_SetDefaultHandler(parser, selective_aborting_default_handler);
    +    XML_SetUserData(parser, match);
    +    resumable = XML_FALSE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Abort not triggered");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_ABORTED)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test a different code path for abort in the epilog */
    +START_TEST(test_abort_epilog_2)
    +{
    +    const char *text = "\n";
    +    XML_Char match[] = XCS("\n");
    +
    +    XML_SetDefaultHandler(parser, selective_aborting_default_handler);
    +    XML_SetUserData(parser, match);
    +    resumable = XML_FALSE;
    +    expect_failure(text, XML_ERROR_ABORTED, "Abort not triggered");
    +}
    +END_TEST
    +
    +/* Test suspension from the epilog */
    +START_TEST(test_suspend_epilog)
    +{
    +    const char *text = "\n";
    +    XML_Char match[] = XCS("\n");
    +
    +    XML_SetDefaultHandler(parser, selective_aborting_default_handler);
    +    XML_SetUserData(parser, match);
    +    resumable = XML_TRUE;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_SUSPENDED)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +static void XMLCALL
    +suspending_end_handler(void *userData,
    +                       const XML_Char *UNUSED_P(s))
    +{
    +    XML_StopParser((XML_Parser)userData, 1);
    +}
    +
    +START_TEST(test_suspend_in_sole_empty_tag)
    +{
    +    const char *text = "";
    +    enum XML_Status rc;
    +
    +    XML_SetEndElementHandler(parser, suspending_end_handler);
    +    XML_SetUserData(parser, parser);
    +    rc = _XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                 XML_TRUE);
    +    if (rc == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    else if (rc != XML_STATUS_SUSPENDED)
    +        fail("Suspend not triggered");
    +    rc = XML_ResumeParser(parser);
    +    if (rc == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    else if (rc != XML_STATUS_OK)
    +        fail("Resume failed");
    +}
    +END_TEST
    +
    +START_TEST(test_unfinished_epilog)
    +{
    +    const char *text = "<";
    +
    +    expect_failure(text, XML_ERROR_UNCLOSED_TOKEN,
    +                   "Incomplete epilog entry not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_partial_char_in_epilog)
    +{
    +    const char *text = "\xe2\x82";
    +
    +    /* First check that no fault is raised if the parse is not finished */
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    /* Now check that it is faulted once we finish */
    +    if (XML_ParseBuffer(parser, 0, XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Partial character in epilog not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_PARTIAL_CHAR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +START_TEST(test_hash_collision)
    +{
    +    /* For full coverage of the lookup routine, we need to ensure a
    +     * hash collision even though we can only tell that we have one
    +     * through breakpoint debugging or coverage statistics.  The
    +     * following will cause a hash collision on machines with a 64-bit
    +     * long type; others will have to experiment.  The full coverage
    +     * tests invoked from qa.sh usually provide a hash collision, but
    +     * not always.  This is an attempt to provide insurance.
    +     */
    +#define COLLIDING_HASH_SALT (unsigned long)_SIP_ULL(0xffffffffU, 0xff99fc90U)
    +    const char * text =
    +        "\n"
    +        "\n"
    +        "This is a foo\n"
    +        "\n"
    +        "\n"
    +        "\n"
    +        "This triggers the table growth and collides with b2\n"
    +        "\n";
    +
    +    XML_SetHashSalt(parser, COLLIDING_HASH_SALT);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +#undef COLLIDING_HASH_SALT
    +
    +/* Test resuming a parse suspended in entity substitution */
    +static void XMLCALL
    +start_element_suspender(void *UNUSED_P(userData),
    +                        const XML_Char *name,
    +                        const XML_Char **UNUSED_P(atts))
    +{
    +    if (!xcstrcmp(name, XCS("suspend")))
    +        XML_StopParser(parser, XML_TRUE);
    +    if (!xcstrcmp(name, XCS("abort")))
    +        XML_StopParser(parser, XML_FALSE);
    +}
    +
    +START_TEST(test_suspend_resume_internal_entity)
    +{
    +    const char *text =
    +        "HiHo'>\n"
    +        "]>\n"
    +        "&foo;\n";
    +    const XML_Char *expected1 = XCS("Hi");
    +    const XML_Char *expected2 = XCS("HiHo");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetStartElementHandler(parser, start_element_suspender);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (XML_Parse(parser, text, (int)strlen(text),
    +                  XML_TRUE) != XML_STATUS_SUSPENDED)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, XCS(""));
    +    if (XML_ResumeParser(parser) != XML_STATUS_SUSPENDED)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected1);
    +    if (XML_ResumeParser(parser) != XML_STATUS_OK)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected2);
    +}
    +END_TEST
    +
    +/* Test syntax error is caught at parse resumption */
    +START_TEST(test_resume_entity_with_syntax_error)
    +{
    +    const char *text =
    +        "Hi'>\n"
    +        "]>\n"
    +        "&foo;\n";
    +
    +    XML_SetStartElementHandler(parser, start_element_suspender);
    +    if (XML_Parse(parser, text, (int)strlen(text),
    +                  XML_TRUE) != XML_STATUS_SUSPENDED)
    +        xml_failure(parser);
    +    if (XML_ResumeParser(parser) != XML_STATUS_ERROR)
    +        fail("Syntax error in entity not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_TAG_MISMATCH)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test suspending and resuming in a parameter entity substitution */
    +static void XMLCALL
    +element_decl_suspender(void *UNUSED_P(userData),
    +                       const XML_Char *UNUSED_P(name),
    +                       XML_Content *model)
    +{
    +    XML_StopParser(parser, XML_TRUE);
    +    XML_FreeContentModel(parser, model);
    +}
    +
    +START_TEST(test_suspend_resume_parameter_entity)
    +{
    +    const char *text =
    +        "'>\n"
    +        "%foo;\n"
    +        "]>\n"
    +        "Hello, world";
    +    const XML_Char *expected = XCS("Hello, world");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetElementDeclHandler(parser, element_decl_suspender);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (XML_Parse(parser, text, (int)strlen(text),
    +                  XML_TRUE) != XML_STATUS_SUSPENDED)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, XCS(""));
    +    if (XML_ResumeParser(parser) != XML_STATUS_OK)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test attempting to use parser after an error is faulted */
    +START_TEST(test_restart_on_error)
    +{
    +    const char *text = "<$doc>";
    +
    +    if (XML_Parse(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Invalid tag name not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_INVALID_TOKEN)
    +        xml_failure(parser);
    +    if (XML_Parse(parser, NULL, 0, XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Restarting invalid parse not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_INVALID_TOKEN)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test that angle brackets in an attribute default value are faulted */
    +START_TEST(test_reject_lt_in_attribute_value)
    +{
    +    const char *text =
    +        "'>]>\n"
    +        "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Bad attribute default not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_reject_unfinished_param_in_att_value)
    +{
    +    const char *text =
    +        "]>\n"
    +        "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Bad attribute default not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_trailing_cr_in_att_value)
    +{
    +    const char *text = "";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Try parsing a general entity within a parameter entity in a
    + * standalone internal DTD.  Covers a corner case in the parser.
    + */
    +START_TEST(test_standalone_internal_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "  '>\n"
    +        "  \n"
    +        "  %pe;\n"
    +        "]>\n"
    +        "";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test that a reference to an unknown external entity is skipped */
    +START_TEST(test_skipped_external_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +    ExtTest test_data = {
    +        "\n"
    +        "\n",
    +        NULL,
    +        NULL
    +    };
    +
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test a different form of unknown external entity */
    +typedef struct ext_hdlr_data {
    +    const char *parse_text;
    +    XML_ExternalEntityRefHandler handler;
    +} ExtHdlrData;
    +
    +static int XMLCALL
    +external_entity_oneshot_loader(XML_Parser parser,
    +                               const XML_Char *context,
    +                               const XML_Char *UNUSED_P(base),
    +                               const XML_Char *UNUSED_P(systemId),
    +                               const XML_Char *UNUSED_P(publicId))
    +{
    +    ExtHdlrData *test_data = (ExtHdlrData *)XML_GetUserData(parser);
    +    XML_Parser ext_parser;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser.");
    +    /* Use the requested entity parser for further externals */
    +    XML_SetExternalEntityRefHandler(ext_parser, test_data->handler);
    +    if ( _XML_Parse_SINGLE_BYTES(ext_parser,
    +                                 test_data->parse_text,
    +                                 (int)strlen(test_data->parse_text),
    +                                 XML_TRUE) == XML_STATUS_ERROR) {
    +        xml_failure(ext_parser);
    +    }
    +
    +    XML_ParserFree(ext_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_skipped_null_loaded_ext_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    ExtHdlrData test_data = {
    +        "\n"
    +        "\n"
    +        "%pe2;\n",
    +        external_entity_null_loader
    +    };
    +
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_oneshot_loader);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +START_TEST(test_skipped_unloaded_ext_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    ExtHdlrData test_data = {
    +        "\n"
    +        "\n"
    +        "%pe2;\n",
    +        NULL
    +    };
    +
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_oneshot_loader);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test that a parameter entity value ending with a carriage return
    + * has it translated internally into a newline.
    + */
    +START_TEST(test_param_entity_with_trailing_cr)
    +{
    +#define PARAM_ENTITY_NAME "pe"
    +#define PARAM_ENTITY_CORE_VALUE ""
    +    const char *text =
    +        "\n"
    +        "";
    +    ExtTest test_data = {
    +        "\n"
    +        "%" PARAM_ENTITY_NAME ";\n",
    +        NULL,
    +        NULL
    +    };
    +
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader);
    +    XML_SetEntityDeclHandler(parser, param_entity_match_handler);
    +    entity_name_to_match = XCS(PARAM_ENTITY_NAME);
    +    entity_value_to_match = XCS(PARAM_ENTITY_CORE_VALUE) XCS("\n");
    +    entity_match_flag = ENTITY_MATCH_NOT_FOUND;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (entity_match_flag == ENTITY_MATCH_FAIL)
    +        fail("Parameter entity CR->NEWLINE conversion failed");
    +    else if (entity_match_flag == ENTITY_MATCH_NOT_FOUND)
    +        fail("Parameter entity not parsed");
    +}
    +#undef PARAM_ENTITY_NAME
    +#undef PARAM_ENTITY_CORE_VALUE
    +END_TEST
    +
    +START_TEST(test_invalid_character_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&entity;";
    +
    +    expect_failure(text, XML_ERROR_BAD_CHAR_REF,
    +                   "Out of range character reference not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_invalid_character_entity_2)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&entity;";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Out of range character reference not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_invalid_character_entity_3)
    +{
    +    const char text[] =
    +        /* \n */
    +        "\0<\0!\0E\0N\0T\0I\0T\0Y\0 \0e\0n\0t\0i\0t\0y\0 "
    +        "\0'\0&\x0e\x04\x0e\x08\0;\0'\0>\0\n"
    +        /* ]>\n */
    +        "\0]\0>\0\n"
    +        /* &entity; */
    +        "\0<\0d\0o\0c\0>\0&\0e\0n\0t\0i\0t\0y\0;\0<\0/\0d\0o\0c\0>";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Invalid start of entity name not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_UNDEFINED_ENTITY)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +START_TEST(test_invalid_character_entity_4)
    +{
    +    const char *text =
    +        "\n" /* = � */
    +        "]>\n"
    +        "&entity;";
    +
    +    expect_failure(text, XML_ERROR_BAD_CHAR_REF,
    +                   "Out of range character reference not faulted");
    +}
    +END_TEST
    +
    +
    +/* Test that processing instructions are picked up by a default handler */
    +START_TEST(test_pi_handled_in_default)
    +{
    +    const char *text = "\n";
    +    const XML_Char *expected = XCS("\n");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetDefaultHandler(parser, accumulate_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE)== XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +
    +/* Test that comments are picked up by a default handler */
    +START_TEST(test_comment_handled_in_default)
    +{
    +    const char *text = "\n";
    +    const XML_Char *expected = XCS("\n");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetDefaultHandler(parser, accumulate_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test PIs that look almost but not quite like XML declarations */
    +static void XMLCALL
    +accumulate_pi_characters(void *userData,
    +                         const XML_Char *target,
    +                         const XML_Char *data)
    +{
    +    CharData *storage = (CharData *)userData;
    +
    +    CharData_AppendXMLChars(storage, target, -1);
    +    CharData_AppendXMLChars(storage, XCS(": "), 2);
    +    CharData_AppendXMLChars(storage, data, -1);
    +    CharData_AppendXMLChars(storage, XCS("\n"), 1);
    +}
    +
    +START_TEST(test_pi_yml)
    +{
    +    const char *text = "";
    +    const XML_Char *expected = XCS("yml: something like data\n");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetProcessingInstructionHandler(parser, accumulate_pi_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_pi_xnl)
    +{
    +    const char *text = "";
    +    const XML_Char *expected = XCS("xnl: nothing like data\n");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetProcessingInstructionHandler(parser, accumulate_pi_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_pi_xmm)
    +{
    +    const char *text = "";
    +    const XML_Char *expected = XCS("xmm: everything like data\n");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetProcessingInstructionHandler(parser, accumulate_pi_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_utf16_pi)
    +{
    +    const char text[] =
    +        /* 
    +         * where {KHO KHWAI} = U+0E04
    +         * and   {CHO CHAN}  = U+0E08
    +         */
    +        "<\0?\0\x04\x0e\x08\x0e?\0>\0"
    +        /*  */
    +        "<\0q\0/\0>\0";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x0e04\x0e08: \n");
    +#else
    +    const XML_Char *expected = XCS("\xe0\xb8\x84\xe0\xb8\x88: \n");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetProcessingInstructionHandler(parser, accumulate_pi_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_utf16_be_pi)
    +{
    +    const char text[] =
    +        /* 
    +         * where {KHO KHWAI} = U+0E04
    +         * and   {CHO CHAN}  = U+0E08
    +         */
    +        "\0<\0?\x0e\x04\x0e\x08\0?\0>"
    +        /*  */
    +        "\0<\0q\0/\0>";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x0e04\x0e08: \n");
    +#else
    +    const XML_Char *expected = XCS("\xe0\xb8\x84\xe0\xb8\x88: \n");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetProcessingInstructionHandler(parser, accumulate_pi_characters);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test that comments can be picked up and translated */
    +static void XMLCALL
    +accumulate_comment(void *userData,
    +                   const XML_Char *data)
    +{
    +    CharData *storage = (CharData *)userData;
    +
    +    CharData_AppendXMLChars(storage, data, -1);
    +}
    +
    +START_TEST(test_utf16_be_comment)
    +{
    +    const char text[] =
    +        /*  */
    +        "\0<\0!\0-\0-\0 \0C\0o\0m\0m\0e\0n\0t\0 \0A\0 \0-\0-\0>\0\n"
    +        /*  */
    +        "\0<\0d\0o\0c\0/\0>";
    +    const XML_Char *expected = XCS(" Comment A ");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetCommentHandler(parser, accumulate_comment);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_utf16_le_comment)
    +{
    +    const char text[] =
    +        /*  */
    +        "<\0!\0-\0-\0 \0C\0o\0m\0m\0e\0n\0t\0 \0B\0 \0-\0-\0>\0\n\0"
    +        /*  */
    +        "<\0d\0o\0c\0/\0>\0";
    +    const XML_Char *expected = XCS(" Comment B ");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetCommentHandler(parser, accumulate_comment);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test that the unknown encoding handler with map entries that expect
    + * conversion but no conversion function is faulted
    + */
    +static int XMLCALL
    +failing_converter(void *UNUSED_P(data), const char *UNUSED_P(s))
    +{
    +    /* Always claim to have failed */
    +    return -1;
    +}
    +
    +static int XMLCALL
    +prefix_converter(void *UNUSED_P(data), const char *s)
    +{
    +    /* If the first byte is 0xff, raise an error */
    +    if (s[0] == (char)-1)
    +        return -1;
    +    /* Just add the low bits of the first byte to the second */
    +    return (s[1] + (s[0] & 0x7f)) & 0x01ff;
    +}
    +
    +static int XMLCALL
    +MiscEncodingHandler(void *data,
    +                    const XML_Char *encoding,
    +                    XML_Encoding *info)
    +{
    +    int i;
    +    int high_map = -2; /* Assume a 2-byte sequence */
    +
    +    if (!xcstrcmp(encoding, XCS("invalid-9")) ||
    +        !xcstrcmp(encoding, XCS("ascii-like")) ||
    +        !xcstrcmp(encoding, XCS("invalid-len")) ||
    +        !xcstrcmp(encoding, XCS("invalid-a")) ||
    +        !xcstrcmp(encoding, XCS("invalid-surrogate")) ||
    +        !xcstrcmp(encoding, XCS("invalid-high")))
    +        high_map = -1;
    +
    +    for (i = 0; i < 128; ++i)
    +        info->map[i] = i;
    +    for (; i < 256; ++i)
    +        info->map[i] = high_map;
    +
    +    /* If required, put an invalid value in the ASCII entries */
    +    if (!xcstrcmp(encoding, XCS("invalid-9")))
    +        info->map[9] = 5;
    +    /* If required, have a top-bit set character starts a 5-byte sequence */
    +    if (!xcstrcmp(encoding, XCS("invalid-len")))
    +        info->map[0x81] = -5;
    +    /* If required, make a top-bit set character a valid ASCII character */
    +    if (!xcstrcmp(encoding, XCS("invalid-a")))
    +        info->map[0x82] = 'a';
    +    /* If required, give a top-bit set character a forbidden value,
    +     * what would otherwise be the first of a surrogate pair.
    +     */
    +    if (!xcstrcmp(encoding, XCS("invalid-surrogate")))
    +        info->map[0x83] = 0xd801;
    +    /* If required, give a top-bit set character too high a value */
    +    if (!xcstrcmp(encoding, XCS("invalid-high")))
    +        info->map[0x84] = 0x010101;
    +
    +    info->data = data;
    +    info->release = NULL;
    +    if (!xcstrcmp(encoding, XCS("failing-conv")))
    +        info->convert = failing_converter;
    +    else if (!xcstrcmp(encoding, XCS("prefix-conv")))
    +        info->convert = prefix_converter;
    +    else
    +        info->convert = NULL;
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_missing_encoding_conversion_fn)
    +{
    +    const char *text =
    +        "\n"
    +        "\x81";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    /* MiscEncodingHandler sets up an encoding with every top-bit-set
    +     * character introducing a two-byte sequence.  For this, it
    +     * requires a convert function.  The above function call doesn't
    +     * pass one through, so when BadEncodingHandler actually gets
    +     * called it should supply an invalid encoding.
    +     */
    +    expect_failure(text, XML_ERROR_UNKNOWN_ENCODING,
    +                   "Encoding with missing convert() not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_failing_encoding_conversion_fn)
    +{
    +    const char *text =
    +        "\n"
    +        "\x81";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    /* BadEncodingHandler sets up an encoding with every top-bit-set
    +     * character introducing a two-byte sequence.  For this, it
    +     * requires a convert function.  The above function call passes
    +     * one that insists all possible sequences are invalid anyway.
    +     */
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Encoding with failing convert() not faulted");
    +}
    +END_TEST
    +
    +/* Test unknown encoding conversions */
    +START_TEST(test_unknown_encoding_success)
    +{
    +    const char *text =
    +        "\n"
    +        /* Equivalent to Hello, world */
    +        "<\x81\x64\x80oc>Hello, world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    run_character_check(text, XCS("Hello, world"));
    +}
    +END_TEST
    +
    +/* Test bad name character in unknown encoding */
    +START_TEST(test_unknown_encoding_bad_name)
    +{
    +    const char *text =
    +        "\n"
    +        "<\xff\x64oc>Hello, world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Bad name start in unknown encoding not faulted");
    +}
    +END_TEST
    +
    +/* Test bad mid-name character in unknown encoding */
    +START_TEST(test_unknown_encoding_bad_name_2)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Bad name in unknown encoding not faulted");
    +}
    +END_TEST
    +
    +/* Test element name that is long enough to fill the conversion buffer
    + * in an unknown encoding, finishing with an encoded character.
    + */
    +START_TEST(test_unknown_encoding_long_name_1)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "Hi"
    +        "";
    +    const XML_Char *expected = XCS("abcdefghabcdefghabcdefghijklmnop");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    XML_SetStartElementHandler(parser, record_element_start_handler);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test element name that is long enough to fill the conversion buffer
    + * in an unknown encoding, finishing with an simple character.
    + */
    +START_TEST(test_unknown_encoding_long_name_2)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "Hi"
    +        "";
    +    const XML_Char *expected = XCS("abcdefghabcdefghabcdefghijklmnop");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    XML_SetStartElementHandler(parser, record_element_start_handler);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_invalid_unknown_encoding)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_UNKNOWN_ENCODING,
    +                   "Invalid unknown encoding not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_ascii_encoding_ok)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    run_character_check(text, XCS("Hello, world"));
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_ascii_encoding_fail)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, \x80 world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Invalid character not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_encoding_invalid_length)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_UNKNOWN_ENCODING,
    +                   "Invalid unknown encoding not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_encoding_invalid_topbit)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_UNKNOWN_ENCODING,
    +                   "Invalid unknown encoding not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_encoding_invalid_surrogate)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, \x82 world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Invalid unknown encoding not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_encoding_invalid_high)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, world";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_UNKNOWN_ENCODING,
    +                   "Invalid unknown encoding not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_encoding_invalid_attr_value)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Invalid attribute valid not faulted");
    +}
    +END_TEST
    +
    +/* Test an external entity parser set to use latin-1 detects UTF-16
    + * BOMs correctly.
    + */
    +enum ee_parse_flags {
    +    EE_PARSE_NONE = 0x00,
    +    EE_PARSE_FULL_BUFFER = 0x01
    +};
    +
    +typedef struct ExtTest2 {
    +    const char *parse_text;
    +    int parse_len;
    +    const XML_Char *encoding;
    +    CharData *storage;
    +    enum ee_parse_flags flags;
    +} ExtTest2;
    +
    +static int XMLCALL
    +external_entity_loader2(XML_Parser parser,
    +                        const XML_Char *context,
    +                        const XML_Char *UNUSED_P(base),
    +                        const XML_Char *UNUSED_P(systemId),
    +                        const XML_Char *UNUSED_P(publicId))
    +{
    +    ExtTest2 *test_data = (ExtTest2 *)XML_GetUserData(parser);
    +    XML_Parser extparser;
    +
    +    extparser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (extparser == NULL)
    +        fail("Coulr not create external entity parser");
    +    if (test_data->encoding != NULL) {
    +        if (!XML_SetEncoding(extparser, test_data->encoding))
    +            fail("XML_SetEncoding() ignored for external entity");
    +    }
    +    if (test_data->flags & EE_PARSE_FULL_BUFFER) {
    +        if (XML_Parse(extparser,
    +                      test_data->parse_text,
    +                      test_data->parse_len,
    +                      XML_TRUE) == XML_STATUS_ERROR) {
    +            xml_failure(extparser);
    +        }
    +    }
    +    else if (_XML_Parse_SINGLE_BYTES(extparser,
    +                                     test_data->parse_text,
    +                                     test_data->parse_len,
    +                                     XML_TRUE) == XML_STATUS_ERROR) {
    +        xml_failure(extparser);
    +    }
    +
    +    XML_ParserFree(extparser);
    +    return XML_STATUS_OK;
    +}
    +
    +/* Test that UTF-16 BOM does not select UTF-16 given explicit encoding */
    +static void XMLCALL
    +ext2_accumulate_characters(void *userData, const XML_Char *s, int len)
    +{
    +    ExtTest2 *test_data = (ExtTest2 *)userData;
    +    accumulate_characters(test_data->storage, s, len);
    +}
    +
    +START_TEST(test_ext_entity_latin1_utf16le_bom)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest2 test_data = {
    +        /* If UTF-16, 0xfeff is the BOM and 0x204c is black left bullet */
    +        /* If Latin-1, 0xff = Y-diaeresis, 0xfe = lowercase thorn,
    +         *   0x4c = L and 0x20 is a space
    +         */
    +        "\xff\xfe\x4c\x20",
    +        4,
    +        XCS("iso-8859-1"),
    +        NULL,
    +        EE_PARSE_NONE
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00ff\x00feL ");
    +#else
    +    /* In UTF-8, y-diaeresis is 0xc3 0xbf, lowercase thorn is 0xc3 0xbe */
    +    const XML_Char *expected = XCS("\xc3\xbf\xc3\xbeL ");
    +#endif
    +    CharData storage;
    +
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_ext_entity_latin1_utf16be_bom)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest2 test_data = {
    +        /* If UTF-16, 0xfeff is the BOM and 0x204c is black left bullet */
    +        /* If Latin-1, 0xff = Y-diaeresis, 0xfe = lowercase thorn,
    +         *   0x4c = L and 0x20 is a space
    +         */
    +        "\xfe\xff\x20\x4c",
    +        4,
    +        XCS("iso-8859-1"),
    +        NULL,
    +        EE_PARSE_NONE
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00fe\x00ff L");
    +#else
    +    /* In UTF-8, y-diaeresis is 0xc3 0xbf, lowercase thorn is 0xc3 0xbe */
    +    const XML_Char *expected = XCS("\xc3\xbe\xc3\xbf L");
    +#endif
    +    CharData storage;
    +
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +
    +/* Parsing the full buffer rather than a byte at a time makes a
    + * difference to the encoding scanning code, so repeat the above tests
    + * without breaking them down by byte.
    + */
    +START_TEST(test_ext_entity_latin1_utf16le_bom2)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest2 test_data = {
    +        /* If UTF-16, 0xfeff is the BOM and 0x204c is black left bullet */
    +        /* If Latin-1, 0xff = Y-diaeresis, 0xfe = lowercase thorn,
    +         *   0x4c = L and 0x20 is a space
    +         */
    +        "\xff\xfe\x4c\x20",
    +        4,
    +        XCS("iso-8859-1"),
    +        NULL,
    +        EE_PARSE_FULL_BUFFER
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00ff\x00feL ");
    +#else
    +    /* In UTF-8, y-diaeresis is 0xc3 0xbf, lowercase thorn is 0xc3 0xbe */
    +    const XML_Char *expected = XCS("\xc3\xbf\xc3\xbeL ");
    +#endif
    +    CharData storage;
    +
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (XML_Parse(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_ext_entity_latin1_utf16be_bom2)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest2 test_data = {
    +        /* If UTF-16, 0xfeff is the BOM and 0x204c is black left bullet */
    +        /* If Latin-1, 0xff = Y-diaeresis, 0xfe = lowercase thorn,
    +         *   0x4c = L and 0x20 is a space
    +         */
    +        "\xfe\xff\x20\x4c",
    +        4,
    +        XCS("iso-8859-1"),
    +        NULL,
    +        EE_PARSE_FULL_BUFFER
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00fe\x00ff L");
    +#else
    +    /* In UTF-8, y-diaeresis is 0xc3 0xbf, lowercase thorn is 0xc3 0xbe */
    +    const XML_Char *expected = "\xc3\xbe\xc3\xbf L";
    +#endif
    +    CharData storage;
    +
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (XML_Parse(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test little-endian UTF-16 given an explicit big-endian encoding */
    +START_TEST(test_ext_entity_utf16_be)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest2 test_data = {
    +        "<\0e\0/\0>\0",
    +        8,
    +        XCS("utf-16be"),
    +        NULL,
    +        EE_PARSE_NONE
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x3c00\x6500\x2f00\x3e00");
    +#else
    +    const XML_Char *expected =
    +        XCS("\xe3\xb0\x80"   /* U+3C00 */
    +            "\xe6\x94\x80"   /* U+6500 */
    +            "\xe2\xbc\x80"   /* U+2F00 */
    +            "\xe3\xb8\x80"); /* U+3E00 */
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test big-endian UTF-16 given an explicit little-endian encoding */
    +START_TEST(test_ext_entity_utf16_le)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest2 test_data = {
    +        "\0<\0e\0/\0>",
    +        8,
    +        XCS("utf-16le"),
    +        NULL,
    +        EE_PARSE_NONE
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x3c00\x6500\x2f00\x3e00");
    +#else
    +    const XML_Char *expected =
    +        XCS("\xe3\xb0\x80"   /* U+3C00 */
    +            "\xe6\x94\x80"   /* U+6500 */
    +            "\xe2\xbc\x80"   /* U+2F00 */
    +            "\xe3\xb8\x80"); /* U+3E00 */
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test little-endian UTF-16 given no explicit encoding.
    + * The existing default encoding (UTF-8) is assumed to hold without a
    + * BOM to contradict it, so the entity value will in fact provoke an
    + * error because 0x00 is not a valid XML character.  We parse the
    + * whole buffer in one go rather than feeding it in byte by byte to
    + * exercise different code paths in the initial scanning routines.
    + */
    +typedef struct ExtFaults2 {
    +    const char *parse_text;
    +    int parse_len;
    +    const char *fail_text;
    +    const XML_Char *encoding;
    +    enum XML_Error error;
    +} ExtFaults2;
    +
    +static int XMLCALL
    +external_entity_faulter2(XML_Parser parser,
    +                         const XML_Char *context,
    +                         const XML_Char *UNUSED_P(base),
    +                         const XML_Char *UNUSED_P(systemId),
    +                         const XML_Char *UNUSED_P(publicId))
    +{
    +    ExtFaults2 *test_data = (ExtFaults2 *)XML_GetUserData(parser);
    +    XML_Parser extparser;
    +
    +    extparser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (extparser == NULL)
    +        fail("Could not create external entity parser");
    +    if (test_data->encoding != NULL) {
    +        if (!XML_SetEncoding(extparser, test_data->encoding))
    +            fail("XML_SetEncoding() ignored for external entity");
    +    }
    +    if (XML_Parse(extparser,
    +                  test_data->parse_text,
    +                  test_data->parse_len,
    +                  XML_TRUE) != XML_STATUS_ERROR)
    +        fail(test_data->fail_text);
    +    if (XML_GetErrorCode(extparser) != test_data->error)
    +        xml_failure(extparser);
    +
    +    XML_ParserFree(extparser);
    +    return XML_STATUS_ERROR;
    +}
    +
    +START_TEST(test_ext_entity_utf16_unknown)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtFaults2 test_data = {
    +        "a\0b\0c\0",
    +        6,
    +        "Invalid character in entity not faulted",
    +        NULL,
    +        XML_ERROR_INVALID_TOKEN
    +    };
    +
    +    XML_SetExternalEntityRefHandler(parser, external_entity_faulter2);
    +    XML_SetUserData(parser, &test_data);
    +    expect_failure(text, XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Invalid character should not have been accepted");
    +}
    +END_TEST
    +
    +/* Test not-quite-UTF-8 BOM (0xEF 0xBB 0xBF) */
    +START_TEST(test_ext_entity_utf8_non_bom)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtTest2 test_data = {
    +        "\xef\xbb\x80", /* Arabic letter DAD medial form, U+FEC0 */
    +        3,
    +        NULL,
    +        NULL,
    +        EE_PARSE_NONE
    +    };
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\xfec0");
    +#else
    +    const XML_Char *expected = XCS("\xef\xbb\x80");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test that UTF-8 in a CDATA section is correctly passed through */
    +START_TEST(test_utf8_in_cdata_section)
    +{
    +    const char *text = "";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("one \x00e9 two");
    +#else
    +    const XML_Char *expected = XCS("one \xc3\xa9 two");
    +#endif
    +
    +    run_character_check(text, expected);
    +}
    +END_TEST
    +
    +/* Test that little-endian UTF-16 in a CDATA section is handled */
    +START_TEST(test_utf8_in_cdata_section_2)
    +{
    +    const char *text = "";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00e9]\x00e9two");
    +#else
    +    const XML_Char *expected = XCS("\xc3\xa9]\xc3\xa9two");
    +#endif
    +
    +    run_character_check(text, expected);
    +}
    +END_TEST
    +
    +/* Test trailing spaces in elements are accepted */
    +static void XMLCALL
    +record_element_end_handler(void *userData,
    +                           const XML_Char *name)
    +{
    +    CharData *storage = (CharData *)userData;
    +
    +    CharData_AppendXMLChars(storage, XCS("/"), 1);
    +    CharData_AppendXMLChars(storage, name, -1);
    +}
    +
    +START_TEST(test_trailing_spaces_in_elements)
    +{
    +    const char *text = "Hi";
    +    const XML_Char *expected = XCS("doc/doc");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetElementHandler(parser, record_element_start_handler,
    +                          record_element_end_handler);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_utf16_attribute)
    +{
    +    const char text[] =
    +        /* 
    +         * where {KHO KHWAI} = U+0E04 = 0xe0 0xb8 0x84 in UTF-8
    +         * and   {CHO CHAN}  = U+0E08 = 0xe0 0xb8 0x88 in UTF-8
    +         */
    +        "<\0d\0 \0\x04\x0e\x08\x0e=\0'\0a\0'\0/\0>\0";
    +    const XML_Char *expected = XCS("a");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetStartElementHandler(parser, accumulate_attribute);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_utf16_second_attr)
    +{
    +    /* 
    +         * where {KHO KHWAI} = U+0E04 = 0xe0 0xb8 0x84 in UTF-8
    +         * and   {CHO CHAN}  = U+0E08 = 0xe0 0xb8 0x88 in UTF-8
    +         */
    +    const char text[] =
    +        "<\0d\0 \0a\0=\0'\0\x31\0'\0 \0"
    +        "\x04\x0e\x08\x0e=\0'\0\x32\0'\0/\0>\0";
    +    const XML_Char *expected = XCS("1");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetStartElementHandler(parser, accumulate_attribute);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_attr_after_solidus)
    +{
    +    const char *text = "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Misplaced / not faulted");
    +}
    +END_TEST
    +
    +static void XMLCALL
    +accumulate_entity_decl(void *userData,
    +                       const XML_Char *entityName,
    +                       int UNUSED_P(is_parameter_entity),
    +                       const XML_Char *value,
    +                       int value_length,
    +                       const XML_Char *UNUSED_P(base),
    +                       const XML_Char *UNUSED_P(systemId),
    +                       const XML_Char *UNUSED_P(publicId),
    +                       const XML_Char *UNUSED_P(notationName))
    +{
    +    CharData *storage = (CharData *)userData;
    +
    +    CharData_AppendXMLChars(storage, entityName, -1);
    +    CharData_AppendXMLChars(storage, XCS("="), 1);
    +    CharData_AppendXMLChars(storage, value, value_length);
    +    CharData_AppendXMLChars(storage, XCS("\n"), 1);
    +}
    +
    +
    +START_TEST(test_utf16_pe)
    +{
    +    /* '>
    +     * %{KHO KHWAI}{CHO CHAN};
    +     * ]>
    +     * 
    +     *
    +     * where {KHO KHWAI} = U+0E04 = 0xe0 0xb8 0x84 in UTF-8
    +     * and   {CHO CHAN}  = U+0E08 = 0xe0 0xb8 0x88 in UTF-8
    +     */
    +    const char text[] =
    +        "\0<\0!\0D\0O\0C\0T\0Y\0P\0E\0 \0d\0o\0c\0 \0[\0\n"
    +        "\0<\0!\0E\0N\0T\0I\0T\0Y\0 \0%\0 \x0e\x04\x0e\x08\0 "
    +        "\0'\0<\0!\0E\0L\0E\0M\0E\0N\0T\0 "
    +        "\0d\0o\0c\0 \0(\0#\0P\0C\0D\0A\0T\0A\0)\0>\0'\0>\0\n"
    +        "\0%\x0e\x04\x0e\x08\0;\0\n"
    +        "\0]\0>\0\n"
    +        "\0<\0d\0o\0c\0>\0<\0/\0d\0o\0c\0>";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected =
    +        XCS("\x0e04\x0e08=\n");
    +#else
    +    const XML_Char *expected =
    +        XCS("\xe0\xb8\x84\xe0\xb8\x88=\n");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetEntityDeclHandler(parser, accumulate_entity_decl);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test that duff attribute description keywords are rejected */
    +START_TEST(test_bad_attr_desc_keyword)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Bad keyword !IMPLIED not faulted");
    +}
    +END_TEST
    +
    +/* Test that an invalid attribute description keyword consisting of
    + * UTF-16 characters with their top bytes non-zero are correctly
    + * faulted
    + */
    +START_TEST(test_bad_attr_desc_keyword_utf16)
    +{
    +    /* 
    +     * ]>
    +     *
    +     * where {KHO KHWAI} = U+0E04 = 0xe0 0xb8 0x84 in UTF-8
    +     * and   {CHO CHAN}  = U+0E08 = 0xe0 0xb8 0x88 in UTF-8
    +     */
    +    const char text[] =
    +        "\0<\0!\0D\0O\0C\0T\0Y\0P\0E\0 \0d\0 \0[\0\n"
    +        "\0<\0!\0A\0T\0T\0L\0I\0S\0T\0 \0d\0 \0a\0 \0C\0D\0A\0T\0A\0 "
    +        "\0#\x0e\x04\x0e\x08\0>\0\n"
    +        "\0]\0>\0<\0d\0/\0>";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Invalid UTF16 attribute keyword not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_SYNTAX)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test that invalid syntax in a  is rejected.  Do this
    + * using prefix-encoding (see above) to trigger specific code paths
    + */
    +START_TEST(test_bad_doctype)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "Invalid bytes in DOCTYPE not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_bad_doctype_utf16)
    +{
    +    const char text[] =
    +        /* 
    +         *
    +         * U+06F2 = EXTENDED ARABIC-INDIC DIGIT TWO, a valid number
    +         * (name character) but not a valid letter (name start character)
    +         */
    +        "\0<\0!\0D\0O\0C\0T\0Y\0P\0E\0 \0d\0o\0c\0 \0[\0 "
    +        "\x06\xf2"
    +        "\0 \0]\0>\0<\0d\0o\0c\0/\0>";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Invalid bytes in DOCTYPE not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_SYNTAX)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +START_TEST(test_bad_doctype_plus)
    +{
    +    const char *text =
    +        " ]>\n"
    +        "<1+>&foo;";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "'+' in document name not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_bad_doctype_star)
    +{
    +    const char *text =
    +        " ]>\n"
    +        "<1*>&foo;";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "'*' in document name not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_bad_doctype_query)
    +{
    +    const char *text =
    +        " ]>\n"
    +        "<1?>&foo;";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "'?' in document name not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_unknown_encoding_bad_ignore)
    +{
    +    const char *text =
    +        ""
    +        ""
    +        "&entity;";
    +    ExtFaults fault = {
    +        "]]>",
    +        "Invalid character not faulted",
    +        XCS("prefix-conv"),
    +        XML_ERROR_INVALID_TOKEN
    +    };
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +    XML_SetUserData(parser, &fault);
    +    expect_failure(text, XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Bad IGNORE section with unknown encoding not failed");
    +}
    +END_TEST
    +
    +START_TEST(test_entity_in_utf16_be_attr)
    +{
    +    const char text[] =
    +        /*  */
    +        "\0<\0e\0 \0a\0=\0'\0&\0#\0\x32\0\x32\0\x38\0;\0 "
    +        "\0&\0#\0x\0\x30\0\x30\0E\0\x34\0;\0'\0>\0<\0/\0e\0>";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00e4 \x00e4");
    +#else
    +    const XML_Char *expected = XCS("\xc3\xa4 \xc3\xa4");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetStartElementHandler(parser, accumulate_attribute);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_entity_in_utf16_le_attr)
    +{
    +    const char text[] =
    +        /*  */
    +        "<\0e\0 \0a\0=\0'\0&\0#\0\x32\0\x32\0\x38\0;\0 \0"
    +        "&\0#\0x\0\x30\0\x30\0E\0\x34\0;\0'\0>\0<\0/\0e\0>\0";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("\x00e4 \x00e4");
    +#else
    +    const XML_Char *expected = XCS("\xc3\xa4 \xc3\xa4");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetStartElementHandler(parser, accumulate_attribute);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_entity_public_utf16_be)
    +{
    +    const char text[] =
    +        /*  */
    +        "\0<\0!\0E\0N\0T\0I\0T\0Y\0 \0%\0 \0e\0 \0P\0U\0B\0L\0I\0C\0 "
    +        "\0'\0f\0o\0o\0'\0 \0'\0b\0a\0r\0.\0e\0n\0t\0'\0>\0\n"
    +        /* %e; */
    +        "\0%\0e\0;\0\n"
    +        /* ]> */
    +        "\0]\0>\0\n"
    +        /* &j; */
    +        "\0<\0d\0>\0&\0j\0;\0<\0/\0d\0>";
    +    ExtTest2 test_data = {
    +        /*  */
    +        "\0<\0!\0E\0N\0T\0I\0T\0Y\0 \0j\0 \0'\0b\0a\0z\0'\0>",
    +        34,
    +        NULL,
    +        NULL,
    +        EE_PARSE_NONE
    +    };
    +    const XML_Char *expected = XCS("baz");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_entity_public_utf16_le)
    +{
    +    const char text[] =
    +        /*  */
    +        "<\0!\0E\0N\0T\0I\0T\0Y\0 \0%\0 \0e\0 \0P\0U\0B\0L\0I\0C\0 \0"
    +        "'\0f\0o\0o\0'\0 \0'\0b\0a\0r\0.\0e\0n\0t\0'\0>\0\n\0"
    +        /* %e; */
    +        "%\0e\0;\0\n\0"
    +        /* ]> */
    +        "]\0>\0\n\0"
    +        /* &j; */
    +        "<\0d\0>\0&\0j\0;\0<\0/\0d\0>\0";
    +    ExtTest2 test_data = {
    +        /*  */
    +        "<\0!\0E\0N\0T\0I\0T\0Y\0 \0j\0 \0'\0b\0a\0z\0'\0>\0",
    +        34,
    +        NULL,
    +        NULL,
    +        EE_PARSE_NONE
    +    };
    +    const XML_Char *expected = XCS("baz");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    test_data.storage = &storage;
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_loader2);
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetCharacterDataHandler(parser, ext2_accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +/* Test that a doctype with neither an internal nor external subset is
    + * faulted
    + */
    +START_TEST(test_short_doctype)
    +{
    +    const char *text = "";
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "DOCTYPE without subset not rejected");
    +}
    +END_TEST
    +
    +START_TEST(test_short_doctype_2)
    +{
    +    const char *text = "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "DOCTYPE without Public ID not rejected");
    +}
    +END_TEST
    +
    +START_TEST(test_short_doctype_3)
    +{
    +    const char *text = "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "DOCTYPE without System ID not rejected");
    +}
    +END_TEST
    +
    +START_TEST(test_long_doctype)
    +{
    +    const char *text = "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "DOCTYPE with extra ID not rejected");
    +}
    +END_TEST
    +
    +START_TEST(test_bad_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "ENTITY without Public ID is not rejected");
    +}
    +END_TEST
    +
    +/* Test unquoted value is faulted */
    +START_TEST(test_bad_entity_2)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "ENTITY without Public ID is not rejected");
    +}
    +END_TEST
    +
    +START_TEST(test_bad_entity_3)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "Parameter ENTITY without Public ID is not rejected");
    +}
    +END_TEST
    +
    +START_TEST(test_bad_entity_4)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "Parameter ENTITY without Public ID is not rejected");
    +}
    +END_TEST
    +
    +START_TEST(test_bad_notation)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "Notation without System ID is not rejected");
    +}
    +END_TEST
    +
    +/* Test for issue #11, wrongly suppressed default handler */
    +typedef struct default_check {
    +    const XML_Char *expected;
    +    const int expectedLen;
    +    XML_Bool seen;
    +} DefaultCheck;
    +
    +static void XMLCALL
    +checking_default_handler(void *userData,
    +                         const XML_Char *s,
    +                         int len)
    +{
    +    DefaultCheck *data = (DefaultCheck *)userData;
    +    int i;
    +
    +    for (i = 0; data[i].expected != NULL; i++) {
    +        if (data[i].expectedLen == len &&
    +            !memcmp(data[i].expected, s, len * sizeof(XML_Char))) {
    +            data[i].seen = XML_TRUE;
    +            break;
    +        }
    +    }
    +}
    +
    +START_TEST(test_default_doctype_handler)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&foo;";
    +    DefaultCheck test_data[] = {
    +        {
    +            XCS("'pubname'"),
    +            9,
    +            XML_FALSE
    +        },
    +        {
    +            XCS("'test.dtd'"),
    +            10,
    +            XML_FALSE
    +        },
    +        { NULL, 0, XML_FALSE }
    +    };
    +    int i;
    +
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetDefaultHandler(parser, checking_default_handler);
    +    XML_SetEntityDeclHandler(parser, dummy_entity_decl_handler);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    for (i = 0; test_data[i].expected != NULL; i++)
    +        if (!test_data[i].seen)
    +            fail("Default handler not run for public !DOCTYPE");
    +}
    +END_TEST
    +
    +START_TEST(test_empty_element_abort)
    +{
    +    const char *text = "";
    +
    +    XML_SetStartElementHandler(parser, start_element_suspender);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Expected to error on abort");
    +}
    +END_TEST
     
     /*
      * Namespaces tests.
    @@ -1252,7 +7118,7 @@ END_TEST
     static void
     namespace_setup(void)
     {
    -    parser = XML_ParserCreateNS(NULL, ' ');
    +    parser = XML_ParserCreateNS(NULL, XCS(' '));
         if (parser == NULL)
             fail("Parser not created.");
     }
    @@ -1268,20 +7134,25 @@ namespace_teardown(void)
        provided as the userData argument; the first is the expected
        element name, and the second is the expected attribute name.
     */
    +static int triplet_start_flag = XML_FALSE;
    +static int triplet_end_flag = XML_FALSE;
    +
     static void XMLCALL
     triplet_start_checker(void *userData, const XML_Char *name,
                           const XML_Char **atts)
     {
    -    char **elemstr = (char **)userData;
    +    XML_Char **elemstr = (XML_Char **)userData;
         char buffer[1024];
    -    if (strcmp(elemstr[0], name) != 0) {
    -        sprintf(buffer, "unexpected start string: '%s'", name);
    +    if (xcstrcmp(elemstr[0], name) != 0) {
    +        sprintf(buffer, "unexpected start string: '%" XML_FMT_STR "'", name);
             fail(buffer);
         }
    -    if (strcmp(elemstr[1], atts[0]) != 0) {
    -        sprintf(buffer, "unexpected attribute string: '%s'", atts[0]);
    +    if (xcstrcmp(elemstr[1], atts[0]) != 0) {
    +        sprintf(buffer, "unexpected attribute string: '%" XML_FMT_STR "'",
    +                atts[0]);
             fail(buffer);
         }
    +    triplet_start_flag = XML_TRUE;
     }
     
     /* Check that the element name passed to the end-element handler matches
    @@ -1291,28 +7162,50 @@ triplet_start_checker(void *userData, const XML_Char *name,
     static void XMLCALL
     triplet_end_checker(void *userData, const XML_Char *name)
     {
    -    char **elemstr = (char **)userData;
    -    if (strcmp(elemstr[0], name) != 0) {
    +    XML_Char **elemstr = (XML_Char **)userData;
    +    if (xcstrcmp(elemstr[0], name) != 0) {
             char buffer[1024];
    -        sprintf(buffer, "unexpected end string: '%s'", name);
    +        sprintf(buffer, "unexpected end string: '%" XML_FMT_STR "'", name);
             fail(buffer);
         }
    +    triplet_end_flag = XML_TRUE;
     }
     
     START_TEST(test_return_ns_triplet)
     {
         const char *text =
    -        "";
    -    const char *elemstr[] = {
    -        "http://expat.sf.net/ e foo",
    -        "http://expat.sf.net/ a bar"
    +        "";
    +    const char *epilog = "";
    +    const XML_Char *elemstr[] = {
    +        XCS("http://example.org/ e foo"),
    +        XCS("http://example.org/ a bar")
         };
         XML_SetReturnNSTriplet(parser, XML_TRUE);
    -    XML_SetUserData(parser, elemstr);
    -    XML_SetElementHandler(parser, triplet_start_checker, triplet_end_checker);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    XML_SetUserData(parser, (void *)elemstr);
    +    XML_SetElementHandler(parser, triplet_start_checker,
    +                          triplet_end_checker);
    +    XML_SetNamespaceDeclHandler(parser,
    +                                dummy_start_namespace_decl_handler,
    +                                dummy_end_namespace_decl_handler);
    +    triplet_start_flag = XML_FALSE;
    +    triplet_end_flag = XML_FALSE;
    +    dummy_handler_flags = 0;
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_FALSE) == XML_STATUS_ERROR)
             xml_failure(parser);
    +    if (!triplet_start_flag)
    +        fail("triplet_start_checker not invoked");
    +    /* Check that unsetting "return triplets" fails while still parsing */
    +    XML_SetReturnNSTriplet(parser, XML_FALSE);
    +    if (_XML_Parse_SINGLE_BYTES(parser, epilog, (int)strlen(epilog),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (!triplet_end_flag)
    +        fail("triplet_end_checker not invoked");
    +    if (dummy_handler_flags != (DUMMY_START_NS_DECL_HANDLER_FLAG |
    +                                DUMMY_END_NS_DECL_HANDLER_FLAG))
    +        fail("Namespace handlers not called");
     }
     END_TEST
     
    @@ -1321,55 +7214,55 @@ overwrite_start_checker(void *userData, const XML_Char *name,
                             const XML_Char **atts)
     {
         CharData *storage = (CharData *) userData;
    -    CharData_AppendString(storage, "start ");
    +    CharData_AppendXMLChars(storage, XCS("start "), 6);
         CharData_AppendXMLChars(storage, name, -1);
         while (*atts != NULL) {
    -        CharData_AppendString(storage, "\nattribute ");
    +        CharData_AppendXMLChars(storage, XCS("\nattribute "), 11);
             CharData_AppendXMLChars(storage, *atts, -1);
             atts += 2;
         }
    -    CharData_AppendString(storage, "\n");
    +    CharData_AppendXMLChars(storage, XCS("\n"), 1);
     }
     
     static void XMLCALL
     overwrite_end_checker(void *userData, const XML_Char *name)
     {
         CharData *storage = (CharData *) userData;
    -    CharData_AppendString(storage, "end ");
    +    CharData_AppendXMLChars(storage, XCS("end "), 4);
         CharData_AppendXMLChars(storage, name, -1);
    -    CharData_AppendString(storage, "\n");
    +    CharData_AppendXMLChars(storage, XCS("\n"), 1);
     }
     
     static void
    -run_ns_tagname_overwrite_test(const char *text, const char *result)
    +run_ns_tagname_overwrite_test(const char *text, const XML_Char *result)
     {
         CharData storage;
         CharData_Init(&storage);
         XML_SetUserData(parser, &storage);
         XML_SetElementHandler(parser,
                               overwrite_start_checker, overwrite_end_checker);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
    -    CharData_CheckString(&storage, result);
    +    CharData_CheckXMLChars(&storage, result);
     }
     
     /* Regression test for SF bug #566334. */
     START_TEST(test_ns_tagname_overwrite)
     {
         const char *text =
    -        "\n"
    +        "\n"
             "  \n"
             "  \n"
             "";
    -    const char *result =
    -        "start http://xml.libexpat.org/ e\n"
    -        "start http://xml.libexpat.org/ f\n"
    -        "attribute http://xml.libexpat.org/ attr\n"
    -        "end http://xml.libexpat.org/ f\n"
    -        "start http://xml.libexpat.org/ g\n"
    -        "attribute http://xml.libexpat.org/ attr2\n"
    -        "end http://xml.libexpat.org/ g\n"
    -        "end http://xml.libexpat.org/ e\n";
    +    const XML_Char *result =
    +        XCS("start http://example.org/ e\n")
    +        XCS("start http://example.org/ f\n")
    +        XCS("attribute http://example.org/ attr\n")
    +        XCS("end http://example.org/ f\n")
    +        XCS("start http://example.org/ g\n")
    +        XCS("attribute http://example.org/ attr2\n")
    +        XCS("end http://example.org/ g\n")
    +        XCS("end http://example.org/ e\n");
         run_ns_tagname_overwrite_test(text, result);
     }
     END_TEST
    @@ -1378,19 +7271,19 @@ END_TEST
     START_TEST(test_ns_tagname_overwrite_triplet)
     {
         const char *text =
    -        "\n"
    +        "\n"
             "  \n"
             "  \n"
             "";
    -    const char *result =
    -        "start http://xml.libexpat.org/ e n\n"
    -        "start http://xml.libexpat.org/ f n\n"
    -        "attribute http://xml.libexpat.org/ attr n\n"
    -        "end http://xml.libexpat.org/ f n\n"
    -        "start http://xml.libexpat.org/ g n\n"
    -        "attribute http://xml.libexpat.org/ attr2 n\n"
    -        "end http://xml.libexpat.org/ g n\n"
    -        "end http://xml.libexpat.org/ e n\n";
    +    const XML_Char *result =
    +        XCS("start http://example.org/ e n\n")
    +        XCS("start http://example.org/ f n\n")
    +        XCS("attribute http://example.org/ attr n\n")
    +        XCS("end http://example.org/ f n\n")
    +        XCS("start http://example.org/ g n\n")
    +        XCS("attribute http://example.org/ attr2 n\n")
    +        XCS("end http://example.org/ g n\n")
    +        XCS("end http://example.org/ e n\n");
         XML_SetReturnNSTriplet(parser, XML_TRUE);
         run_ns_tagname_overwrite_test(text, result);
     }
    @@ -1420,12 +7313,13 @@ START_TEST(test_start_ns_clears_start_element)
            syntax doesn't cause the problematic path through Expat to be
            taken.
         */
    -    const char *text = "";
    +    const char *text = "";
     
         XML_SetStartElementHandler(parser, start_element_fail);
         XML_SetStartNamespaceDeclHandler(parser, start_ns_clearing_start_element);
    +    XML_SetEndNamespaceDeclHandler(parser, dummy_end_namespace_decl_handler);
         XML_UseParserAsHandlerArg(parser);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -1452,22 +7346,22 @@ external_entity_handler(XML_Parser parser,
     
         XML_SetUserData(parser, (void *) callno);
         p2 = XML_ExternalEntityParserCreate(parser, context, NULL);
    -    if (_XML_Parse_SINGLE_BYTES(p2, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR) {
    +    if (_XML_Parse_SINGLE_BYTES(p2, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR) {
             xml_failure(p2);
    -        return 0;
    +        return XML_STATUS_ERROR;
         }
         XML_ParserFree(p2);
    -    return 1;
    +    return XML_STATUS_OK;
     }
     
     START_TEST(test_default_ns_from_ext_subset_and_ext_ge)
     {
         const char *text =
             "\n"
    -        "\n"
    +        "\n"
             "]>\n"
    -        "\n"
    +        "\n"
             "&en;\n"
             "";
     
    @@ -1476,7 +7370,7 @@ START_TEST(test_default_ns_from_ext_subset_and_ext_ge)
         /* We actually need to set this handler to tickle this bug. */
         XML_SetStartElementHandler(parser, dummy_start_element);
         XML_SetUserData(parser, NULL);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -1485,7 +7379,7 @@ END_TEST
     START_TEST(test_ns_prefix_with_empty_uri_1)
     {
         const char *text =
    -        "\n"
    +        "\n"
             "  \n"
             "";
     
    @@ -1533,19 +7427,38 @@ START_TEST(test_ns_prefix_with_empty_uri_4)
             "\n"
             "  \n"
    +        "    xmlns:prefix CDATA 'http://example.org/'>\n"
             "]>\n"
             "";
         /* Packaged info expected by the end element handler;
            the weird structuring lets us re-use the triplet_end_checker()
            function also used for another test. */
    -    const char *elemstr[] = {
    -        "http://xml.libexpat.org/ doc prefix"
    +    const XML_Char *elemstr[] = {
    +        XCS("http://example.org/ doc prefix")
         };
         XML_SetReturnNSTriplet(parser, XML_TRUE);
    -    XML_SetUserData(parser, elemstr);
    +    XML_SetUserData(parser, (void *)elemstr);
         XML_SetEndElementHandler(parser, triplet_end_checker);
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test with non-xmlns prefix */
    +START_TEST(test_ns_unbound_prefix)
    +{
    +    const char *text =
    +        "\n"
    +        "  \n"
    +        "]>\n"
    +        "";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Unbound prefix incorrectly passed");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_UNBOUND_PREFIX)
             xml_failure(parser);
     }
     END_TEST
    @@ -1553,10 +7466,15 @@ END_TEST
     START_TEST(test_ns_default_with_empty_uri)
     {
         const char *text =
    -        "\n"
    +        "\n"
             "  \n"
             "";
    -    if (_XML_Parse_SINGLE_BYTES(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +    /* Add some handlers to exercise extra code paths */
    +    XML_SetStartNamespaceDeclHandler(parser,
    +                                     dummy_start_namespace_decl_handler);
    +    XML_SetEndNamespaceDeclHandler(parser,
    +                                   dummy_end_namespace_decl_handler);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
             xml_failure(parser);
     }
     END_TEST
    @@ -1565,8 +7483,8 @@ END_TEST
     START_TEST(test_ns_duplicate_attrs_diff_prefixes)
     {
         const char *text =
    -        "";
         expect_failure(text,
                        XML_ERROR_DUPLICATE_ATTRIBUTE,
    @@ -1574,6 +7492,33 @@ START_TEST(test_ns_duplicate_attrs_diff_prefixes)
     }
     END_TEST
     
    +START_TEST(test_ns_duplicate_hashes)
    +{
    +    /* The hash of an attribute is calculated as the hash of its URI
    +     * concatenated with a space followed by its name (after the
    +     * colon).  We wish to generate attributes with the same hash
    +     * value modulo the attribute table size so that we can check that
    +     * the attribute hash table works correctly.  The attribute hash
    +     * table size will be the smallest power of two greater than the
    +     * number of attributes, but at least eight.  There is
    +     * unfortunately no programmatic way of getting the hash or the
    +     * table size at user level, but the test code coverage percentage
    +     * will drop if the hashes cease to point to the same row.
    +     *
    +     * The cunning plan is to have few enough attributes to have a
    +     * reliable table size of 8, and have the single letter attribute
    +     * names be 8 characters apart, producing a hash which will be the
    +     * same modulo 8.
    +     */
    +    const char *text =
    +        "";
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
     /* Regression test for SF bug #695401: unbound prefix. */
     START_TEST(test_ns_unbound_prefix_on_attribute)
     {
    @@ -1594,25 +7539,4472 @@ START_TEST(test_ns_unbound_prefix_on_element)
     }
     END_TEST
     
    +/* Test that the parsing status is correctly reset by XML_ParserReset().
    + * We usE test_return_ns_triplet() for our example parse to improve
    + * coverage of tidying up code executed.
    + */
    +START_TEST(test_ns_parser_reset)
    +{
    +    XML_ParsingStatus status;
    +
    +    XML_GetParsingStatus(parser, &status);
    +    if (status.parsing != XML_INITIALIZED)
    +        fail("parsing status doesn't start INITIALIZED");
    +    test_return_ns_triplet();
    +    XML_GetParsingStatus(parser, &status);
    +    if (status.parsing != XML_FINISHED)
    +        fail("parsing status doesn't end FINISHED");
    +    XML_ParserReset(parser, NULL);
    +    XML_GetParsingStatus(parser, &status);
    +    if (status.parsing != XML_INITIALIZED)
    +        fail("parsing status doesn't reset to INITIALIZED");
    +}
    +END_TEST
    +
    +/* Test that long element names with namespaces are handled correctly */
    +START_TEST(test_ns_long_element)
    +{
    +    const char *text =
    +        ""
    +        "";
    +    const XML_Char *elemstr[] = {
    +        XCS("http://example.org/")
    +        XCS(" thisisalongenoughelementnametotriggerareallocation foo"),
    +        XCS("http://example.org/ a bar")
    +    };
    +
    +    XML_SetReturnNSTriplet(parser, XML_TRUE);
    +    XML_SetUserData(parser, (void *)elemstr);
    +    XML_SetElementHandler(parser,
    +                          triplet_start_checker,
    +                          triplet_end_checker);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test mixed population of prefixed and unprefixed attributes */
    +START_TEST(test_ns_mixed_prefix_atts)
    +{
    +    const char *text =
    +        ""
    +        "";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test having a long namespaced element name inside a short one.
    + * This exercises some internal buffer reallocation that is shared
    + * across elements with the same namespace URI.
    + */
    +START_TEST(test_ns_extend_uri_buffer)
    +{
    +    const char *text =
    +        ""
    +        " "
    +        "";
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test that xmlns is correctly rejected as an attribute in the xmlns
    + * namespace, but not in other namespaces
    + */
    +START_TEST(test_ns_reserved_attributes)
    +{
    +    const char *text1 =
    +        "";
    +    const char *text2 =
    +        "";
    +    expect_failure(text1, XML_ERROR_RESERVED_PREFIX_XMLNS,
    +                   "xmlns not rejected as an attribute");
    +    XML_ParserReset(parser, NULL);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text2, (int)strlen(text2),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test more reserved attributes */
    +START_TEST(test_ns_reserved_attributes_2)
    +{
    +    const char *text1 =
    +        "";
    +    const char *text2 =
    +        "";
    +    const char *text3 =
    +        "";
    +
    +    expect_failure(text1, XML_ERROR_RESERVED_PREFIX_XML,
    +                   "xml not rejected as an attribute");
    +    XML_ParserReset(parser, NULL);
    +    expect_failure(text2, XML_ERROR_RESERVED_NAMESPACE_URI,
    +                   "Use of w3.org URL not faulted");
    +    XML_ParserReset(parser, NULL);
    +    expect_failure(text3, XML_ERROR_RESERVED_NAMESPACE_URI,
    +                   "Use of w3.org xmlns URL not faulted");
    +}
    +END_TEST
    +
    +/* Test string pool handling of namespace names of 2048 characters */
    +/* Exercises a particular string pool growth path */
    +START_TEST(test_ns_extremely_long_prefix)
    +{
    +    /* C99 compilers are only required to support 4095-character
    +     * strings, so the following needs to be split in two to be safe
    +     * for all compilers.
    +     */
    +    const char *text1 =
    +        ""
    +        "";
    +
    +    if (_XML_Parse_SINGLE_BYTES(parser, text1, (int)strlen(text1),
    +                                XML_FALSE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text2, (int)strlen(text2),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +/* Test unknown encoding handlers in namespace setup */
    +START_TEST(test_ns_unknown_encoding_success)
    +{
    +    const char *text =
    +        "\n"
    +        "Hi";
    +
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    run_character_check(text, XCS("Hi"));
    +}
    +END_TEST
    +
    +/* Test that too many colons are rejected */
    +START_TEST(test_ns_double_colon)
    +{
    +    const char *text =
    +        "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Double colon in attribute name not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_ns_double_colon_element)
    +{
    +    const char *text =
    +        "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Double colon in element name not faulted");
    +}
    +END_TEST
    +
    +/* Test that non-name characters after a colon are rejected */
    +START_TEST(test_ns_bad_attr_leafname)
    +{
    +    const char *text =
    +        "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Invalid character in leafname not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_ns_bad_element_leafname)
    +{
    +    const char *text =
    +        "";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Invalid character in element leafname not faulted");
    +}
    +END_TEST
    +
    +/* Test high-byte-set UTF-16 characters are valid in a leafname */
    +START_TEST(test_ns_utf16_leafname)
    +{
    +    const char text[] =
    +        /* 
    +         * where {KHO KHWAI} = U+0E04 = 0xe0 0xb8 0x84 in UTF-8
    +         */
    +        "<\0n\0:\0e\0 \0x\0m\0l\0n\0s\0:\0n\0=\0'\0U\0R\0I\0'\0 \0"
    +        "n\0:\0\x04\x0e=\0'\0a\0'\0 \0/\0>\0";
    +    const XML_Char *expected = XCS("a");
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetStartElementHandler(parser, accumulate_attribute);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_ns_utf16_element_leafname)
    +{
    +    const char text[] =
    +        /* 
    +         * where {KHO KHWAI} = U+0E04 = 0xe0 0xb8 0x84 in UTF-8
    +         */
    +        "\0<\0n\0:\x0e\x04\0 \0x\0m\0l\0n\0s\0:\0n\0=\0'\0U\0R\0I\0'\0/\0>";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("URI \x0e04");
    +#else
    +    const XML_Char *expected = XCS("URI \xe0\xb8\x84");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetStartElementHandler(parser, start_element_event_handler);
    +    XML_SetUserData(parser, &storage);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_ns_utf16_doctype)
    +{
    +    const char text[] =
    +        /*  ]>\n
    +         * where {KHO KHWAI} = U+0E04 = 0xe0 0xb8 0x84 in UTF-8
    +         */
    +        "\0<\0!\0D\0O\0C\0T\0Y\0P\0E\0 \0f\0o\0o\0:\x0e\x04\0 "
    +        "\0[\0 \0<\0!\0E\0N\0T\0I\0T\0Y\0 \0b\0a\0r\0 \0'\0b\0a\0z\0'\0>\0 "
    +        "\0]\0>\0\n"
    +        /* &bar; */
    +        "\0<\0f\0o\0o\0:\x0e\x04\0 "
    +        "\0x\0m\0l\0n\0s\0:\0f\0o\0o\0=\0'\0U\0R\0I\0'\0>"
    +        "\0&\0b\0a\0r\0;"
    +        "\0<\0/\0f\0o\0o\0:\x0e\x04\0>";
    +#ifdef XML_UNICODE
    +    const XML_Char *expected = XCS("URI \x0e04");
    +#else
    +    const XML_Char *expected = XCS("URI \xe0\xb8\x84");
    +#endif
    +    CharData storage;
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetStartElementHandler(parser, start_element_event_handler);
    +    XML_SetUnknownEncodingHandler(parser, MiscEncodingHandler, NULL);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +START_TEST(test_ns_invalid_doctype)
    +{
    +    const char *text =
    +        "\n"
    +        "&bar;";
    +
    +    expect_failure(text, XML_ERROR_INVALID_TOKEN,
    +                   "Invalid character in document local name not faulted");
    +}
    +END_TEST
    +
    +START_TEST(test_ns_double_colon_doctype)
    +{
    +    const char *text =
    +        "\n"
    +        "&bar;";
    +
    +    expect_failure(text, XML_ERROR_SYNTAX,
    +                   "Double colon in document name not faulted");
    +}
    +END_TEST
    +
    +/* Control variable; the number of times duff_allocator() will successfully allocate */
    +#define ALLOC_ALWAYS_SUCCEED (-1)
    +#define REALLOC_ALWAYS_SUCCEED (-1)
    +
    +static intptr_t allocation_count = ALLOC_ALWAYS_SUCCEED;
    +static intptr_t reallocation_count = REALLOC_ALWAYS_SUCCEED;
    +
    +/* Crocked allocator for allocation failure tests */
    +static void *duff_allocator(size_t size)
    +{
    +    if (allocation_count == 0)
    +        return NULL;
    +    if (allocation_count != ALLOC_ALWAYS_SUCCEED)
    +        allocation_count--;
    +    return malloc(size);
    +}
    +
    +/* Crocked reallocator for allocation failure tests */
    +static void *duff_reallocator(void *ptr, size_t size)
    +{
    +    if (reallocation_count == 0)
    +        return NULL;
    +    if (reallocation_count != REALLOC_ALWAYS_SUCCEED)
    +        reallocation_count--;
    +    return realloc(ptr, size);
    +}
    +
    +/* Test that a failure to allocate the parser structure fails gracefully */
    +START_TEST(test_misc_alloc_create_parser)
    +{
    +    XML_Memory_Handling_Suite memsuite = { duff_allocator, realloc, free };
    +    unsigned int i;
    +    const unsigned int max_alloc_count = 10;
    +
    +    /* Something this simple shouldn't need more than 10 allocations */
    +    for (i = 0; i < max_alloc_count; i++)
    +    {
    +        allocation_count = i;
    +        parser = XML_ParserCreate_MM(NULL, &memsuite, NULL);
    +        if (parser != NULL)
    +            break;
    +    }
    +    if (i == 0)
    +        fail("Parser unexpectedly ignored failing allocator");
    +    else if (i == max_alloc_count)
    +        fail("Parser not created with max allocation count");
    +}
    +END_TEST
    +
    +/* Test memory allocation failures for a parser with an encoding */
    +START_TEST(test_misc_alloc_create_parser_with_encoding)
    +{
    +    XML_Memory_Handling_Suite memsuite = { duff_allocator, realloc, free };
    +    unsigned int i;
    +    const unsigned int max_alloc_count = 10;
    +
    +    /* Try several levels of allocation */
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        parser = XML_ParserCreate_MM(XCS("us-ascii"), &memsuite, NULL);
    +        if (parser != NULL)
    +            break;
    +    }
    +    if (i == 0)
    +        fail("Parser ignored failing allocator");
    +    else if (i == max_alloc_count)
    +        fail("Parser not created with max allocation count");
    +}
    +END_TEST
    +
    +/* Test that freeing a NULL parser doesn't cause an explosion.
    + * (Not actually tested anywhere else)
    + */
    +START_TEST(test_misc_null_parser)
    +{
    +    XML_ParserFree(NULL);
    +}
    +END_TEST
    +
    +/* Test that XML_ErrorString rejects out-of-range codes */
    +START_TEST(test_misc_error_string)
    +{
    +    if (XML_ErrorString((enum XML_Error)-1) != NULL)
    +        fail("Negative error code not rejected");
    +    if (XML_ErrorString((enum XML_Error)100) != NULL)
    +        fail("Large error code not rejected");
    +}
    +END_TEST
    +
    +/* Test the version information is consistent */
    +
    +/* Since we are working in XML_LChars (potentially 16-bits), we
    + * can't use the standard C library functions for character
    + * manipulation and have to roll our own.
    + */
    +static int
    +parse_version(const XML_LChar *version_text,
    +              XML_Expat_Version *version_struct)
    +{
    +    while (*version_text != 0x00) {
    +        if (*version_text >= ASCII_0 && *version_text <= ASCII_9)
    +            break;
    +        version_text++;
    +    }
    +    if (*version_text == 0x00)
    +        return XML_FALSE;
    +
    +    /* version_struct->major = strtoul(version_text, 10, &version_text) */
    +    version_struct->major = 0;
    +    while (*version_text >= ASCII_0 && *version_text <= ASCII_9) {
    +        version_struct->major =
    +            10 * version_struct->major + (*version_text++ - ASCII_0);
    +    }
    +    if (*version_text++ != ASCII_PERIOD)
    +        return XML_FALSE;
    +
    +    /* Now for the minor version number */
    +    version_struct->minor = 0;
    +    while (*version_text >= ASCII_0 && *version_text <= ASCII_9) {
    +        version_struct->minor =
    +            10 * version_struct->minor + (*version_text++ - ASCII_0);
    +    }
    +    if (*version_text++ != ASCII_PERIOD)
    +        return XML_FALSE;
    +
    +    /* Finally the micro version number */
    +    version_struct->micro = 0;
    +    while (*version_text >= ASCII_0 && *version_text <= ASCII_9) {
    +        version_struct->micro =
    +            10 * version_struct->micro + (*version_text++ - ASCII_0);
    +    }
    +    if (*version_text != 0x00)
    +        return XML_FALSE;
    +    return XML_TRUE;
    +}
    +
    +static int
    +versions_equal(const XML_Expat_Version *first,
    +               const XML_Expat_Version *second)
    +{
    +    return (first->major == second->major &&
    +            first->minor == second->minor &&
    +            first->micro == second->micro);
    +}
    +
    +START_TEST(test_misc_version)
    +{
    +    XML_Expat_Version read_version = XML_ExpatVersionInfo();
    +     /* Silence compiler warning with the following assignment */
    +    XML_Expat_Version parsed_version = { 0, 0, 0 };
    +    const XML_LChar *version_text = XML_ExpatVersion();
    +
    +    if (version_text == NULL)
    +        fail("Could not obtain version text");
    +    if (!parse_version(version_text, &parsed_version))
    +        fail("Unable to parse version text");
    +    if (!versions_equal(&read_version, &parsed_version))
    +        fail("Version mismatch");
    +
    +#if ! defined(XML_UNICODE) || defined(XML_UNICODE_WCHAR_T)
    +    if (xcstrcmp(version_text, XCS("expat_2.2.6")))  /* needs bump on releases */
    +        fail("XML_*_VERSION in expat.h out of sync?\n");
    +#else
    +    /* If we have XML_UNICODE defined but not XML_UNICODE_WCHAR_T
    +     * then XML_LChar is defined as char, for some reason.
    +     */
    +    if (strcmp(version_text, "expat_2.2.5")) /* needs bump on releases */
    +        fail("XML_*_VERSION in expat.h out of sync?\n");
    +#endif  /* ! defined(XML_UNICODE) || defined(XML_UNICODE_WCHAR_T) */
    +}
    +END_TEST
    +
    +/* Test feature information */
    +START_TEST(test_misc_features)
    +{
    +    const XML_Feature *features = XML_GetFeatureList();
    +
    +    /* Prevent problems with double-freeing parsers */
    +    parser = NULL;
    +    if (features == NULL)
    +        fail("Failed to get feature information");
    +    /* Loop through the features checking what we can */
    +    while (features->feature != XML_FEATURE_END) {
    +        switch(features->feature) {
    +            case XML_FEATURE_SIZEOF_XML_CHAR:
    +                if (features->value != sizeof(XML_Char))
    +                    fail("Incorrect size of XML_Char");
    +                break;
    +            case XML_FEATURE_SIZEOF_XML_LCHAR:
    +                if (features->value != sizeof(XML_LChar))
    +                    fail("Incorrect size of XML_LChar");
    +                break;
    +            default:
    +                break;
    +        }
    +        features++;
    +    }
    +}
    +END_TEST
    +
    +/* Regression test for GitHub Issue #17: memory leak parsing attribute
    + * values with mixed bound and unbound namespaces.
    + */
    +START_TEST(test_misc_attribute_leak)
    +{
    +    const char *text = "";
    +    XML_Memory_Handling_Suite memsuite = {
    +        tracking_malloc,
    +        tracking_realloc,
    +        tracking_free
    +    };
    +
    +    parser = XML_ParserCreate_MM(XCS("UTF-8"), &memsuite, XCS("\n"));
    +    expect_failure(text, XML_ERROR_UNBOUND_PREFIX,
    +                   "Unbound prefixes not found");
    +    XML_ParserFree(parser);
    +    /* Prevent the teardown trying to double free */
    +    parser = NULL;
    +
    +    if (!tracking_report())
    +        fail("Memory leak found");
    +}
    +END_TEST
    +
    +/* Test parser created for UTF-16LE is successful */
    +START_TEST(test_misc_utf16le)
    +{
    +    const char text[] =
    +        /* Hi */
    +        "<\0?\0x\0m\0l\0 \0"
    +        "v\0e\0r\0s\0i\0o\0n\0=\0'\0\x31\0.\0\x30\0'\0?\0>\0"
    +        "<\0q\0>\0H\0i\0<\0/\0q\0>\0";
    +    const XML_Char *expected = XCS("Hi");
    +    CharData storage;
    +
    +    parser = XML_ParserCreate(XCS("UTF-16LE"));
    +    if (parser == NULL)
    +        fail("Parser not created");
    +
    +    CharData_Init(&storage);
    +    XML_SetUserData(parser, &storage);
    +    XML_SetCharacterDataHandler(parser, accumulate_characters);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)sizeof(text)-1,
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +    CharData_CheckXMLChars(&storage, expected);
    +}
    +END_TEST
    +
    +
    +static void
    +alloc_setup(void)
    +{
    +    XML_Memory_Handling_Suite memsuite = {
    +        duff_allocator,
    +        duff_reallocator,
    +        free
    +    };
    +
    +    /* Ensure the parser creation will go through */
    +    allocation_count = ALLOC_ALWAYS_SUCCEED;
    +    reallocation_count = REALLOC_ALWAYS_SUCCEED;
    +    parser = XML_ParserCreate_MM(NULL, &memsuite, NULL);
    +    if (parser == NULL)
    +        fail("Parser not created");
    +}
    +
    +static void
    +alloc_teardown(void)
    +{
    +    basic_teardown();
    +}
    +
    +
    +/* Test the effects of allocation failures on xml declaration processing */
    +START_TEST(test_alloc_parse_xdecl)
    +{
    +    const char *text =
    +        "\n"
    +        "Hello, world";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetXmlDeclHandler(parser, dummy_xdecl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* Resetting the parser is insufficient, because some memory
    +         * allocations are cached within the parser.  Instead we use
    +         * the teardown and setup routines to ensure that we have the
    +         * right sort of parser back in our hands.
    +         */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed with max allocations");
    +}
    +END_TEST
    +
    +/* As above, but with an encoding big enough to cause storing the
    + * version information to expand the string pool being used.
    + */
    +static int XMLCALL
    +long_encoding_handler(void *UNUSED_P(userData),
    +                      const XML_Char *UNUSED_P(encoding),
    +                      XML_Encoding *info)
    +{
    +    int i;
    +
    +    for (i = 0; i < 256; i++)
    +        info->map[i] = i;
    +    info->data = NULL;
    +    info->convert = NULL;
    +    info->release = NULL;
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_alloc_parse_xdecl_2)
    +{
    +    const char *text =
    +        ""
    +        "Hello, world";
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetXmlDeclHandler(parser, dummy_xdecl_handler);
    +        XML_SetUnknownEncodingHandler(parser, long_encoding_handler, NULL);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed with max allocations");
    +}
    +END_TEST
    +
    +/* Test the effects of allocation failures on a straightforward parse */
    +START_TEST(test_alloc_parse_pi)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        ""
    +        "Hello, world"
    +        "";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetProcessingInstructionHandler(parser, dummy_pi_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed with max allocations");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_parse_pi_2)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "Hello, world"
    +        "\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetProcessingInstructionHandler(parser, dummy_pi_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed with max allocations");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_parse_pi_3)
    +{
    +    const char *text =
    +        "";
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetProcessingInstructionHandler(parser, dummy_pi_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed with max allocations");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_parse_comment)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "Hi";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetCommentHandler(parser, dummy_comment_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed with max allocations");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_parse_comment_2)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "Hello, world"
    +        ""
    +        "";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetCommentHandler(parser, dummy_comment_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed with max allocations");
    +}
    +END_TEST
    +
    +static int XMLCALL
    +external_entity_duff_loader(XML_Parser parser,
    +                            const XML_Char *context,
    +                            const XML_Char *UNUSED_P(base),
    +                            const XML_Char *UNUSED_P(systemId),
    +                            const XML_Char *UNUSED_P(publicId))
    +{
    +    XML_Parser new_parser;
    +    unsigned int i;
    +    const unsigned int max_alloc_count = 10;
    +
    +    /* Try a few different allocation levels */
    +    for (i = 0; i < max_alloc_count; i++)
    +    {
    +        allocation_count = i;
    +        new_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +        if (new_parser != NULL)
    +        {
    +            XML_ParserFree(new_parser);
    +            break;
    +        }
    +    }
    +    if (i == 0)
    +        fail("External parser creation ignored failing allocator");
    +    else if (i == max_alloc_count)
    +        fail("Extern parser not created with max allocation count");
    +
    +    /* Make sure other random allocation doesn't now fail */
    +    allocation_count = ALLOC_ALWAYS_SUCCEED;
    +
    +    /* Make sure the failure code path is executed too */
    +    return XML_STATUS_ERROR;
    +}
    +
    +/* Test that external parser creation running out of memory is
    + * correctly reported.  Based on the external entity test cases.
    + */
    +START_TEST(test_alloc_create_external_parser)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +    char foo_text[] =
    +        "";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetUserData(parser, foo_text);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_duff_loader);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR) {
    +        fail("External parser allocator returned success incorrectly");
    +    }
    +}
    +END_TEST
    +
    +/* More external parser memory allocation testing */
    +START_TEST(test_alloc_run_external_parser)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "&entity;";
    +    char foo_text[] =
    +        "";
    +    unsigned int i;
    +    const unsigned int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        XML_SetParamEntityParsing(parser,
    +                                  XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetUserData(parser, foo_text);
    +        XML_SetExternalEntityRefHandler(parser,
    +                                        external_entity_null_loader);
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing ignored failing allocator");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed with allocation count 10");
    +}
    +END_TEST
    +
    +
    +static int XMLCALL
    +external_entity_dbl_handler(XML_Parser parser,
    +                            const XML_Char *context,
    +                            const XML_Char *UNUSED_P(base),
    +                            const XML_Char *UNUSED_P(systemId),
    +                            const XML_Char *UNUSED_P(publicId))
    +{
    +    intptr_t callno = (intptr_t)XML_GetUserData(parser);
    +    const char *text;
    +    XML_Parser new_parser;
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    if (callno == 0) {
    +        /* First time through, check how many calls to malloc occur */
    +        text = ("\n"
    +                "\n"
    +                "\n");
    +        allocation_count = 10000;
    +        new_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +        if (new_parser == NULL) {
    +            fail("Unable to allocate first external parser");
    +            return XML_STATUS_ERROR;
    +        }
    +        /* Stash the number of calls in the user data */
    +        XML_SetUserData(parser, (void *)(intptr_t)(10000 - allocation_count));
    +    } else {
    +        text = (""
    +                "");
    +        /* Try at varying levels to exercise more code paths */
    +        for (i = 0; i < max_alloc_count; i++) {
    +            allocation_count = callno + i;
    +            new_parser = XML_ExternalEntityParserCreate(parser,
    +                                                        context,
    +                                                        NULL);
    +            if (new_parser != NULL)
    +                break;
    +        }
    +        if (i == 0) {
    +            fail("Second external parser unexpectedly created");
    +            XML_ParserFree(new_parser);
    +            return XML_STATUS_ERROR;
    +        }
    +        else if (i == max_alloc_count) {
    +            fail("Second external parser not created");
    +            return XML_STATUS_ERROR;
    +        }
    +    }
    +
    +    allocation_count = ALLOC_ALWAYS_SUCCEED;
    +    if (_XML_Parse_SINGLE_BYTES(new_parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR) {
    +        xml_failure(new_parser);
    +        return XML_STATUS_ERROR;
    +    }
    +    XML_ParserFree(new_parser);
    +    return XML_STATUS_OK;
    +}
    +
    +/* Test that running out of memory in dtdCopy is correctly reported.
    + * Based on test_default_ns_from_ext_subset_and_ext_ge()
    + */
    +START_TEST(test_alloc_dtd_copy_default_atts)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;\n"
    +        "";
    +
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser,
    +                                    external_entity_dbl_handler);
    +    XML_SetUserData(parser, NULL);
    +    if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +}
    +END_TEST
    +
    +
    +static int XMLCALL
    +external_entity_dbl_handler_2(XML_Parser parser,
    +                              const XML_Char *context,
    +                              const XML_Char *UNUSED_P(base),
    +                              const XML_Char *UNUSED_P(systemId),
    +                              const XML_Char *UNUSED_P(publicId))
    +{
    +    intptr_t callno = (intptr_t)XML_GetUserData(parser);
    +    const char *text;
    +    XML_Parser new_parser;
    +    enum XML_Status rv;
    +
    +    if (callno == 0) {
    +        /* Try different allocation levels for whole exercise */
    +        text = ("\n"
    +                "\n"
    +                "\n");
    +        XML_SetUserData(parser, (void *)(intptr_t)1);
    +        new_parser = XML_ExternalEntityParserCreate(parser,
    +                                                    context,
    +                                                    NULL);
    +        if (new_parser == NULL)
    +            return XML_STATUS_ERROR;
    +        rv = _XML_Parse_SINGLE_BYTES(new_parser, text, (int)strlen(text),
    +                                     XML_TRUE);
    +    } else {
    +        /* Just run through once */
    +        text = (""
    +                "");
    +        new_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +        if (new_parser == NULL)
    +            return XML_STATUS_ERROR;
    +        rv =_XML_Parse_SINGLE_BYTES(new_parser, text, (int)strlen(text),
    +                                    XML_TRUE);
    +    }
    +    XML_ParserFree(new_parser);
    +    if (rv == XML_STATUS_ERROR)
    +        return XML_STATUS_ERROR;
    +    return XML_STATUS_OK;
    +}
    +
    +/* Test more external entity allocation failure paths */
    +START_TEST(test_alloc_external_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;\n"
    +        "";
    +    int i;
    +    const int alloc_test_max_repeats = 50;
    +
    +    for (i = 0; i < alloc_test_max_repeats; i++) {
    +        allocation_count = -1;
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser,
    +                                        external_entity_dbl_handler_2);
    +        XML_SetUserData(parser, NULL);
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) == XML_STATUS_OK)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    allocation_count = -1;
    +    if (i == 0)
    +        fail("External entity parsed despite duff allocator");
    +    if (i == alloc_test_max_repeats)
    +        fail("External entity not parsed at max allocation count");
    +}
    +END_TEST
    +
    +/* Test more allocation failure paths */
    +static int XMLCALL
    +external_entity_alloc_set_encoding(XML_Parser parser,
    +                                   const XML_Char *context,
    +                                   const XML_Char *UNUSED_P(base),
    +                                   const XML_Char *UNUSED_P(systemId),
    +                                   const XML_Char *UNUSED_P(publicId))
    +{
    +    /* As for external_entity_loader() */
    +    const char *text =
    +        ""
    +        "\xC3\xA9";
    +    XML_Parser ext_parser;
    +    enum XML_Status status;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        return XML_STATUS_ERROR;
    +    if (!XML_SetEncoding(ext_parser, XCS("utf-8"))) {
    +        XML_ParserFree(ext_parser);
    +        return XML_STATUS_ERROR;
    +    }
    +    status = _XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                     XML_TRUE);
    +    XML_ParserFree(ext_parser);
    +    if (status == XML_STATUS_ERROR)
    +        return XML_STATUS_ERROR;
    +    return XML_STATUS_OK;
    +}
    +
    +START_TEST(test_alloc_ext_entity_set_encoding)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    int i;
    +    const int max_allocation_count = 30;
    +
    +    for (i = 0; i < max_allocation_count; i++) {
    +        XML_SetExternalEntityRefHandler(parser,
    +                                        external_entity_alloc_set_encoding);
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) == XML_STATUS_OK)
    +            break;
    +        allocation_count = -1;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Encoding check succeeded despite failing allocator");
    +    if (i == max_allocation_count)
    +        fail("Encoding failed at max allocation count");
    +}
    +END_TEST
    +
    +static int XMLCALL
    +unknown_released_encoding_handler(void *UNUSED_P(data),
    +                                  const XML_Char *encoding,
    +                                  XML_Encoding *info)
    +{
    +    if (!xcstrcmp(encoding, XCS("unsupported-encoding"))) {
    +        int i;
    +
    +        for (i = 0; i < 256; i++)
    +            info->map[i] = i;
    +        info->data = NULL;
    +        info->convert = NULL;
    +        info->release = dummy_release;
    +        return XML_STATUS_OK;
    +    }
    +    return XML_STATUS_ERROR;
    +}
    +
    +/* Test the effects of allocation failure in internal entities.
    + * Based on test_unknown_encoding_internal_entity
    + */
    +START_TEST(test_alloc_internal_entity)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "";
    +    unsigned int i;
    +    const unsigned int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUnknownEncodingHandler(parser,
    +                                      unknown_released_encoding_handler,
    +                                      NULL);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Internal entity worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Internal entity failed at max allocation count");
    +}
    +END_TEST
    +
    +
    +/* Test the robustness against allocation failure of element handling
    + * Based on test_dtd_default_handling().
    + */
    +START_TEST(test_alloc_dtd_default_handling)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "\n"
    +        "\n"
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        "";
    +    const XML_Char *expected = XCS("\n\n\n\n\n\n\n\n\ntext in doc");
    +    CharData storage;
    +    int i;
    +    const int max_alloc_count = 25;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        dummy_handler_flags = 0;
    +        XML_SetDefaultHandler(parser, accumulate_characters);
    +        XML_SetDoctypeDeclHandler(parser,
    +                                  dummy_start_doctype_handler,
    +                                  dummy_end_doctype_handler);
    +        XML_SetEntityDeclHandler(parser, dummy_entity_decl_handler);
    +        XML_SetNotationDeclHandler(parser, dummy_notation_decl_handler);
    +        XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +        XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
    +        XML_SetProcessingInstructionHandler(parser, dummy_pi_handler);
    +        XML_SetCommentHandler(parser, dummy_comment_handler);
    +        XML_SetCdataSectionHandler(parser,
    +                                   dummy_start_cdata_handler,
    +                                   dummy_end_cdata_handler);
    +        XML_SetUnparsedEntityDeclHandler(
    +            parser,
    +            dummy_unparsed_entity_decl_handler);
    +        CharData_Init(&storage);
    +        XML_SetUserData(parser, &storage);
    +        XML_SetCharacterDataHandler(parser, accumulate_characters);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Default DTD parsed despite allocation failures");
    +    if (i == max_alloc_count)
    +        fail("Default DTD not parsed with maximum alloc count");
    +    CharData_CheckXMLChars(&storage, expected);
    +    if (dummy_handler_flags != (DUMMY_START_DOCTYPE_HANDLER_FLAG |
    +                                DUMMY_END_DOCTYPE_HANDLER_FLAG |
    +                                DUMMY_ENTITY_DECL_HANDLER_FLAG |
    +                                DUMMY_NOTATION_DECL_HANDLER_FLAG |
    +                                DUMMY_ELEMENT_DECL_HANDLER_FLAG |
    +                                DUMMY_ATTLIST_DECL_HANDLER_FLAG |
    +                                DUMMY_COMMENT_HANDLER_FLAG |
    +                                DUMMY_PI_HANDLER_FLAG |
    +                                DUMMY_START_CDATA_HANDLER_FLAG |
    +                                DUMMY_END_CDATA_HANDLER_FLAG |
    +                                DUMMY_UNPARSED_ENTITY_DECL_HANDLER_FLAG))
    +        fail("Not all handlers were called");
    +}
    +END_TEST
    +
    +/* Test robustness of XML_SetEncoding() with a failing allocator */
    +START_TEST(test_alloc_explicit_encoding)
    +{
    +    int i;
    +    const int max_alloc_count = 5;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (XML_SetEncoding(parser, XCS("us-ascii")) == XML_STATUS_OK)
    +            break;
    +    }
    +    if (i == 0)
    +        fail("Encoding set despite failing allocator");
    +    else if (i == max_alloc_count)
    +        fail("Encoding not set at max allocation count");
    +}
    +END_TEST
    +
    +/* Test robustness of XML_SetBase against a failing allocator */
    +START_TEST(test_alloc_set_base)
    +{
    +    const XML_Char *new_base = XCS("/local/file/name.xml");
    +    int i;
    +    const int max_alloc_count = 5;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (XML_SetBase(parser, new_base) == XML_STATUS_OK)
    +            break;
    +    }
    +    if (i == 0)
    +        fail("Base set despite failing allocator");
    +    else if (i == max_alloc_count)
    +        fail("Base not set with max allocation count");
    +}
    +END_TEST
    +
    +/* Test buffer extension in the face of a duff reallocator */
    +START_TEST(test_alloc_realloc_buffer)
    +{
    +    const char *text = get_buffer_test_text;
    +    void *buffer;
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    /* Get a smallish buffer */
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        buffer = XML_GetBuffer(parser, 1536);
    +        if (buffer == NULL)
    +            fail("1.5K buffer reallocation failed");
    +        memcpy(buffer, text, strlen(text));
    +        if (XML_ParseBuffer(parser, (int)strlen(text),
    +                            XML_FALSE) == XML_STATUS_OK)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    reallocation_count = -1;
    +    if (i == 0)
    +        fail("Parse succeeded with no reallocation");
    +    else if (i == max_realloc_count)
    +        fail("Parse failed with max reallocation count");
    +}
    +END_TEST
    +
    +/* Same test for external entity parsers */
    +static int XMLCALL
    +external_entity_reallocator(XML_Parser parser,
    +                            const XML_Char *context,
    +                            const XML_Char *UNUSED_P(base),
    +                            const XML_Char *UNUSED_P(systemId),
    +                            const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = get_buffer_test_text;
    +    XML_Parser ext_parser;
    +    void *buffer;
    +    enum XML_Status status;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        fail("Could not create external entity parser");
    +
    +    reallocation_count = (intptr_t)XML_GetUserData(parser);
    +    buffer = XML_GetBuffer(ext_parser, 1536);
    +    if (buffer == NULL)
    +        fail("Buffer allocation failed");
    +    memcpy(buffer, text, strlen(text));
    +    status = XML_ParseBuffer(ext_parser, (int)strlen(text), XML_FALSE);
    +    reallocation_count = -1;
    +    XML_ParserFree(ext_parser);
    +    return (status == XML_STATUS_OK) ? XML_STATUS_OK : XML_STATUS_ERROR;
    +}
    +
    +START_TEST(test_alloc_ext_entity_realloc_buffer)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        XML_SetExternalEntityRefHandler(parser,
    +                                        external_entity_reallocator);
    +        XML_SetUserData(parser, (void *)(intptr_t)i);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) == XML_STATUS_OK)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Succeeded with no reallocations");
    +    if (i == max_realloc_count)
    +        fail("Failed with max reallocations");
    +}
    +END_TEST
    +
    +/* Test elements with many attributes are handled correctly */
    +START_TEST(test_alloc_realloc_many_attributes)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "]>\n"
    +        ""
    +        "";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite no reallocations");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at max reallocations");
    +}
    +END_TEST
    +
    +/* Test handling of a public entity with failing allocator */
    +START_TEST(test_alloc_public_entity_value)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +    char dtd_text[] =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "%e1;\n";
    +    int i;
    +    const int max_alloc_count = 50;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        dummy_handler_flags = 0;
    +        XML_SetUserData(parser, dtd_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_public);
    +        /* Provoke a particular code path */
    +        XML_SetEntityDeclHandler(parser, dummy_entity_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocation");
    +    if (i == max_alloc_count)
    +        fail("Parsing failed at max allocation count");
    +    if (dummy_handler_flags != DUMMY_ENTITY_DECL_HANDLER_FLAG)
    +        fail("Entity declaration handler not called");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_realloc_subst_public_entity_value)
    +{
    +    const char *text =
    +        "\n"
    +        "\n";
    +    char dtd_text[] =
    +        "\n"
    +        "\n"
    +        "%ThisIsAStupidlyLongParameterNameIntendedToTriggerPoolGrowth12345"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP;";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetUserData(parser, dtd_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_public);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocation");
    +    if (i == max_realloc_count)
    +        fail("Parsing failed at max reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_parse_public_doctype)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 25;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        dummy_handler_flags = 0;
    +        XML_SetDoctypeDeclHandler(parser,
    +                                  dummy_start_doctype_decl_handler,
    +                                  dummy_end_doctype_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +    if (dummy_handler_flags != (DUMMY_START_DOCTYPE_DECL_HANDLER_FLAG |
    +                                DUMMY_END_DOCTYPE_DECL_HANDLER_FLAG))
    +        fail("Doctype handler functions not called");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_parse_public_doctype_long_name)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 25;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetDoctypeDeclHandler(parser,
    +                                  dummy_start_doctype_decl_handler,
    +                                  dummy_end_doctype_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +}
    +END_TEST
    +
    +static int XMLCALL
    +external_entity_alloc(XML_Parser parser,
    +                      const XML_Char *context,
    +                      const XML_Char *UNUSED_P(base),
    +                      const XML_Char *UNUSED_P(systemId),
    +                      const XML_Char *UNUSED_P(publicId))
    +{
    +    const char *text = (const char *)XML_GetUserData(parser);
    +    XML_Parser ext_parser;
    +    int parse_res;
    +
    +    ext_parser = XML_ExternalEntityParserCreate(parser, context, NULL);
    +    if (ext_parser == NULL)
    +        return XML_STATUS_ERROR;
    +    parse_res = _XML_Parse_SINGLE_BYTES(ext_parser, text, (int)strlen(text),
    +                                        XML_TRUE);
    +    XML_ParserFree(ext_parser);
    +    return parse_res;
    +}
    +
    +/* Test foreign DTD handling */
    +START_TEST(test_alloc_set_foreign_dtd)
    +{
    +    const char *text1 =
    +        "\n"
    +        "&entity;";
    +    char text2[] = "";
    +    int i;
    +    const int max_alloc_count = 25;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetUserData(parser, &text2);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        if (XML_UseForeignDTD(parser, XML_TRUE) != XML_ERROR_NONE)
    +            fail("Could not set foreign DTD");
    +        if (_XML_Parse_SINGLE_BYTES(parser, text1, (int)strlen(text1),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +}
    +END_TEST
    +
    +/* Test based on ibm/valid/P32/ibm32v04.xml */
    +START_TEST(test_alloc_attribute_enum_value)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "This is a \n      \n\nyellow tiger";
    +    char dtd_text[] =
    +        "\n"
    +        "\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 30;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        XML_SetUserData(parser, dtd_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        /* An attribute list handler provokes a different code path */
    +        XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +}
    +END_TEST
    +
    +/* Test attribute enums sufficient to overflow the string pool */
    +START_TEST(test_alloc_realloc_attribute_enum_value)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "This is a yellow tiger";
    +    /* We wish to define a collection of attribute enums that will
    +     * cause the string pool storing them to have to expand.  This
    +     * means more than 1024 bytes, including the parentheses and
    +     * separator bars.
    +     */
    +    char dtd_text[] =
    +        "\n"
    +        "";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        XML_SetUserData(parser, dtd_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        /* An attribute list handler provokes a different code path */
    +        XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +}
    +END_TEST
    +
    +/* Test attribute enums in a #IMPLIED attribute forcing pool growth */
    +START_TEST(test_alloc_realloc_implied_attribute)
    +{
    +    /* Forcing this particular code path is a balancing act.  The
    +     * addition of the closing parenthesis and terminal NUL must be
    +     * what pushes the string of enums over the 1024-byte limit,
    +     * otherwise a different code path will pick up the realloc.
    +     */
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "]>";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +}
    +END_TEST
    +
    +/* Test attribute enums in a defaulted attribute forcing pool growth */
    +START_TEST(test_alloc_realloc_default_attribute)
    +{
    +    /* Forcing this particular code path is a balancing act.  The
    +     * addition of the closing parenthesis and terminal NUL must be
    +     * what pushes the string of enums over the 1024-byte limit,
    +     * otherwise a different code path will pick up the realloc.
    +     */
    +    const char *text =
    +        "\n"
    +        "\n]>";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetAttlistDeclHandler(parser, dummy_attlist_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +}
    +END_TEST
    +
    +/* Test long notation name with dodgy allocator */
    +START_TEST(test_alloc_notation)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "]>\n";
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        dummy_handler_flags = 0;
    +        XML_SetNotationDeclHandler(parser, dummy_notation_decl_handler);
    +        XML_SetEntityDeclHandler(parser, dummy_entity_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite allocation failures");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +    if (dummy_handler_flags != (DUMMY_ENTITY_DECL_HANDLER_FLAG |
    +                                DUMMY_NOTATION_DECL_HANDLER_FLAG))
    +        fail("Entity declaration handler not called");
    +}
    +END_TEST
    +
    +/* Test public notation with dodgy allocator */
    +START_TEST(test_alloc_public_notation)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "]>\n";
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        dummy_handler_flags = 0;
    +        XML_SetNotationDeclHandler(parser, dummy_notation_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite allocation failures");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +    if (dummy_handler_flags != DUMMY_NOTATION_DECL_HANDLER_FLAG)
    +        fail("Notation handler not called");
    +}
    +END_TEST
    +
    +/* Test public notation with dodgy allocator */
    +START_TEST(test_alloc_system_notation)
    +{
    +    const char *text =
    +        "\n"
    +        "\n"
    +        "\n"
    +        "]>\n";
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        dummy_handler_flags = 0;
    +        XML_SetNotationDeclHandler(parser, dummy_notation_decl_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite allocation failures");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +    if (dummy_handler_flags != DUMMY_NOTATION_DECL_HANDLER_FLAG)
    +        fail("Notation handler not called");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_nested_groups)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "]>\n"
    +        "";
    +    CharData storage;
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        CharData_Init(&storage);
    +        XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +        XML_SetStartElementHandler(parser, record_element_start_handler);
    +        XML_SetUserData(parser, &storage);
    +        dummy_handler_flags = 0;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +    CharData_CheckXMLChars(&storage, XCS("doce"));
    +    if (dummy_handler_flags != DUMMY_ELEMENT_DECL_HANDLER_FLAG)
    +        fail("Element handler not fired");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_realloc_nested_groups)
    +{
    +    const char *text =
    +        "\n"
    +        ""
    +        "]>\n"
    +        "";
    +    CharData storage;
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        CharData_Init(&storage);
    +        XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +        XML_SetStartElementHandler(parser, record_element_start_handler);
    +        XML_SetUserData(parser, &storage);
    +        dummy_handler_flags = 0;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +    CharData_CheckXMLChars(&storage, XCS("doce"));
    +    if (dummy_handler_flags != DUMMY_ELEMENT_DECL_HANDLER_FLAG)
    +        fail("Element handler not fired");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_large_group)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "\n"
    +        "\n";
    +    int i;
    +    const int max_alloc_count = 50;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +        dummy_handler_flags = 0;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +    if (dummy_handler_flags != DUMMY_ELEMENT_DECL_HANDLER_FLAG)
    +        fail("Element handler flag not raised");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_realloc_group_choice)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "\n"
    +        "This is a foo\n"
    +        "\n"
    +        "\n";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetElementDeclHandler(parser, dummy_element_decl_handler);
    +        dummy_handler_flags = 0;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +    if (dummy_handler_flags != DUMMY_ELEMENT_DECL_HANDLER_FLAG)
    +        fail("Element handler flag not raised");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_pi_in_epilog)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetProcessingInstructionHandler(parser, dummy_pi_handler);
    +        dummy_handler_flags = 0;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse completed despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +    if (dummy_handler_flags != DUMMY_PI_HANDLER_FLAG)
    +        fail("Processing instruction handler not invoked");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_comment_in_epilog)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetCommentHandler(parser, dummy_comment_handler);
    +        dummy_handler_flags = 0;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse completed despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +    if (dummy_handler_flags != DUMMY_COMMENT_HANDLER_FLAG)
    +        fail("Processing instruction handler not invoked");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_realloc_long_attribute_value)
    +{
    +    const char *text =
    +        "]>\n"
    +        "";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_attribute_whitespace)
    +{
    +    const char *text = "";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_attribute_predefined_entity)
    +{
    +    const char *text = "";
    +    int i;
    +    const int max_alloc_count = 15;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +}
    +END_TEST
    +
    +/* Test that a character reference at the end of a suitably long
    + * default value for an attribute can trigger pool growth, and recovers
    + * if the allocator fails on it.
    + */
    +START_TEST(test_alloc_long_attr_default_with_char_ref)
    +{
    +    const char *text =
    +        "]>\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +}
    +END_TEST
    +
    +/* Test that a long character reference substitution triggers a pool
    + * expansion correctly for an attribute value.
    + */
    +START_TEST(test_alloc_long_attr_value)
    +{
    +    const char *text =
    +        "]>\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 25;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing allocator");
    +    if (i == max_alloc_count)
    +        fail("Parse failed at maximum allocation count");
    +}
    +END_TEST
    +
    +/* Test that an error in a nested parameter entity substitution is
    + * handled correctly.  It seems unlikely that the code path being
    + * exercised can be reached purely by carefully crafted XML, but an
    + * allocation error in the right place will definitely do it.
    + */
    +START_TEST(test_alloc_nested_entities)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    ExtFaults test_data = {
    +        "\n"
    +        "\n"
    +        "%pe2;",
    +        "Memory Fail not faulted",
    +        NULL,
    +        XML_ERROR_NO_MEMORY
    +    };
    +
    +    /* Causes an allocation error in a nested storeEntityValue() */
    +    allocation_count = 12;
    +    XML_SetUserData(parser, &test_data);
    +    XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +    XML_SetExternalEntityRefHandler(parser, external_entity_faulter);
    +    expect_failure(text, XML_ERROR_EXTERNAL_ENTITY_HANDLING,
    +                   "Entity allocation failure not noted");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_realloc_param_entity_newline)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    char dtd_text[] =
    +        "\n'>"
    +        "%pe;\n";
    +    int i;
    +    const int max_realloc_count = 5;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetUserData(parser, dtd_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_realloc_ce_extends_pe)
    +{
    +    const char *text =
    +        "\n"
    +        "";
    +    char dtd_text[] =
    +        "\n'>"
    +        "%pe;\n";
    +    int i;
    +    const int max_realloc_count = 5;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetUserData(parser, dtd_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_realloc_attributes)
    +{
    +    const char *text =
    +        "]>\n"
    +        "wombat\n";
    +    int i;
    +    const int max_realloc_count = 5;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +
    +    if (i == 0)
    +        fail("Parse succeeded despite failing reallocator");
    +    if (i == max_realloc_count)
    +        fail("Parse failed at maximum reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_long_doc_name)
    +{
    +    const char *text =
    +        /* 64 characters per line */
    +        "";
    +    int i;
    +    const int max_alloc_count = 20;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_long_base)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&e;";
    +    char entity_text[] = "Hello world";
    +    const XML_Char *base =
    +        /* 64 characters per line */
    +        XCS("LongBaseURI/that/will/overflow/an/internal/buffer/and/cause/it/t")
    +        XCS("o/have/to/grow/PQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789A/");
    +    int i;
    +    const int max_alloc_count = 25;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, entity_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        if (XML_SetBase(parser, base) == XML_STATUS_ERROR) {
    +            XML_ParserReset(parser, NULL);
    +            continue;
    +        }
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_long_public_id)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&e;";
    +    char entity_text[] = "Hello world";
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, entity_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_long_entity_value)
    +{
    +    const char *text =
    +        "\n"
    +        "  \n"
    +        "]>\n"
    +        "&e2;";
    +    char entity_text[] = "Hello world";
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, entity_text);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_alloc);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_alloc_long_notation)
    +{
    +    const char *text =
    +        "\n"
    +        "  \n"
    +        "  \n"
    +        "]>\n"
    +        "&e2;";
    +    ExtOption options[] = {
    +        { XCS("foo"), "Entity Foo" },
    +        { XCS("bar"), "Entity Bar" },
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +
    +        /* See comment in test_alloc_parse_xdecl() */
    +        alloc_teardown();
    +        alloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +
    +static void
    +nsalloc_setup(void)
    +{
    +    XML_Memory_Handling_Suite memsuite = {
    +        duff_allocator,
    +        duff_reallocator,
    +        free
    +    };
    +    XML_Char ns_sep[2] = { ' ', '\0' };
    +
    +    /* Ensure the parser creation will go through */
    +    allocation_count = ALLOC_ALWAYS_SUCCEED;
    +    reallocation_count = REALLOC_ALWAYS_SUCCEED;
    +    parser = XML_ParserCreate_MM(NULL, &memsuite, ns_sep);
    +    if (parser == NULL)
    +        fail("Parser not created");
    +}
    +
    +static void
    +nsalloc_teardown(void)
    +{
    +    basic_teardown();
    +}
    +
    +
    +/* Test the effects of allocation failure in simple namespace parsing.
    + * Based on test_ns_default_with_empty_uri()
    + */
    +START_TEST(test_nsalloc_xmlns)
    +{
    +    const char *text =
    +        "\n"
    +        "  \n"
    +        "";
    +    unsigned int i;
    +    const unsigned int max_alloc_count = 30;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        /* Exercise more code paths with a default handler */
    +        XML_SetDefaultHandler(parser, dummy_default_handler);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* Resetting the parser is insufficient, because some memory
    +         * allocations are cached within the parser.  Instead we use
    +         * the teardown and setup routines to ensure that we have the
    +         * right sort of parser back in our hands.
    +         */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at maximum allocation count");
    +}
    +END_TEST
    +
    +/* Test XML_ParseBuffer interface with namespace and a dicky allocator */
    +START_TEST(test_nsalloc_parse_buffer)
    +{
    +    const char *text = "Hello";
    +    void *buffer;
    +
    +    /* Try a parse before the start of the world */
    +    /* (Exercises new code path) */
    +    allocation_count = 0;
    +    if (XML_ParseBuffer(parser, 0, XML_FALSE) != XML_STATUS_ERROR)
    +        fail("Pre-init XML_ParseBuffer not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_NO_MEMORY)
    +        fail("Pre-init XML_ParseBuffer faulted for wrong reason");
    +
    +    /* Now with actual memory allocation */
    +    allocation_count = ALLOC_ALWAYS_SUCCEED;
    +    if (XML_ParseBuffer(parser, 0, XML_FALSE) != XML_STATUS_OK)
    +        xml_failure(parser);
    +
    +    /* Check that resuming an unsuspended parser is faulted */
    +    if (XML_ResumeParser(parser) != XML_STATUS_ERROR)
    +        fail("Resuming unsuspended parser not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_NOT_SUSPENDED)
    +        xml_failure(parser);
    +
    +    /* Get the parser into suspended state */
    +    XML_SetCharacterDataHandler(parser, clearing_aborting_character_handler);
    +    resumable = XML_TRUE;
    +    buffer = XML_GetBuffer(parser, (int)strlen(text));
    +    if (buffer == NULL)
    +        fail("Could not acquire parse buffer");
    +    memcpy(buffer, text, strlen(text));
    +    if (XML_ParseBuffer(parser, (int)strlen(text),
    +                        XML_TRUE) != XML_STATUS_SUSPENDED)
    +        xml_failure(parser);
    +    if (XML_GetErrorCode(parser) != XML_ERROR_NONE)
    +        xml_failure(parser);
    +    if (XML_ParseBuffer(parser, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Suspended XML_ParseBuffer not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_SUSPENDED)
    +        xml_failure(parser);
    +    if (XML_GetBuffer(parser, (int)strlen(text)) != NULL)
    +        fail("Suspended XML_GetBuffer not faulted");
    +
    +    /* Get it going again and complete the world */
    +    XML_SetCharacterDataHandler(parser, NULL);
    +    if (XML_ResumeParser(parser) != XML_STATUS_OK)
    +        xml_failure(parser);
    +    if (XML_ParseBuffer(parser, (int)strlen(text), XML_TRUE) != XML_STATUS_ERROR)
    +        fail("Post-finishing XML_ParseBuffer not faulted");
    +    if (XML_GetErrorCode(parser) != XML_ERROR_FINISHED)
    +        xml_failure(parser);
    +    if (XML_GetBuffer(parser, (int)strlen(text)) != NULL)
    +        fail("Post-finishing XML_GetBuffer not faulted");
    +}
    +END_TEST
    +
    +/* Check handling of long prefix names (pool growth) */
    +START_TEST(test_nsalloc_long_prefix)
    +{
    +    const char *text =
    +        "<"
    +        /* 64 characters per line */
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        ":foo xmlns:"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "='http://example.org/'>"
    +        "";
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +/* Check handling of long uri names (pool growth) */
    +START_TEST(test_nsalloc_long_uri)
    +{
    +    const char *text =
    +        ""
    +        "";
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +/* Test handling of long attribute names with prefixes */
    +START_TEST(test_nsalloc_long_attr)
    +{
    +    const char *text =
    +        ""
    +        "";
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +/* Test handling of an attribute name with a long namespace prefix */
    +START_TEST(test_nsalloc_long_attr_prefix)
    +{
    +    const char *text =
    +        ""
    +        "";
    +    const XML_Char *elemstr[] = {
    +        XCS("http://example.org/ e foo"),
    +        XCS("http://example.org/ a ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +        XCS("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ")
    +    };
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetReturnNSTriplet(parser, XML_TRUE);
    +        XML_SetUserData(parser, (void *)elemstr);
    +        XML_SetElementHandler(parser,
    +                              triplet_start_checker,
    +                              triplet_end_checker);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +/* Test attribute handling in the face of a dodgy reallocator */
    +START_TEST(test_nsalloc_realloc_attributes)
    +{
    +    const char *text =
    +        ""
    +        "";
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_realloc_count)
    +        fail("Parsing failed at max reallocation count");
    +}
    +END_TEST
    +
    +/* Test long element names with namespaces under a failing allocator */
    +START_TEST(test_nsalloc_long_element)
    +{
    +    const char *text =
    +        ""
    +        "";
    +    const XML_Char *elemstr[] = {
    +        XCS("http://example.org/")
    +        XCS(" thisisalongenoughelementnametotriggerareallocation foo"),
    +        XCS("http://example.org/ a bar")
    +    };
    +    int i;
    +    const int max_alloc_count = 30;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetReturnNSTriplet(parser, XML_TRUE);
    +        XML_SetUserData(parser, (void *)elemstr);
    +        XML_SetElementHandler(parser,
    +                              triplet_start_checker,
    +                              triplet_end_checker);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed at max reallocation count");
    +}
    +END_TEST
    +
    +/* Test the effects of reallocation failure when reassigning a
    + * binding.
    + *
    + * XML_ParserReset does not free the BINDING structures used by a
    + * parser, but instead adds them to an internal free list to be reused
    + * as necessary.  Likewise the URI buffers allocated for the binding
    + * aren't freed, but kept attached to their existing binding.  If the
    + * new binding has a longer URI, it will need reallocation.  This test
    + * provokes that reallocation, and tests the control path if it fails.
    + */
    +START_TEST(test_nsalloc_realloc_binding_uri)
    +{
    +    const char *first =
    +        "\n"
    +        "  \n"
    +        "";
    +    const char *second =
    +        "\n"
    +        "  \n"
    +        "";
    +    unsigned i;
    +    const unsigned max_realloc_count = 10;
    +
    +    /* First, do a full parse that will leave bindings around */
    +    if (_XML_Parse_SINGLE_BYTES(parser, first, (int)strlen(first),
    +                                XML_TRUE) == XML_STATUS_ERROR)
    +        xml_failure(parser);
    +
    +    /* Now repeat with a longer URI and a duff reallocator */
    +    for (i = 0; i < max_realloc_count; i++) {
    +        XML_ParserReset(parser, NULL);
    +        reallocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, second, (int)strlen(second),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocation");
    +    else if (i == max_realloc_count)
    +        fail("Parsing failed at max reallocation count");
    +}
    +END_TEST
    +
    +/* Check handling of long prefix names (pool growth) */
    +START_TEST(test_nsalloc_realloc_long_prefix)
    +{
    +    const char *text =
    +        "<"
    +        /* 64 characters per line */
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        ":foo xmlns:"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "='http://example.org/'>"
    +        "";
    +    int i;
    +    const int max_realloc_count = 12;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_realloc_count)
    +        fail("Parsing failed even at max reallocation count");
    +}
    +END_TEST
    +
    +/* Check handling of even long prefix names (different code path) */
    +START_TEST(test_nsalloc_realloc_longer_prefix)
    +{
    +    const char *text =
    +        "<"
    +        /* 64 characters per line */
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "Q:foo xmlns:"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "Q='http://example.org/'>"
    +        "";
    +    int i;
    +    const int max_realloc_count = 12;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_realloc_count)
    +        fail("Parsing failed even at max reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_long_namespace)
    +{
    +    const char *text1 =
    +        "<"
    +        /* 64 characters per line */
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        ":e xmlns:"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "='http://example.org/'>\n";
    +    const char *text2 =
    +        "<"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        ":f "
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        ":attr='foo'/>\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text1, (int)strlen(text1),
    +                                    XML_FALSE) != XML_STATUS_ERROR &&
    +            _XML_Parse_SINGLE_BYTES(parser, text2, (int)strlen(text2),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +/* Using a slightly shorter namespace name provokes allocations in
    + * slightly different places in the code.
    + */
    +START_TEST(test_nsalloc_less_long_namespace)
    +{
    +    const char *text =
    +        "<"
    +        /* 64 characters per line */
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678"
    +        ":e xmlns:"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678"
    +        "='http://example.org/'>\n"
    +        "<"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678"
    +        ":f "
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789AZ"
    +        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678"
    +        ":att='foo'/>\n"
    +        "";
    +    int i;
    +    const int max_alloc_count = 40;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_long_context)
    +{
    +    const char *text =
    +        "\n"
    +        "  \n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +    ExtOption options[] = {
    +        { XCS("foo"), ""},
    +        { XCS("bar"), "" },
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_alloc_count = 70;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +/* This function is void; it will throw a fail() on error, so if it
    + * returns normally it must have succeeded.
    + */
    +static void
    +context_realloc_test(const char *text)
    +{
    +    ExtOption options[] = {
    +        { XCS("foo"), ""},
    +        { XCS("bar"), "" },
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_realloc_count = 6;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_realloc_count)
    +        fail("Parsing failed even at max reallocation count");
    +}
    +
    +START_TEST(test_nsalloc_realloc_long_context)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +
    +    context_realloc_test(text);
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_realloc_long_context_2)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +
    +    context_realloc_test(text);
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_realloc_long_context_3)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +
    +    context_realloc_test(text);
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_realloc_long_context_4)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +
    +    context_realloc_test(text);
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_realloc_long_context_5)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +
    +    context_realloc_test(text);
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_realloc_long_context_6)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +
    +    context_realloc_test(text);
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_realloc_long_context_7)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +
    +    context_realloc_test(text);
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_realloc_long_ge_name)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "\n"
    +        "&"
    +        /* 64 characters per line */
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        ";"
    +        "";
    +    ExtOption options[] = {
    +        { XCS("foo"), "" },
    +        { XCS("bar"), "" },
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_realloc_count = 10;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_realloc_count)
    +        fail("Parsing failed even at max reallocation count");
    +}
    +END_TEST
    +
    +/* Test that when a namespace is passed through the context mechanism
    + * to an external entity parser, the parsers handle reallocation
    + * failures correctly.  The prefix is exactly the right length to
    + * provoke particular uncommon code paths.
    + */
    +START_TEST(test_nsalloc_realloc_long_context_in_dtd)
    +{
    +    const char *text1 =
    +        "\n"
    +        "]>\n"
    +        "<"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        ":doc xmlns:"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "ABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOPABCDEFGHIJKLMNOP"
    +        "='foo/Second'>&First;";
    +    const char *text2 = "";
    +    ExtOption options[] = {
    +        { XCS("foo/First"), "Hello world" },
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_realloc_count = 20;
    +
    +    for (i = 0; i < max_realloc_count; i++) {
    +        reallocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text1, (int)strlen(text1),
    +                                    XML_FALSE) != XML_STATUS_ERROR &&
    +            _XML_Parse_SINGLE_BYTES(parser, text2, (int)strlen(text2),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing reallocations");
    +    else if (i == max_realloc_count)
    +        fail("Parsing failed even at max reallocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_long_default_in_ext)
    +{
    +    const char *text =
    +        "\n"
    +        "  \n"
    +        "]>\n"
    +        "&x;";
    +    ExtOption options[] = {
    +        { XCS("foo"), ""},
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_alloc_count = 50;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +START_TEST(test_nsalloc_long_systemid_in_ext)
    +{
    +    const char *text =
    +        "\n"
    +        "]>\n"
    +        "&en;";
    +    ExtOption options[] = {
    +        { XCS("foo"), "" },
    +        {
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/")
    +            XCS("ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/ABCDEFGHIJKLMNO/"),
    +            ""
    +        },
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_alloc_count = 55;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Parsing worked despite failing allocations");
    +    else if (i == max_alloc_count)
    +        fail("Parsing failed even at max allocation count");
    +}
    +END_TEST
    +
    +/* Test the effects of allocation failure on parsing an element in a
    + * namespace.  Based on test_nsalloc_long_context.
    + */
    +START_TEST(test_nsalloc_prefixed_element)
    +{
    +    const char *text =
    +        "\n"
    +        "  \n"
    +        "]>\n"
    +        "\n"
    +        "&en;"
    +        "";
    +    ExtOption options[] = {
    +        { XCS("foo"), "" },
    +        { XCS("bar"), "" },
    +        { NULL, NULL }
    +    };
    +    int i;
    +    const int max_alloc_count = 70;
    +
    +    for (i = 0; i < max_alloc_count; i++) {
    +        allocation_count = i;
    +        XML_SetUserData(parser, options);
    +        XML_SetParamEntityParsing(parser, XML_PARAM_ENTITY_PARSING_ALWAYS);
    +        XML_SetExternalEntityRefHandler(parser, external_entity_optioner);
    +        if (_XML_Parse_SINGLE_BYTES(parser, text, (int)strlen(text),
    +                                    XML_TRUE) != XML_STATUS_ERROR)
    +            break;
    +
    +        /* See comment in test_nsalloc_xmlns() */
    +        nsalloc_teardown();
    +        nsalloc_setup();
    +    }
    +    if (i == 0)
    +        fail("Success despite failing allocator");
    +    else if (i == max_alloc_count)
    +        fail("Failed even at full allocation count");
    +}
    +END_TEST
    +
     static Suite *
     make_suite(void)
     {
         Suite *s = suite_create("basic");
         TCase *tc_basic = tcase_create("basic tests");
         TCase *tc_namespace = tcase_create("XML namespaces");
    +    TCase *tc_misc = tcase_create("miscellaneous tests");
    +    TCase *tc_alloc = tcase_create("allocation tests");
    +    TCase *tc_nsalloc = tcase_create("namespace allocation tests");
     
         suite_add_tcase(s, tc_basic);
         tcase_add_checked_fixture(tc_basic, basic_setup, basic_teardown);
         tcase_add_test(tc_basic, test_nul_byte);
         tcase_add_test(tc_basic, test_u0000_char);
    +    tcase_add_test(tc_basic, test_siphash_self);
    +    tcase_add_test(tc_basic, test_siphash_spec);
         tcase_add_test(tc_basic, test_bom_utf8);
         tcase_add_test(tc_basic, test_bom_utf16_be);
         tcase_add_test(tc_basic, test_bom_utf16_le);
    +    tcase_add_test(tc_basic, test_nobom_utf16_le);
         tcase_add_test(tc_basic, test_illegal_utf8);
         tcase_add_test(tc_basic, test_utf8_auto_align);
         tcase_add_test(tc_basic, test_utf16);
         tcase_add_test(tc_basic, test_utf16_le_epilog_newline);
    +    tcase_add_test(tc_basic, test_not_utf16);
    +    tcase_add_test(tc_basic, test_bad_encoding);
         tcase_add_test(tc_basic, test_latin1_umlauts);
    +    tcase_add_test(tc_basic, test_long_utf8_character);
    +    tcase_add_test(tc_basic, test_long_latin1_attribute);
    +    tcase_add_test(tc_basic, test_long_ascii_attribute);
         /* Regression test for SF bug #491986. */
         tcase_add_test(tc_basic, test_danish_latin1);
         /* Regression test for SF bug #514281. */
    @@ -1627,27 +12019,191 @@ make_suite(void)
         tcase_add_test(tc_basic, test_line_number_after_error);
         tcase_add_test(tc_basic, test_column_number_after_error);
         tcase_add_test(tc_basic, test_really_long_lines);
    +    tcase_add_test(tc_basic, test_really_long_encoded_lines);
         tcase_add_test(tc_basic, test_end_element_events);
         tcase_add_test(tc_basic, test_attr_whitespace_normalization);
         tcase_add_test(tc_basic, test_xmldecl_misplaced);
    +    tcase_add_test(tc_basic, test_xmldecl_invalid);
    +    tcase_add_test(tc_basic, test_xmldecl_missing_attr);
    +    tcase_add_test(tc_basic, test_xmldecl_missing_value);
         tcase_add_test(tc_basic, test_unknown_encoding_internal_entity);
    +    tcase_add_test(tc_basic, test_unrecognised_encoding_internal_entity);
         tcase_add_test(tc_basic,
                        test_wfc_undeclared_entity_unread_external_subset);
         tcase_add_test(tc_basic, test_wfc_undeclared_entity_no_external_subset);
         tcase_add_test(tc_basic, test_wfc_undeclared_entity_standalone);
         tcase_add_test(tc_basic, test_wfc_undeclared_entity_with_external_subset);
    +    tcase_add_test(tc_basic, test_not_standalone_handler_reject);
    +    tcase_add_test(tc_basic, test_not_standalone_handler_accept);
         tcase_add_test(tc_basic,
                        test_wfc_undeclared_entity_with_external_subset_standalone);
    +    tcase_add_test(tc_basic,
    +                   test_entity_with_external_subset_unless_standalone);
         tcase_add_test(tc_basic, test_wfc_no_recursive_entity_refs);
         tcase_add_test(tc_basic, test_ext_entity_set_encoding);
    +    tcase_add_test(tc_basic, test_ext_entity_no_handler);
    +    tcase_add_test(tc_basic, test_ext_entity_set_bom);
    +    tcase_add_test(tc_basic, test_ext_entity_bad_encoding);
    +    tcase_add_test(tc_basic, test_ext_entity_bad_encoding_2);
    +    tcase_add_test(tc_basic, test_ext_entity_invalid_parse);
    +    tcase_add_test(tc_basic, test_ext_entity_invalid_suspended_parse);
         tcase_add_test(tc_basic, test_dtd_default_handling);
    +    tcase_add_test(tc_basic, test_dtd_attr_handling);
         tcase_add_test(tc_basic, test_empty_ns_without_namespaces);
         tcase_add_test(tc_basic, test_ns_in_attribute_default_without_namespaces);
         tcase_add_test(tc_basic, test_stop_parser_between_char_data_calls);
         tcase_add_test(tc_basic, test_suspend_parser_between_char_data_calls);
    +    tcase_add_test(tc_basic, test_repeated_stop_parser_between_char_data_calls);
         tcase_add_test(tc_basic, test_good_cdata_ascii);
         tcase_add_test(tc_basic, test_good_cdata_utf16);
    +    tcase_add_test(tc_basic, test_good_cdata_utf16_le);
    +    tcase_add_test(tc_basic, test_long_cdata_utf16);
    +    tcase_add_test(tc_basic, test_multichar_cdata_utf16);
    +    tcase_add_test(tc_basic, test_utf16_bad_surrogate_pair);
         tcase_add_test(tc_basic, test_bad_cdata);
    +    tcase_add_test(tc_basic, test_bad_cdata_utf16);
    +    tcase_add_test(tc_basic, test_stop_parser_between_cdata_calls);
    +    tcase_add_test(tc_basic, test_suspend_parser_between_cdata_calls);
    +    tcase_add_test(tc_basic, test_memory_allocation);
    +    tcase_add_test(tc_basic, test_default_current);
    +    tcase_add_test(tc_basic, test_dtd_elements);
    +    tcase_add_test(tc_basic, test_set_foreign_dtd);
    +    tcase_add_test(tc_basic, test_foreign_dtd_not_standalone);
    +    tcase_add_test(tc_basic, test_invalid_foreign_dtd);
    +    tcase_add_test(tc_basic, test_foreign_dtd_with_doctype);
    +    tcase_add_test(tc_basic, test_foreign_dtd_without_external_subset);
    +    tcase_add_test(tc_basic, test_empty_foreign_dtd);
    +    tcase_add_test(tc_basic, test_set_base);
    +    tcase_add_test(tc_basic, test_attributes);
    +    tcase_add_test(tc_basic, test_reset_in_entity);
    +    tcase_add_test(tc_basic, test_resume_invalid_parse);
    +    tcase_add_test(tc_basic, test_resume_resuspended);
    +    tcase_add_test(tc_basic, test_cdata_default);
    +    tcase_add_test(tc_basic, test_subordinate_reset);
    +    tcase_add_test(tc_basic, test_subordinate_suspend);
    +    tcase_add_test(tc_basic, test_subordinate_xdecl_suspend);
    +    tcase_add_test(tc_basic, test_subordinate_xdecl_abort);
    +    tcase_add_test(tc_basic, test_explicit_encoding);
    +    tcase_add_test(tc_basic, test_trailing_cr);
    +    tcase_add_test(tc_basic, test_ext_entity_trailing_cr);
    +    tcase_add_test(tc_basic, test_trailing_rsqb);
    +    tcase_add_test(tc_basic, test_ext_entity_trailing_rsqb);
    +    tcase_add_test(tc_basic, test_ext_entity_good_cdata);
    +    tcase_add_test(tc_basic, test_user_parameters);
    +    tcase_add_test(tc_basic, test_ext_entity_ref_parameter);
    +    tcase_add_test(tc_basic, test_empty_parse);
    +    tcase_add_test(tc_basic, test_get_buffer_1);
    +    tcase_add_test(tc_basic, test_get_buffer_2);
    +    tcase_add_test(tc_basic, test_byte_info_at_end);
    +    tcase_add_test(tc_basic, test_byte_info_at_error);
    +    tcase_add_test(tc_basic, test_byte_info_at_cdata);
    +    tcase_add_test(tc_basic, test_predefined_entities);
    +    tcase_add_test(tc_basic, test_invalid_tag_in_dtd);
    +    tcase_add_test(tc_basic, test_not_predefined_entities);
    +    tcase_add_test(tc_basic, test_ignore_section);
    +    tcase_add_test(tc_basic, test_ignore_section_utf16);
    +    tcase_add_test(tc_basic, test_ignore_section_utf16_be);
    +    tcase_add_test(tc_basic, test_bad_ignore_section);
    +    tcase_add_test(tc_basic, test_external_entity_values);
    +    tcase_add_test(tc_basic, test_ext_entity_not_standalone);
    +    tcase_add_test(tc_basic, test_ext_entity_value_abort);
    +    tcase_add_test(tc_basic, test_bad_public_doctype);
    +    tcase_add_test(tc_basic, test_attribute_enum_value);
    +    tcase_add_test(tc_basic, test_predefined_entity_redefinition);
    +    tcase_add_test(tc_basic, test_dtd_stop_processing);
    +    tcase_add_test(tc_basic, test_public_notation_no_sysid);
    +    tcase_add_test(tc_basic, test_nested_groups);
    +    tcase_add_test(tc_basic, test_group_choice);
    +    tcase_add_test(tc_basic, test_standalone_parameter_entity);
    +    tcase_add_test(tc_basic, test_skipped_parameter_entity);
    +    tcase_add_test(tc_basic, test_recursive_external_parameter_entity);
    +    tcase_add_test(tc_basic, test_undefined_ext_entity_in_external_dtd);
    +    tcase_add_test(tc_basic, test_suspend_xdecl);
    +    tcase_add_test(tc_basic, test_abort_epilog);
    +    tcase_add_test(tc_basic, test_abort_epilog_2);
    +    tcase_add_test(tc_basic, test_suspend_epilog);
    +    tcase_add_test(tc_basic, test_suspend_in_sole_empty_tag);
    +    tcase_add_test(tc_basic, test_unfinished_epilog);
    +    tcase_add_test(tc_basic, test_partial_char_in_epilog);
    +    tcase_add_test(tc_basic, test_hash_collision);
    +    tcase_add_test(tc_basic, test_suspend_resume_internal_entity);
    +    tcase_add_test(tc_basic, test_resume_entity_with_syntax_error);
    +    tcase_add_test(tc_basic, test_suspend_resume_parameter_entity);
    +    tcase_add_test(tc_basic, test_restart_on_error);
    +    tcase_add_test(tc_basic, test_reject_lt_in_attribute_value);
    +    tcase_add_test(tc_basic, test_reject_unfinished_param_in_att_value);
    +    tcase_add_test(tc_basic, test_trailing_cr_in_att_value);
    +    tcase_add_test(tc_basic, test_standalone_internal_entity);
    +    tcase_add_test(tc_basic, test_skipped_external_entity);
    +    tcase_add_test(tc_basic, test_skipped_null_loaded_ext_entity);
    +    tcase_add_test(tc_basic, test_skipped_unloaded_ext_entity);
    +    tcase_add_test(tc_basic, test_param_entity_with_trailing_cr);
    +    tcase_add_test(tc_basic, test_invalid_character_entity);
    +    tcase_add_test(tc_basic, test_invalid_character_entity_2);
    +    tcase_add_test(tc_basic, test_invalid_character_entity_3);
    +    tcase_add_test(tc_basic, test_invalid_character_entity_4);
    +    tcase_add_test(tc_basic, test_pi_handled_in_default);
    +    tcase_add_test(tc_basic, test_comment_handled_in_default);
    +    tcase_add_test(tc_basic, test_pi_yml);
    +    tcase_add_test(tc_basic, test_pi_xnl);
    +    tcase_add_test(tc_basic, test_pi_xmm);
    +    tcase_add_test(tc_basic, test_utf16_pi);
    +    tcase_add_test(tc_basic, test_utf16_be_pi);
    +    tcase_add_test(tc_basic, test_utf16_be_comment);
    +    tcase_add_test(tc_basic, test_utf16_le_comment);
    +    tcase_add_test(tc_basic, test_missing_encoding_conversion_fn);
    +    tcase_add_test(tc_basic, test_failing_encoding_conversion_fn);
    +    tcase_add_test(tc_basic, test_unknown_encoding_success);
    +    tcase_add_test(tc_basic, test_unknown_encoding_bad_name);
    +    tcase_add_test(tc_basic, test_unknown_encoding_bad_name_2);
    +    tcase_add_test(tc_basic, test_unknown_encoding_long_name_1);
    +    tcase_add_test(tc_basic, test_unknown_encoding_long_name_2);
    +    tcase_add_test(tc_basic, test_invalid_unknown_encoding);
    +    tcase_add_test(tc_basic, test_unknown_ascii_encoding_ok);
    +    tcase_add_test(tc_basic, test_unknown_ascii_encoding_fail);
    +    tcase_add_test(tc_basic, test_unknown_encoding_invalid_length);
    +    tcase_add_test(tc_basic, test_unknown_encoding_invalid_topbit);
    +    tcase_add_test(tc_basic, test_unknown_encoding_invalid_surrogate);
    +    tcase_add_test(tc_basic, test_unknown_encoding_invalid_high);
    +    tcase_add_test(tc_basic, test_unknown_encoding_invalid_attr_value);
    +    tcase_add_test(tc_basic, test_ext_entity_latin1_utf16le_bom);
    +    tcase_add_test(tc_basic, test_ext_entity_latin1_utf16be_bom);
    +    tcase_add_test(tc_basic, test_ext_entity_latin1_utf16le_bom2);
    +    tcase_add_test(tc_basic, test_ext_entity_latin1_utf16be_bom2);
    +    tcase_add_test(tc_basic, test_ext_entity_utf16_be);
    +    tcase_add_test(tc_basic, test_ext_entity_utf16_le);
    +    tcase_add_test(tc_basic, test_ext_entity_utf16_unknown);
    +    tcase_add_test(tc_basic, test_ext_entity_utf8_non_bom);
    +    tcase_add_test(tc_basic, test_utf8_in_cdata_section);
    +    tcase_add_test(tc_basic, test_utf8_in_cdata_section_2);
    +    tcase_add_test(tc_basic, test_trailing_spaces_in_elements);
    +    tcase_add_test(tc_basic, test_utf16_attribute);
    +    tcase_add_test(tc_basic, test_utf16_second_attr);
    +    tcase_add_test(tc_basic, test_attr_after_solidus);
    +    tcase_add_test(tc_basic, test_utf16_pe);
    +    tcase_add_test(tc_basic, test_bad_attr_desc_keyword);
    +    tcase_add_test(tc_basic, test_bad_attr_desc_keyword_utf16);
    +    tcase_add_test(tc_basic, test_bad_doctype);
    +    tcase_add_test(tc_basic, test_bad_doctype_utf16);
    +    tcase_add_test(tc_basic, test_bad_doctype_plus);
    +    tcase_add_test(tc_basic, test_bad_doctype_star);
    +    tcase_add_test(tc_basic, test_bad_doctype_query);
    +    tcase_add_test(tc_basic, test_unknown_encoding_bad_ignore);
    +    tcase_add_test(tc_basic, test_entity_in_utf16_be_attr);
    +    tcase_add_test(tc_basic, test_entity_in_utf16_le_attr);
    +    tcase_add_test(tc_basic, test_entity_public_utf16_be);
    +    tcase_add_test(tc_basic, test_entity_public_utf16_le);
    +    tcase_add_test(tc_basic, test_short_doctype);
    +    tcase_add_test(tc_basic, test_short_doctype_2);
    +    tcase_add_test(tc_basic, test_short_doctype_3);
    +    tcase_add_test(tc_basic, test_long_doctype);
    +    tcase_add_test(tc_basic, test_bad_entity);
    +    tcase_add_test(tc_basic, test_bad_entity_2);
    +    tcase_add_test(tc_basic, test_bad_entity_3);
    +    tcase_add_test(tc_basic, test_bad_entity_4);
    +    tcase_add_test(tc_basic, test_bad_notation);
    +    tcase_add_test(tc_basic, test_default_doctype_handler);
    +    tcase_add_test(tc_basic, test_empty_element_abort);
     
         suite_add_tcase(s, tc_namespace);
         tcase_add_checked_fixture(tc_namespace,
    @@ -1661,10 +12217,123 @@ make_suite(void)
         tcase_add_test(tc_namespace, test_ns_prefix_with_empty_uri_2);
         tcase_add_test(tc_namespace, test_ns_prefix_with_empty_uri_3);
         tcase_add_test(tc_namespace, test_ns_prefix_with_empty_uri_4);
    +    tcase_add_test(tc_namespace, test_ns_unbound_prefix);
         tcase_add_test(tc_namespace, test_ns_default_with_empty_uri);
         tcase_add_test(tc_namespace, test_ns_duplicate_attrs_diff_prefixes);
    +    tcase_add_test(tc_namespace, test_ns_duplicate_hashes);
         tcase_add_test(tc_namespace, test_ns_unbound_prefix_on_attribute);
         tcase_add_test(tc_namespace, test_ns_unbound_prefix_on_element);
    +    tcase_add_test(tc_namespace, test_ns_parser_reset);
    +    tcase_add_test(tc_namespace, test_ns_long_element);
    +    tcase_add_test(tc_namespace, test_ns_mixed_prefix_atts);
    +    tcase_add_test(tc_namespace, test_ns_extend_uri_buffer);
    +    tcase_add_test(tc_namespace, test_ns_reserved_attributes);
    +    tcase_add_test(tc_namespace, test_ns_reserved_attributes_2);
    +    tcase_add_test(tc_namespace, test_ns_extremely_long_prefix);
    +    tcase_add_test(tc_namespace, test_ns_unknown_encoding_success);
    +    tcase_add_test(tc_namespace, test_ns_double_colon);
    +    tcase_add_test(tc_namespace, test_ns_double_colon_element);
    +    tcase_add_test(tc_namespace, test_ns_bad_attr_leafname);
    +    tcase_add_test(tc_namespace, test_ns_bad_element_leafname);
    +    tcase_add_test(tc_namespace, test_ns_utf16_leafname);
    +    tcase_add_test(tc_namespace, test_ns_utf16_element_leafname);
    +    tcase_add_test(tc_namespace, test_ns_utf16_doctype);
    +    tcase_add_test(tc_namespace, test_ns_invalid_doctype);
    +    tcase_add_test(tc_namespace, test_ns_double_colon_doctype);
    +
    +    suite_add_tcase(s, tc_misc);
    +    tcase_add_checked_fixture(tc_misc, NULL, basic_teardown);
    +    tcase_add_test(tc_misc, test_misc_alloc_create_parser);
    +    tcase_add_test(tc_misc, test_misc_alloc_create_parser_with_encoding);
    +    tcase_add_test(tc_misc, test_misc_null_parser);
    +    tcase_add_test(tc_misc, test_misc_error_string);
    +    tcase_add_test(tc_misc, test_misc_version);
    +    tcase_add_test(tc_misc, test_misc_features);
    +    tcase_add_test(tc_misc, test_misc_attribute_leak);
    +    tcase_add_test(tc_misc, test_misc_utf16le);
    +
    +    suite_add_tcase(s, tc_alloc);
    +    tcase_add_checked_fixture(tc_alloc, alloc_setup, alloc_teardown);
    +    tcase_add_test(tc_alloc, test_alloc_parse_xdecl);
    +    tcase_add_test(tc_alloc, test_alloc_parse_xdecl_2);
    +    tcase_add_test(tc_alloc, test_alloc_parse_pi);
    +    tcase_add_test(tc_alloc, test_alloc_parse_pi_2);
    +    tcase_add_test(tc_alloc, test_alloc_parse_pi_3);
    +    tcase_add_test(tc_alloc, test_alloc_parse_comment);
    +    tcase_add_test(tc_alloc, test_alloc_parse_comment_2);
    +    tcase_add_test(tc_alloc, test_alloc_create_external_parser);
    +    tcase_add_test(tc_alloc, test_alloc_run_external_parser);
    +    tcase_add_test(tc_alloc, test_alloc_dtd_copy_default_atts);
    +    tcase_add_test(tc_alloc, test_alloc_external_entity);
    +    tcase_add_test(tc_alloc, test_alloc_ext_entity_set_encoding);
    +    tcase_add_test(tc_alloc, test_alloc_internal_entity);
    +    tcase_add_test(tc_alloc, test_alloc_dtd_default_handling);
    +    tcase_add_test(tc_alloc, test_alloc_explicit_encoding);
    +    tcase_add_test(tc_alloc, test_alloc_set_base);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_buffer);
    +    tcase_add_test(tc_alloc, test_alloc_ext_entity_realloc_buffer);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_many_attributes);
    +    tcase_add_test(tc_alloc, test_alloc_public_entity_value);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_subst_public_entity_value);
    +    tcase_add_test(tc_alloc, test_alloc_parse_public_doctype);
    +    tcase_add_test(tc_alloc, test_alloc_parse_public_doctype_long_name);
    +    tcase_add_test(tc_alloc, test_alloc_set_foreign_dtd);
    +    tcase_add_test(tc_alloc, test_alloc_attribute_enum_value);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_attribute_enum_value);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_implied_attribute);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_default_attribute);
    +    tcase_add_test(tc_alloc, test_alloc_notation);
    +    tcase_add_test(tc_alloc, test_alloc_public_notation);
    +    tcase_add_test(tc_alloc, test_alloc_system_notation);
    +    tcase_add_test(tc_alloc, test_alloc_nested_groups);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_nested_groups);
    +    tcase_add_test(tc_alloc, test_alloc_large_group);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_group_choice);
    +    tcase_add_test(tc_alloc, test_alloc_pi_in_epilog);
    +    tcase_add_test(tc_alloc, test_alloc_comment_in_epilog);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_long_attribute_value);
    +    tcase_add_test(tc_alloc, test_alloc_attribute_whitespace);
    +    tcase_add_test(tc_alloc, test_alloc_attribute_predefined_entity);
    +    tcase_add_test(tc_alloc, test_alloc_long_attr_default_with_char_ref);
    +    tcase_add_test(tc_alloc, test_alloc_long_attr_value);
    +    tcase_add_test(tc_alloc, test_alloc_nested_entities);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_param_entity_newline);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_ce_extends_pe);
    +    tcase_add_test(tc_alloc, test_alloc_realloc_attributes);
    +    tcase_add_test(tc_alloc, test_alloc_long_doc_name);
    +    tcase_add_test(tc_alloc, test_alloc_long_base);
    +    tcase_add_test(tc_alloc, test_alloc_long_public_id);
    +    tcase_add_test(tc_alloc, test_alloc_long_entity_value);
    +    tcase_add_test(tc_alloc, test_alloc_long_notation);
    +
    +    suite_add_tcase(s, tc_nsalloc);
    +    tcase_add_checked_fixture(tc_nsalloc, nsalloc_setup, nsalloc_teardown);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_xmlns);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_parse_buffer);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_prefix);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_uri);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_attr);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_attr_prefix);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_attributes);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_element);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_binding_uri);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_prefix);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_longer_prefix);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_namespace);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_less_long_namespace);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_context);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context_2);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context_3);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context_4);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context_5);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context_6);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context_7);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_ge_name);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_realloc_long_context_in_dtd);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_default_in_ext);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_long_systemid_in_ext);
    +    tcase_add_test(tc_nsalloc, test_nsalloc_prefixed_element);
     
         return s;
     }
    @@ -1693,7 +12362,7 @@ main(int argc, char *argv[])
             }
         }
         if (verbosity != CK_SILENT)
    -        printf("Expat version: %s\n", XML_ExpatVersion());
    +        printf("Expat version: %" XML_FMT_STR "\n", XML_ExpatVersion());
         srunner_run_all(sr, verbosity);
         nf = srunner_ntests_failed(sr);
         srunner_free(sr);
    diff --git a/contrib/expat/tests/runtests.sln b/contrib/expat/tests/runtests.sln
    new file mode 100644
    index 000000000000..6e07293f580c
    --- /dev/null
    +++ b/contrib/expat/tests/runtests.sln
    @@ -0,0 +1,24 @@
    +
    +Microsoft Visual Studio Solution File, Format Version 12.00
    +# Visual Studio 2013
    +VisualStudioVersion = 12.0.40629.0
    +MinimumVisualStudioVersion = 10.0.40219.1
    +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "runtests", "runtests.vcxproj", "{63D6D820-B526-4A5F-9605-9B8551FAC591}"
    +EndProject
    +Global
    +	GlobalSection(SolutionConfigurationPlatforms) = preSolution
    +		Debug|Win32 = Debug|Win32
    +		Release|Win32 = Release|Win32
    +		Template|Win32 = Template|Win32
    +	EndGlobalSection
    +	GlobalSection(ProjectConfigurationPlatforms) = postSolution
    +		{63D6D820-B526-4A5F-9605-9B8551FAC591}.Debug|Win32.ActiveCfg = Debug|Win32
    +		{63D6D820-B526-4A5F-9605-9B8551FAC591}.Debug|Win32.Build.0 = Debug|Win32
    +		{63D6D820-B526-4A5F-9605-9B8551FAC591}.Release|Win32.ActiveCfg = Release|Win32
    +		{63D6D820-B526-4A5F-9605-9B8551FAC591}.Release|Win32.Build.0 = Release|Win32
    +		{63D6D820-B526-4A5F-9605-9B8551FAC591}.Template|Win32.ActiveCfg = Release|Win32
    +	EndGlobalSection
    +	GlobalSection(SolutionProperties) = preSolution
    +		HideSolutionNode = FALSE
    +	EndGlobalSection
    +EndGlobal
    diff --git a/contrib/expat/tests/runtestspp.cpp b/contrib/expat/tests/runtestspp.cpp
    index c35dc583d57a..fd3ceaa97a39 100644
    --- a/contrib/expat/tests/runtestspp.cpp
    +++ b/contrib/expat/tests/runtestspp.cpp
    @@ -1,6 +1,36 @@
    -// C++ compilation harness for the test suite.
    -//
    -// This is used to ensure the Expat headers can be included from C++
    -// and have everything work as expected.
    -//
    +/* C++ compilation harness for the test suite.
    +
    +   This is used to ensure the Expat headers can be included from C++
    +   and have everything work as expected.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     #include "runtests.c"
    diff --git a/contrib/expat/tests/structdata.c b/contrib/expat/tests/structdata.c
    new file mode 100644
    index 000000000000..2ed36fc38de8
    --- /dev/null
    +++ b/contrib/expat/tests/structdata.c
    @@ -0,0 +1,162 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
    +#ifdef HAVE_EXPAT_CONFIG_H
    +# include "expat_config.h"
    +#endif
    +
    +
    +#include 
    +#include 
    +#include 
    +#include 
    +
    +#include "structdata.h"
    +#include "minicheck.h"
    +
    +#define STRUCT_EXTENSION_COUNT 8
    +
    +#ifdef XML_UNICODE_WCHAR_T
    +# include 
    +# define XML_FMT_STR "ls"
    +# define xcstrlen(s) wcslen(s)
    +# define xcstrcmp(s, t) wcscmp((s), (t))
    +#else
    +# define XML_FMT_STR "s"
    +# define xcstrlen(s) strlen(s)
    +# define xcstrcmp(s, t) strcmp((s), (t))
    +#endif
    +
    +
    +static XML_Char *
    +xmlstrdup(const XML_Char *s)
    +{
    +    size_t byte_count = (xcstrlen(s) + 1) * sizeof(XML_Char);
    +    XML_Char *dup = malloc(byte_count);
    +
    +    assert(dup != NULL);
    +    memcpy(dup, s, byte_count);
    +    return dup;
    +}
    +
    +
    +void
    +StructData_Init(StructData *storage)
    +{
    +    assert(storage != NULL);
    +    storage->count = 0;
    +    storage->max_count = 0;
    +    storage->entries = NULL;
    +}
    +
    +void
    +StructData_AddItem(StructData *storage,
    +                   const XML_Char *s,
    +                   int data0,
    +                   int data1,
    +                   int data2)
    +{
    +    StructDataEntry *entry;
    +
    +    assert(storage != NULL);
    +    assert(s != NULL);
    +    if (storage->count == storage->max_count) {
    +        StructDataEntry *new;
    +
    +        storage->max_count += STRUCT_EXTENSION_COUNT;
    +        new = realloc(storage->entries,
    +                      storage->max_count * sizeof(StructDataEntry));
    +        assert(new != NULL);
    +        storage->entries = new;
    +    }
    +
    +    entry = &storage->entries[storage->count];
    +    entry->str = xmlstrdup(s);
    +    entry->data0 = data0;
    +    entry->data1 = data1;
    +    entry->data2 = data2;
    +    storage->count++;
    +}
    +
    +/* 'fail()' aborts the function via a longjmp, so there is no point
    + * in returning a value from this function.
    + */
    +void
    +StructData_CheckItems(StructData *storage,
    +                      const StructDataEntry *expected,
    +                      int count)
    +{
    +    char buffer[1024];
    +    int i;
    +
    +    assert(storage != NULL);
    +    assert(expected != NULL);
    +    if (count != storage->count) {
    +        sprintf(buffer, "wrong number of entries: got %d, expected %d",
    +                storage->count, count);
    +        StructData_Dispose(storage);
    +        fail(buffer);
    +    }
    +    for (i = 0; i < count; i++)
    +    {
    +        const StructDataEntry *got = &storage->entries[i];
    +        const StructDataEntry *want = &expected[i];
    +
    +        if (xcstrcmp(got->str, want->str) != 0) {
    +            StructData_Dispose(storage);
    +            fail("structure got bad string");
    +        }
    +        if (got->data0 != want->data0 ||
    +            got->data1 != want->data1 ||
    +            got->data2 != want->data2) {
    +            sprintf(buffer,
    +                    "struct '%" XML_FMT_STR
    +                    "' expected (%d,%d,%d), got (%d,%d,%d)",
    +                    got->str,
    +                    want->data0, want->data1, want->data2,
    +                    got->data0, got->data1, got->data2);
    +            StructData_Dispose(storage);
    +            fail(buffer);
    +        }
    +    }
    +}
    +
    +void
    +StructData_Dispose(StructData *storage)
    +{
    +    int i;
    +
    +    assert(storage != NULL);
    +    for (i = 0; i < storage->count; i++)
    +        free((void *)storage->entries[i].str);
    +    free(storage->entries);
    +}
    diff --git a/contrib/expat/tests/structdata.h b/contrib/expat/tests/structdata.h
    new file mode 100644
    index 000000000000..19016a9195c7
    --- /dev/null
    +++ b/contrib/expat/tests/structdata.h
    @@ -0,0 +1,76 @@
    +/* Interface to some helper routines used to accumulate and check
    +   structured content.
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
    +#ifdef __cplusplus
    +extern "C" {
    +#endif
    +
    +#ifndef XML_STRUCTDATA_H
    +#define XML_STRUCTDATA_H 1
    +
    +#include "expat.h"
    +
    +typedef struct {
    +    const XML_Char *str;
    +    int data0;
    +    int data1;
    +    int data2;
    +} StructDataEntry;
    +
    +typedef struct {
    +    int count;       /* Number of entries used */
    +    int max_count;   /* Number of StructDataEntry items in `entries` */
    +    StructDataEntry *entries;
    +} StructData;
    +
    +
    +void StructData_Init(StructData *storage);
    +
    +void StructData_AddItem(StructData *storage,
    +                        const XML_Char *s,
    +                        int data0,
    +                        int data1,
    +                        int data2);
    +
    +void StructData_CheckItems(StructData *storage,
    +                           const StructDataEntry *expected,
    +                           int count);
    +
    +void StructData_Dispose(StructData *storage);
    +
    +
    +#endif  /* XML_STRUCTDATA_H */
    +
    +#ifdef __cplusplus
    +}
    +#endif
    diff --git a/contrib/expat/tests/udiffer.py b/contrib/expat/tests/udiffer.py
    new file mode 100755
    index 000000000000..6fb91be7e3d0
    --- /dev/null
    +++ b/contrib/expat/tests/udiffer.py
    @@ -0,0 +1,62 @@
    +#! /usr/bin/env python3
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +import argparse
    +import difflib
    +import sys
    +
    +
    +def _read_lines(filename):
    +    try:
    +        with open(filename) as f:
    +            return f.readlines()
    +    except UnicodeDecodeError:
    +        with open(filename, encoding='utf_16') as f:
    +            return f.readlines()
    +
    +
    +def main():
    +    parser = argparse.ArgumentParser()
    +    parser.add_argument('first', metavar='FILE')
    +    parser.add_argument('second', metavar='FILE')
    +    config = parser.parse_args()
    +
    +    first = _read_lines(config.first)
    +    second = _read_lines(config.second)
    +
    +    diffs = list(difflib.unified_diff(first, second, fromfile=config.first,
    +                                      tofile=config.second))
    +    if diffs:
    +        sys.stdout.writelines(diffs)
    +        sys.exit(1)
    +
    +
    +if __name__ == '__main__':
    +    main()
    diff --git a/contrib/expat/tests/xmltest.log.expected b/contrib/expat/tests/xmltest.log.expected
    new file mode 100644
    index 000000000000..032f5464243b
    --- /dev/null
    +++ b/contrib/expat/tests/xmltest.log.expected
    @@ -0,0 +1,10 @@
    +Output differs: ibm/valid/P02/ibm02v01.xml
    +ibm49i02.dtd: No such file or directory
    +Expected not well-formed: ibm/not-wf/misc/432gewf.xml
    +Expected not well-formed: xmltest/not-wf/not-sa/005.xml
    +Expected not well-formed: sun/not-wf/uri01.xml
    +Expected not well-formed: oasis/p06fail1.xml
    +Expected not well-formed: oasis/p08fail1.xml
    +Expected not well-formed: oasis/p08fail2.xml
    +Passed: 1801
    +Failed: 8
    diff --git a/contrib/expat/tests/xmltest.sh b/contrib/expat/tests/xmltest.sh
    index 64a17eec06f5..2b8cb196b385 100755
    --- a/contrib/expat/tests/xmltest.sh
    +++ b/contrib/expat/tests/xmltest.sh
    @@ -25,12 +25,14 @@ shopt -s nullglob
     MYDIR="`dirname \"$0\"`"
     cd "$MYDIR"
     MYDIR="`pwd`"
    -XMLWF="`dirname \"$MYDIR\"`/xmlwf/xmlwf"
    +XMLWF="${1:-`dirname \"$MYDIR\"`/xmlwf/xmlwf}"
     # XMLWF=/usr/local/bin/xmlwf
     TS="$MYDIR"
     # OUTPUT must terminate with the directory separator.
     OUTPUT="$TS/out/"
     # OUTPUT=/home/tmp/xml-testsuite-out/
    +# Unicode-aware diff utility
    +DIFF="$TS/udiffer.py"
     
     
     # RunXmlwfNotWF file reldir
    @@ -53,11 +55,11 @@ RunXmlwfNotWF() {
     RunXmlwfWF() {
       file="$1"
       reldir="$2"
    -  $XMLWF -p -d "$OUTPUT$reldir" "$file" > outfile || return $?
    +  $XMLWF -p -N -d "$OUTPUT$reldir" "$file" > outfile || return $?
       read outdata < outfile 
       if test "$outdata" = "" ; then 
           if [ -f "out/$file" ] ; then 
    -          diff -u "$OUTPUT$reldir$file" "out/$file" > outfile 
    +          $DIFF "$OUTPUT$reldir$file" "out/$file" > outfile 
               if [ -s outfile ] ; then 
                   cp outfile "$OUTPUT$reldir$file.diff"
                   echo "Output differs: $reldir$file"
    @@ -98,7 +100,8 @@ for xmldir in ibm/valid/P* \
                   sun/invalid ; do
       cd "$TS/xmlconf/$xmldir"
       mkdir -p "$OUTPUT$xmldir"
    -  for xmlfile in *.xml ; do
    +  for xmlfile in $(ls -1 *.xml | sort -d) ; do
    +      [[ -f "$xmlfile" ]] || continue
           RunXmlwfWF "$xmlfile" "$xmldir/"
           UpdateStatus $?
       done
    diff --git a/contrib/expat/xmlwf/Makefile.am b/contrib/expat/xmlwf/Makefile.am
    new file mode 100644
    index 000000000000..ff460902caa0
    --- /dev/null
    +++ b/contrib/expat/xmlwf/Makefile.am
    @@ -0,0 +1,61 @@
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +bin_PROGRAMS = xmlwf
    +
    +xmlwf_LDADD = ../lib/libexpat.la
    +xmlwf_SOURCES = \
    +    xmlwf.c \
    +    xmlfile.c \
    +    codepage.c \
    +    @FILEMAP@.c
    +
    +xmlwf_CPPFLAGS = -I$(srcdir)/../lib
    +
    +if MINGW
    +if UNICODE
    +xmlwf_CPPFLAGS += -mwindows
    +xmlwf_LDFLAGS = -municode
    +endif
    +endif
    +
    +EXTRA_DIST = \
    +    codepage.h \
    +    ct.c \
    +    filemap.h \
    +    readfilemap.c \
    +    unixfilemap.c \
    +    win32filemap.c \
    +    xmlfile.h \
    +    xmlmime.c \
    +    xmlmime.h \
    +    xmltchar.h \
    +    xmlurl.h \
    +    xmlwin32url.cxx
    diff --git a/contrib/expat/xmlwf/Makefile.in b/contrib/expat/xmlwf/Makefile.in
    new file mode 100644
    index 000000000000..152bbe97eec3
    --- /dev/null
    +++ b/contrib/expat/xmlwf/Makefile.in
    @@ -0,0 +1,753 @@
    +# Makefile.in generated by automake 1.15.1 from Makefile.am.
    +# @configure_input@
    +
    +# Copyright (C) 1994-2017 Free Software Foundation, Inc.
    +
    +# This Makefile.in is free software; the Free Software Foundation
    +# gives unlimited permission to copy and/or distribute it,
    +# with or without modifications, as long as this notice is preserved.
    +
    +# This program is distributed in the hope that it will be useful,
    +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
    +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
    +# PARTICULAR PURPOSE.
    +
    +@SET_MAKE@
    +
    +#
    +#                          __  __            _
    +#                       ___\ \/ /_ __   __ _| |_
    +#                      / _ \\  /| '_ \ / _` | __|
    +#                     |  __//  \| |_) | (_| | |_
    +#                      \___/_/\_\ .__/ \__,_|\__|
    +#                               |_| XML parser
    +#
    +# Copyright (c) 2017 Expat development team
    +# Licensed under the MIT license:
    +#
    +# Permission is  hereby granted,  free of charge,  to any  person obtaining
    +# a  copy  of  this  software   and  associated  documentation  files  (the
    +# "Software"),  to  deal in  the  Software  without restriction,  including
    +# without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +# distribute, sublicense, and/or sell copies of the Software, and to permit
    +# persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +# following conditions:
    +#
    +# The above copyright  notice and this permission notice  shall be included
    +# in all copies or substantial portions of the Software.
    +#
    +# THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +# EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +# NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +# DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +# USE OR OTHER DEALINGS IN THE SOFTWARE.
    +
    +VPATH = @srcdir@
    +am__is_gnu_make = { \
    +  if test -z '$(MAKELEVEL)'; then \
    +    false; \
    +  elif test -n '$(MAKE_HOST)'; then \
    +    true; \
    +  elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \
    +    true; \
    +  else \
    +    false; \
    +  fi; \
    +}
    +am__make_running_with_option = \
    +  case $${target_option-} in \
    +      ?) ;; \
    +      *) echo "am__make_running_with_option: internal error: invalid" \
    +              "target option '$${target_option-}' specified" >&2; \
    +         exit 1;; \
    +  esac; \
    +  has_opt=no; \
    +  sane_makeflags=$$MAKEFLAGS; \
    +  if $(am__is_gnu_make); then \
    +    sane_makeflags=$$MFLAGS; \
    +  else \
    +    case $$MAKEFLAGS in \
    +      *\\[\ \	]*) \
    +        bs=\\; \
    +        sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
    +          | sed "s/$$bs$$bs[$$bs $$bs	]*//g"`;; \
    +    esac; \
    +  fi; \
    +  skip_next=no; \
    +  strip_trailopt () \
    +  { \
    +    flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
    +  }; \
    +  for flg in $$sane_makeflags; do \
    +    test $$skip_next = yes && { skip_next=no; continue; }; \
    +    case $$flg in \
    +      *=*|--*) continue;; \
    +        -*I) strip_trailopt 'I'; skip_next=yes;; \
    +      -*I?*) strip_trailopt 'I';; \
    +        -*O) strip_trailopt 'O'; skip_next=yes;; \
    +      -*O?*) strip_trailopt 'O';; \
    +        -*l) strip_trailopt 'l'; skip_next=yes;; \
    +      -*l?*) strip_trailopt 'l';; \
    +      -[dEDm]) skip_next=yes;; \
    +      -[JT]) skip_next=yes;; \
    +    esac; \
    +    case $$flg in \
    +      *$$target_option*) has_opt=yes; break;; \
    +    esac; \
    +  done; \
    +  test $$has_opt = yes
    +am__make_dryrun = (target_option=n; $(am__make_running_with_option))
    +am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
    +pkgdatadir = $(datadir)/@PACKAGE@
    +pkgincludedir = $(includedir)/@PACKAGE@
    +pkglibdir = $(libdir)/@PACKAGE@
    +pkglibexecdir = $(libexecdir)/@PACKAGE@
    +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
    +install_sh_DATA = $(install_sh) -c -m 644
    +install_sh_PROGRAM = $(install_sh) -c
    +install_sh_SCRIPT = $(install_sh) -c
    +INSTALL_HEADER = $(INSTALL_DATA)
    +transform = $(program_transform_name)
    +NORMAL_INSTALL = :
    +PRE_INSTALL = :
    +POST_INSTALL = :
    +NORMAL_UNINSTALL = :
    +PRE_UNINSTALL = :
    +POST_UNINSTALL = :
    +build_triplet = @build@
    +host_triplet = @host@
    +bin_PROGRAMS = xmlwf$(EXEEXT)
    +@MINGW_TRUE@@UNICODE_TRUE@am__append_1 = -mwindows
    +subdir = xmlwf
    +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
    +am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
    +	$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
    +	$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
    +	$(top_srcdir)/conftools/ac_c_bigendian_cross.m4 \
    +	$(top_srcdir)/configure.ac
    +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
    +	$(ACLOCAL_M4)
    +DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON)
    +mkinstalldirs = $(install_sh) -d
    +CONFIG_HEADER = $(top_builddir)/expat_config.h
    +CONFIG_CLEAN_FILES =
    +CONFIG_CLEAN_VPATH_FILES =
    +am__installdirs = "$(DESTDIR)$(bindir)"
    +PROGRAMS = $(bin_PROGRAMS)
    +am_xmlwf_OBJECTS = xmlwf-xmlwf.$(OBJEXT) xmlwf-xmlfile.$(OBJEXT) \
    +	xmlwf-codepage.$(OBJEXT) xmlwf-@FILEMAP@.$(OBJEXT)
    +xmlwf_OBJECTS = $(am_xmlwf_OBJECTS)
    +xmlwf_DEPENDENCIES = ../lib/libexpat.la
    +AM_V_lt = $(am__v_lt_@AM_V@)
    +am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@)
    +am__v_lt_0 = --silent
    +am__v_lt_1 = 
    +xmlwf_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
    +	$(xmlwf_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_P = $(am__v_P_@AM_V@)
    +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@)
    +am__v_P_0 = false
    +am__v_P_1 = :
    +AM_V_GEN = $(am__v_GEN_@AM_V@)
    +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@)
    +am__v_GEN_0 = @echo "  GEN     " $@;
    +am__v_GEN_1 = 
    +AM_V_at = $(am__v_at_@AM_V@)
    +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@)
    +am__v_at_0 = @
    +am__v_at_1 = 
    +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
    +depcomp = $(SHELL) $(top_srcdir)/conftools/depcomp
    +am__depfiles_maybe = depfiles
    +am__mv = mv -f
    +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
    +	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
    +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \
    +	$(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
    +	$(AM_CFLAGS) $(CFLAGS)
    +AM_V_CC = $(am__v_CC_@AM_V@)
    +am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@)
    +am__v_CC_0 = @echo "  CC      " $@;
    +am__v_CC_1 = 
    +CCLD = $(CC)
    +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
    +	$(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
    +	$(AM_LDFLAGS) $(LDFLAGS) -o $@
    +AM_V_CCLD = $(am__v_CCLD_@AM_V@)
    +am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@)
    +am__v_CCLD_0 = @echo "  CCLD    " $@;
    +am__v_CCLD_1 = 
    +SOURCES = $(xmlwf_SOURCES)
    +DIST_SOURCES = $(xmlwf_SOURCES)
    +am__can_run_installinfo = \
    +  case $$AM_UPDATE_INFO_DIR in \
    +    n|no|NO) false;; \
    +    *) (install-info --version) >/dev/null 2>&1;; \
    +  esac
    +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
    +# Read a list of newline-separated strings from the standard input,
    +# and print each of them once, without duplicates.  Input order is
    +# *not* preserved.
    +am__uniquify_input = $(AWK) '\
    +  BEGIN { nonempty = 0; } \
    +  { items[$$0] = 1; nonempty = 1; } \
    +  END { if (nonempty) { for (i in items) print i; }; } \
    +'
    +# Make sure the list of sources is unique.  This is necessary because,
    +# e.g., the same source file might be shared among _SOURCES variables
    +# for different programs/libraries.
    +am__define_uniq_tagged_files = \
    +  list='$(am__tagged_files)'; \
    +  unique=`for i in $$list; do \
    +    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
    +  done | $(am__uniquify_input)`
    +ETAGS = etags
    +CTAGS = ctags
    +am__DIST_COMMON = $(srcdir)/Makefile.in \
    +	$(top_srcdir)/conftools/depcomp
    +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
    +ACLOCAL = @ACLOCAL@
    +AMTAR = @AMTAR@
    +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
    +AR = @AR@
    +AS = @AS@
    +AUTOCONF = @AUTOCONF@
    +AUTOHEADER = @AUTOHEADER@
    +AUTOMAKE = @AUTOMAKE@
    +AWK = @AWK@
    +CC = @CC@
    +CCDEPMODE = @CCDEPMODE@
    +CFLAGS = @CFLAGS@
    +CPP = @CPP@
    +CPPFLAGS = @CPPFLAGS@
    +CXX = @CXX@
    +CXXCPP = @CXXCPP@
    +CXXDEPMODE = @CXXDEPMODE@
    +CXXFLAGS = @CXXFLAGS@
    +CYGPATH_W = @CYGPATH_W@
    +DEFS = @DEFS@
    +DEPDIR = @DEPDIR@
    +DLLTOOL = @DLLTOOL@
    +DOCBOOK_TO_MAN = @DOCBOOK_TO_MAN@
    +DSYMUTIL = @DSYMUTIL@
    +DUMPBIN = @DUMPBIN@
    +ECHO_C = @ECHO_C@
    +ECHO_N = @ECHO_N@
    +ECHO_T = @ECHO_T@
    +EGREP = @EGREP@
    +EXEEXT = @EXEEXT@
    +FGREP = @FGREP@
    +FILEMAP = @FILEMAP@
    +GREP = @GREP@
    +INSTALL = @INSTALL@
    +INSTALL_DATA = @INSTALL_DATA@
    +INSTALL_PROGRAM = @INSTALL_PROGRAM@
    +INSTALL_SCRIPT = @INSTALL_SCRIPT@
    +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
    +LD = @LD@
    +LDFLAGS = @LDFLAGS@
    +LIBAGE = @LIBAGE@
    +LIBCURRENT = @LIBCURRENT@
    +LIBOBJS = @LIBOBJS@
    +LIBREVISION = @LIBREVISION@
    +LIBS = @LIBS@
    +LIBTOOL = @LIBTOOL@
    +LIPO = @LIPO@
    +LN_S = @LN_S@
    +LTLIBOBJS = @LTLIBOBJS@
    +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@
    +MAKEINFO = @MAKEINFO@
    +MANIFEST_TOOL = @MANIFEST_TOOL@
    +MKDIR_P = @MKDIR_P@
    +NM = @NM@
    +NMEDIT = @NMEDIT@
    +OBJDUMP = @OBJDUMP@
    +OBJEXT = @OBJEXT@
    +OTOOL = @OTOOL@
    +OTOOL64 = @OTOOL64@
    +PACKAGE = @PACKAGE@
    +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
    +PACKAGE_NAME = @PACKAGE_NAME@
    +PACKAGE_STRING = @PACKAGE_STRING@
    +PACKAGE_TARNAME = @PACKAGE_TARNAME@
    +PACKAGE_URL = @PACKAGE_URL@
    +PACKAGE_VERSION = @PACKAGE_VERSION@
    +PATH_SEPARATOR = @PATH_SEPARATOR@
    +RANLIB = @RANLIB@
    +SED = @SED@
    +SET_MAKE = @SET_MAKE@
    +SHELL = @SHELL@
    +STRIP = @STRIP@
    +VERSION = @VERSION@
    +abs_builddir = @abs_builddir@
    +abs_srcdir = @abs_srcdir@
    +abs_top_builddir = @abs_top_builddir@
    +abs_top_srcdir = @abs_top_srcdir@
    +ac_ct_AR = @ac_ct_AR@
    +ac_ct_CC = @ac_ct_CC@
    +ac_ct_CXX = @ac_ct_CXX@
    +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@
    +am__include = @am__include@
    +am__leading_dot = @am__leading_dot@
    +am__quote = @am__quote@
    +am__tar = @am__tar@
    +am__untar = @am__untar@
    +bindir = @bindir@
    +build = @build@
    +build_alias = @build_alias@
    +build_cpu = @build_cpu@
    +build_os = @build_os@
    +build_vendor = @build_vendor@
    +builddir = @builddir@
    +datadir = @datadir@
    +datarootdir = @datarootdir@
    +docdir = @docdir@
    +dvidir = @dvidir@
    +exec_prefix = @exec_prefix@
    +host = @host@
    +host_alias = @host_alias@
    +host_cpu = @host_cpu@
    +host_os = @host_os@
    +host_vendor = @host_vendor@
    +htmldir = @htmldir@
    +includedir = @includedir@
    +infodir = @infodir@
    +install_sh = @install_sh@
    +libdir = @libdir@
    +libexecdir = @libexecdir@
    +localedir = @localedir@
    +localstatedir = @localstatedir@
    +mandir = @mandir@
    +mkdir_p = @mkdir_p@
    +oldincludedir = @oldincludedir@
    +pdfdir = @pdfdir@
    +prefix = @prefix@
    +program_transform_name = @program_transform_name@
    +psdir = @psdir@
    +sbindir = @sbindir@
    +sharedstatedir = @sharedstatedir@
    +srcdir = @srcdir@
    +sysconfdir = @sysconfdir@
    +target_alias = @target_alias@
    +top_build_prefix = @top_build_prefix@
    +top_builddir = @top_builddir@
    +top_srcdir = @top_srcdir@
    +xmlwf_LDADD = ../lib/libexpat.la
    +xmlwf_SOURCES = \
    +    xmlwf.c \
    +    xmlfile.c \
    +    codepage.c \
    +    @FILEMAP@.c
    +
    +xmlwf_CPPFLAGS = -I$(srcdir)/../lib $(am__append_1)
    +@MINGW_TRUE@@UNICODE_TRUE@xmlwf_LDFLAGS = -municode
    +EXTRA_DIST = \
    +    codepage.h \
    +    ct.c \
    +    filemap.h \
    +    readfilemap.c \
    +    unixfilemap.c \
    +    win32filemap.c \
    +    xmlfile.h \
    +    xmlmime.c \
    +    xmlmime.h \
    +    xmltchar.h \
    +    xmlurl.h \
    +    xmlwin32url.cxx
    +
    +all: all-am
    +
    +.SUFFIXES:
    +.SUFFIXES: .c .lo .o .obj
    +$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am  $(am__configure_deps)
    +	@for dep in $?; do \
    +	  case '$(am__configure_deps)' in \
    +	    *$$dep*) \
    +	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
    +	        && { if test -f $@; then exit 0; else break; fi; }; \
    +	      exit 1;; \
    +	  esac; \
    +	done; \
    +	echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu xmlwf/Makefile'; \
    +	$(am__cd) $(top_srcdir) && \
    +	  $(AUTOMAKE) --gnu xmlwf/Makefile
    +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
    +	@case '$?' in \
    +	  *config.status*) \
    +	    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
    +	  *) \
    +	    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
    +	    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
    +	esac;
    +
    +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +
    +$(top_srcdir)/configure:  $(am__configure_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(ACLOCAL_M4):  $(am__aclocal_m4_deps)
    +	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
    +$(am__aclocal_m4_deps):
    +install-binPROGRAMS: $(bin_PROGRAMS)
    +	@$(NORMAL_INSTALL)
    +	@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
    +	if test -n "$$list"; then \
    +	  echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \
    +	  $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \
    +	fi; \
    +	for p in $$list; do echo "$$p $$p"; done | \
    +	sed 's/$(EXEEXT)$$//' | \
    +	while read p p1; do if test -f $$p \
    +	 || test -f $$p1 \
    +	  ; then echo "$$p"; echo "$$p"; else :; fi; \
    +	done | \
    +	sed -e 'p;s,.*/,,;n;h' \
    +	    -e 's|.*|.|' \
    +	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
    +	sed 'N;N;N;s,\n, ,g' | \
    +	$(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \
    +	  { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \
    +	    if ($$2 == $$4) files[d] = files[d] " " $$1; \
    +	    else { print "f", $$3 "/" $$4, $$1; } } \
    +	  END { for (d in files) print "f", d, files[d] }' | \
    +	while read type dir files; do \
    +	    if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \
    +	    test -z "$$files" || { \
    +	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \
    +	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
    +	    } \
    +	; done
    +
    +uninstall-binPROGRAMS:
    +	@$(NORMAL_UNINSTALL)
    +	@list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \
    +	files=`for p in $$list; do echo "$$p"; done | \
    +	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
    +	      -e 's/$$/$(EXEEXT)/' \
    +	`; \
    +	test -n "$$list" || exit 0; \
    +	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
    +	cd "$(DESTDIR)$(bindir)" && rm -f $$files
    +
    +clean-binPROGRAMS:
    +	@list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list || exit $$?; \
    +	test -n "$(EXEEXT)" || exit 0; \
    +	list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
    +	echo " rm -f" $$list; \
    +	rm -f $$list
    +
    +xmlwf$(EXEEXT): $(xmlwf_OBJECTS) $(xmlwf_DEPENDENCIES) $(EXTRA_xmlwf_DEPENDENCIES) 
    +	@rm -f xmlwf$(EXEEXT)
    +	$(AM_V_CCLD)$(xmlwf_LINK) $(xmlwf_OBJECTS) $(xmlwf_LDADD) $(LIBS)
    +
    +mostlyclean-compile:
    +	-rm -f *.$(OBJEXT)
    +
    +distclean-compile:
    +	-rm -f *.tab.c
    +
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmlwf-@FILEMAP@.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmlwf-codepage.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmlwf-xmlfile.Po@am__quote@
    +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmlwf-xmlwf.Po@am__quote@
    +
    +.c.o:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $<
    +
    +.c.obj:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
    +
    +.c.lo:
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $<
    +
    +xmlwf-xmlwf.o: xmlwf.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-xmlwf.o -MD -MP -MF $(DEPDIR)/xmlwf-xmlwf.Tpo -c -o xmlwf-xmlwf.o `test -f 'xmlwf.c' || echo '$(srcdir)/'`xmlwf.c
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-xmlwf.Tpo $(DEPDIR)/xmlwf-xmlwf.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='xmlwf.c' object='xmlwf-xmlwf.o' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-xmlwf.o `test -f 'xmlwf.c' || echo '$(srcdir)/'`xmlwf.c
    +
    +xmlwf-xmlwf.obj: xmlwf.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-xmlwf.obj -MD -MP -MF $(DEPDIR)/xmlwf-xmlwf.Tpo -c -o xmlwf-xmlwf.obj `if test -f 'xmlwf.c'; then $(CYGPATH_W) 'xmlwf.c'; else $(CYGPATH_W) '$(srcdir)/xmlwf.c'; fi`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-xmlwf.Tpo $(DEPDIR)/xmlwf-xmlwf.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='xmlwf.c' object='xmlwf-xmlwf.obj' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-xmlwf.obj `if test -f 'xmlwf.c'; then $(CYGPATH_W) 'xmlwf.c'; else $(CYGPATH_W) '$(srcdir)/xmlwf.c'; fi`
    +
    +xmlwf-xmlfile.o: xmlfile.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-xmlfile.o -MD -MP -MF $(DEPDIR)/xmlwf-xmlfile.Tpo -c -o xmlwf-xmlfile.o `test -f 'xmlfile.c' || echo '$(srcdir)/'`xmlfile.c
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-xmlfile.Tpo $(DEPDIR)/xmlwf-xmlfile.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='xmlfile.c' object='xmlwf-xmlfile.o' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-xmlfile.o `test -f 'xmlfile.c' || echo '$(srcdir)/'`xmlfile.c
    +
    +xmlwf-xmlfile.obj: xmlfile.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-xmlfile.obj -MD -MP -MF $(DEPDIR)/xmlwf-xmlfile.Tpo -c -o xmlwf-xmlfile.obj `if test -f 'xmlfile.c'; then $(CYGPATH_W) 'xmlfile.c'; else $(CYGPATH_W) '$(srcdir)/xmlfile.c'; fi`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-xmlfile.Tpo $(DEPDIR)/xmlwf-xmlfile.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='xmlfile.c' object='xmlwf-xmlfile.obj' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-xmlfile.obj `if test -f 'xmlfile.c'; then $(CYGPATH_W) 'xmlfile.c'; else $(CYGPATH_W) '$(srcdir)/xmlfile.c'; fi`
    +
    +xmlwf-codepage.o: codepage.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-codepage.o -MD -MP -MF $(DEPDIR)/xmlwf-codepage.Tpo -c -o xmlwf-codepage.o `test -f 'codepage.c' || echo '$(srcdir)/'`codepage.c
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-codepage.Tpo $(DEPDIR)/xmlwf-codepage.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='codepage.c' object='xmlwf-codepage.o' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-codepage.o `test -f 'codepage.c' || echo '$(srcdir)/'`codepage.c
    +
    +xmlwf-codepage.obj: codepage.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-codepage.obj -MD -MP -MF $(DEPDIR)/xmlwf-codepage.Tpo -c -o xmlwf-codepage.obj `if test -f 'codepage.c'; then $(CYGPATH_W) 'codepage.c'; else $(CYGPATH_W) '$(srcdir)/codepage.c'; fi`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-codepage.Tpo $(DEPDIR)/xmlwf-codepage.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='codepage.c' object='xmlwf-codepage.obj' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-codepage.obj `if test -f 'codepage.c'; then $(CYGPATH_W) 'codepage.c'; else $(CYGPATH_W) '$(srcdir)/codepage.c'; fi`
    +
    +xmlwf-@FILEMAP@.o: @FILEMAP@.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-@FILEMAP@.o -MD -MP -MF $(DEPDIR)/xmlwf-@FILEMAP@.Tpo -c -o xmlwf-@FILEMAP@.o `test -f '@FILEMAP@.c' || echo '$(srcdir)/'`@FILEMAP@.c
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-@FILEMAP@.Tpo $(DEPDIR)/xmlwf-@FILEMAP@.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='@FILEMAP@.c' object='xmlwf-@FILEMAP@.o' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-@FILEMAP@.o `test -f '@FILEMAP@.c' || echo '$(srcdir)/'`@FILEMAP@.c
    +
    +xmlwf-@FILEMAP@.obj: @FILEMAP@.c
    +@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT xmlwf-@FILEMAP@.obj -MD -MP -MF $(DEPDIR)/xmlwf-@FILEMAP@.Tpo -c -o xmlwf-@FILEMAP@.obj `if test -f '@FILEMAP@.c'; then $(CYGPATH_W) '@FILEMAP@.c'; else $(CYGPATH_W) '$(srcdir)/@FILEMAP@.c'; fi`
    +@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) $(DEPDIR)/xmlwf-@FILEMAP@.Tpo $(DEPDIR)/xmlwf-@FILEMAP@.Po
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='@FILEMAP@.c' object='xmlwf-@FILEMAP@.obj' libtool=no @AMDEPBACKSLASH@
    +@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
    +@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(xmlwf_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o xmlwf-@FILEMAP@.obj `if test -f '@FILEMAP@.c'; then $(CYGPATH_W) '@FILEMAP@.c'; else $(CYGPATH_W) '$(srcdir)/@FILEMAP@.c'; fi`
    +
    +mostlyclean-libtool:
    +	-rm -f *.lo
    +
    +clean-libtool:
    +	-rm -rf .libs _libs
    +
    +ID: $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); mkid -fID $$unique
    +tags: tags-am
    +TAGS: tags
    +
    +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	set x; \
    +	here=`pwd`; \
    +	$(am__define_uniq_tagged_files); \
    +	shift; \
    +	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
    +	  test -n "$$unique" || unique=$$empty_fix; \
    +	  if test $$# -gt 0; then \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      "$$@" $$unique; \
    +	  else \
    +	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
    +	      $$unique; \
    +	  fi; \
    +	fi
    +ctags: ctags-am
    +
    +CTAGS: ctags
    +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
    +	$(am__define_uniq_tagged_files); \
    +	test -z "$(CTAGS_ARGS)$$unique" \
    +	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
    +	     $$unique
    +
    +GTAGS:
    +	here=`$(am__cd) $(top_builddir) && pwd` \
    +	  && $(am__cd) $(top_srcdir) \
    +	  && gtags -i $(GTAGS_ARGS) "$$here"
    +cscopelist: cscopelist-am
    +
    +cscopelist-am: $(am__tagged_files)
    +	list='$(am__tagged_files)'; \
    +	case "$(srcdir)" in \
    +	  [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
    +	  *) sdir=$(subdir)/$(srcdir) ;; \
    +	esac; \
    +	for i in $$list; do \
    +	  if test -f "$$i"; then \
    +	    echo "$(subdir)/$$i"; \
    +	  else \
    +	    echo "$$sdir/$$i"; \
    +	  fi; \
    +	done >> $(top_builddir)/cscope.files
    +
    +distclean-tags:
    +	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
    +
    +distdir: $(DISTFILES)
    +	@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
    +	list='$(DISTFILES)'; \
    +	  dist_files=`for file in $$list; do echo $$file; done | \
    +	  sed -e "s|^$$srcdirstrip/||;t" \
    +	      -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
    +	case $$dist_files in \
    +	  */*) $(MKDIR_P) `echo "$$dist_files" | \
    +			   sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
    +			   sort -u` ;; \
    +	esac; \
    +	for file in $$dist_files; do \
    +	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
    +	  if test -d $$d/$$file; then \
    +	    dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
    +	    if test -d "$(distdir)/$$file"; then \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
    +	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
    +	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
    +	    fi; \
    +	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
    +	  else \
    +	    test -f "$(distdir)/$$file" \
    +	    || cp -p $$d/$$file "$(distdir)/$$file" \
    +	    || exit 1; \
    +	  fi; \
    +	done
    +check-am: all-am
    +check: check-am
    +all-am: Makefile $(PROGRAMS)
    +installdirs:
    +	for dir in "$(DESTDIR)$(bindir)"; do \
    +	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
    +	done
    +install: install-am
    +install-exec: install-exec-am
    +install-data: install-data-am
    +uninstall: uninstall-am
    +
    +install-am: all-am
    +	@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
    +
    +installcheck: installcheck-am
    +install-strip:
    +	if test -z '$(STRIP)'; then \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	      install; \
    +	else \
    +	  $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
    +	    install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
    +	    "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
    +	fi
    +mostlyclean-generic:
    +
    +clean-generic:
    +
    +distclean-generic:
    +	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
    +	-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
    +
    +maintainer-clean-generic:
    +	@echo "This command is intended for maintainers to use"
    +	@echo "it deletes files that may require special tools to rebuild."
    +clean: clean-am
    +
    +clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
    +
    +distclean: distclean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +distclean-am: clean-am distclean-compile distclean-generic \
    +	distclean-tags
    +
    +dvi: dvi-am
    +
    +dvi-am:
    +
    +html: html-am
    +
    +html-am:
    +
    +info: info-am
    +
    +info-am:
    +
    +install-data-am:
    +
    +install-dvi: install-dvi-am
    +
    +install-dvi-am:
    +
    +install-exec-am: install-binPROGRAMS
    +
    +install-html: install-html-am
    +
    +install-html-am:
    +
    +install-info: install-info-am
    +
    +install-info-am:
    +
    +install-man:
    +
    +install-pdf: install-pdf-am
    +
    +install-pdf-am:
    +
    +install-ps: install-ps-am
    +
    +install-ps-am:
    +
    +installcheck-am:
    +
    +maintainer-clean: maintainer-clean-am
    +	-rm -rf ./$(DEPDIR)
    +	-rm -f Makefile
    +maintainer-clean-am: distclean-am maintainer-clean-generic
    +
    +mostlyclean: mostlyclean-am
    +
    +mostlyclean-am: mostlyclean-compile mostlyclean-generic \
    +	mostlyclean-libtool
    +
    +pdf: pdf-am
    +
    +pdf-am:
    +
    +ps: ps-am
    +
    +ps-am:
    +
    +uninstall-am: uninstall-binPROGRAMS
    +
    +.MAKE: install-am install-strip
    +
    +.PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \
    +	clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \
    +	ctags ctags-am distclean distclean-compile distclean-generic \
    +	distclean-libtool distclean-tags distdir dvi dvi-am html \
    +	html-am info info-am install install-am install-binPROGRAMS \
    +	install-data install-data-am install-dvi install-dvi-am \
    +	install-exec install-exec-am install-html install-html-am \
    +	install-info install-info-am install-man install-pdf \
    +	install-pdf-am install-ps install-ps-am install-strip \
    +	installcheck installcheck-am installdirs maintainer-clean \
    +	maintainer-clean-generic mostlyclean mostlyclean-compile \
    +	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
    +	tags tags-am uninstall uninstall-am uninstall-binPROGRAMS
    +
    +.PRECIOUS: Makefile
    +
    +
    +# Tell versions [3.59,3.63) of GNU make to not export all variables.
    +# Otherwise a system limit (for SysV at least) may be exceeded.
    +.NOEXPORT:
    diff --git a/contrib/expat/xmlwf/codepage.c b/contrib/expat/xmlwf/codepage.c
    index 91bd15e96f8b..1a0487ff91d2 100644
    --- a/contrib/expat/xmlwf/codepage.c
    +++ b/contrib/expat/xmlwf/codepage.c
    @@ -1,11 +1,39 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #include "codepage.h"
     #include "internal.h"  /* for UNUSED_P only */
     
    -#if (defined(WIN32) || (defined(__WATCOMC__) && defined(__NT__)))
    +#if defined(_WIN32)
     #define STRICT 1
     #define WIN32_LEAN_AND_MEAN 1
     
    @@ -52,7 +80,7 @@ codepageConvert(int cp, const char *p)
       return -1;
     }
     
    -#else /* not WIN32 */
    +#else /* not _WIN32 */
     
     int
     codepageMap(int UNUSED_P(cp), int *UNUSED_P(map))
    @@ -66,4 +94,4 @@ codepageConvert(int UNUSED_P(cp), const char *UNUSED_P(p))
       return -1;
     }
     
    -#endif /* not WIN32 */
    +#endif /* not _WIN32 */
    diff --git a/contrib/expat/xmlwf/codepage.h b/contrib/expat/xmlwf/codepage.h
    index 6a4df68883e4..1b75d58365f4 100644
    --- a/contrib/expat/xmlwf/codepage.h
    +++ b/contrib/expat/xmlwf/codepage.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     int codepageMap(int cp, int *map);
    diff --git a/contrib/expat/xmlwf/ct.c b/contrib/expat/xmlwf/ct.c
    index 95903a34500a..dd42f5ec98d8 100644
    --- a/contrib/expat/xmlwf/ct.c
    +++ b/contrib/expat/xmlwf/ct.c
    @@ -1,3 +1,35 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     #define CHARSET_MAX 41
     
     static const char *
    diff --git a/contrib/expat/xmlwf/filemap.h b/contrib/expat/xmlwf/filemap.h
    index 814edec2528c..5487a4ebe50b 100644
    --- a/contrib/expat/xmlwf/filemap.h
    +++ b/contrib/expat/xmlwf/filemap.h
    @@ -1,9 +1,49 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
    +#include   /* INT_MAX */
     #include 
     
    +
    +/* The following limit (for XML_Parse's int len) derives from
    + * this loop in xmparse.c:
    + *
    + *    do {
    + *      bufferSize = (int) (2U * (unsigned) bufferSize);
    + *    } while (bufferSize < neededSize && bufferSize > 0);
    + */
    +#define XML_MAX_CHUNK_LEN  (INT_MAX / 2 + 1)
    +
    +
     #ifdef XML_UNICODE
     int filemap(const wchar_t *name,
                 void (*processor)(const void *, size_t,
    diff --git a/contrib/expat/xmlwf/readfilemap.c b/contrib/expat/xmlwf/readfilemap.c
    index d816b263aae1..4c4780bde0e3 100644
    --- a/contrib/expat/xmlwf/readfilemap.c
    +++ b/contrib/expat/xmlwf/readfilemap.c
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #include 
    @@ -9,64 +37,76 @@
     #include 
     
     /* Functions close(2) and read(2) */
    -#ifdef __WATCOMC__
    -#ifndef __LINUX__
    -#include 
    -#else
    -#include 
    +#if !defined(_WIN32) && !defined(_WIN64)
    +# include 
     #endif
    -#else
    -# if !defined(WIN32) && !defined(_WIN32) && !defined(_WIN64)
    -#  include 
    -# endif
    +
    +/* Function "read": */
    +#if defined(_MSC_VER)
    +# include 
    +  /* https://msdn.microsoft.com/en-us/library/wyssk1bs(v=vs.100).aspx */
    +# define _EXPAT_read          _read
    +# define _EXPAT_read_count_t  int
    +# define _EXPAT_read_req_t    unsigned int
    +#else  /* POSIX */
    +  /* http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html */
    +# define _EXPAT_read          read
    +# define _EXPAT_read_count_t  ssize_t
    +# define _EXPAT_read_req_t    size_t
     #endif
     
     #ifndef S_ISREG
    -#ifndef S_IFREG
    -#define S_IFREG _S_IFREG
    -#endif
    -#ifndef S_IFMT
    -#define S_IFMT _S_IFMT
    -#endif
    -#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
    +# ifndef S_IFREG
    +#  define S_IFREG _S_IFREG
    +# endif
    +# ifndef S_IFMT
    +#  define S_IFMT _S_IFMT
    +# endif
    +# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
     #endif /* not S_ISREG */
     
     #ifndef O_BINARY
    -#ifdef _O_BINARY
    -#define O_BINARY _O_BINARY
    -#else
    -#define O_BINARY 0
    -#endif
    +# ifdef _O_BINARY
    +#  define O_BINARY _O_BINARY
    +# else
    +#  define O_BINARY 0
    +# endif
     #endif
     
    +#include "xmltchar.h"
     #include "filemap.h"
     
     int
    -filemap(const char *name,
    -        void (*processor)(const void *, size_t, const char *, void *arg),
    +filemap(const tchar *name,
    +        void (*processor)(const void *, size_t, const tchar *, void *arg),
             void *arg)
     {
       size_t nbytes;
       int fd;
    -  int n;
    +  _EXPAT_read_count_t n;
       struct stat sb;
       void *p;
     
    -  fd = open(name, O_RDONLY|O_BINARY);
    +  fd = topen(name, O_RDONLY|O_BINARY);
       if (fd < 0) {
    -    perror(name);
    +    tperror(name);
         return 0;
       }
       if (fstat(fd, &sb) < 0) {
    -    perror(name);
    +    tperror(name);
         close(fd);
         return 0;
       }
       if (!S_ISREG(sb.st_mode)) {
    -    fprintf(stderr, "%s: not a regular file\n", name);
    +    ftprintf(stderr, T("%s: not a regular file\n"), name);
         close(fd);
         return 0;
       }
    +  if (sb.st_size > XML_MAX_CHUNK_LEN) {
    +    close(fd);
    +    return 2;  /* Cannot be passed to XML_Parse in one go */
    +  }
    +
       nbytes = sb.st_size;
       /* malloc will return NULL with nbytes == 0, handle files with size 0 */
       if (nbytes == 0) {
    @@ -77,19 +117,19 @@ filemap(const char *name,
       }
       p = malloc(nbytes);
       if (!p) {
    -    fprintf(stderr, "%s: out of memory\n", name);
    +    ftprintf(stderr, T("%s: out of memory\n"), name);
         close(fd);
         return 0;
       }
    -  n = read(fd, p, nbytes);
    +  n = _EXPAT_read(fd, p, (_EXPAT_read_req_t)nbytes);
       if (n < 0) {
    -    perror(name);
    +    tperror(name);
         free(p);
         close(fd);
         return 0;
       }
    -  if (n != nbytes) {
    -    fprintf(stderr, "%s: read unexpected number of bytes\n", name);
    +  if (n != (_EXPAT_read_count_t)nbytes) {
    +    ftprintf(stderr, T("%s: read unexpected number of bytes\n"), name);
         free(p);
         close(fd);
         return 0;
    diff --git a/contrib/expat/xmlwf/unixfilemap.c b/contrib/expat/xmlwf/unixfilemap.c
    index e13299da05fc..4ab757c2ab9c 100644
    --- a/contrib/expat/xmlwf/unixfilemap.c
    +++ b/contrib/expat/xmlwf/unixfilemap.c
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #include 
    @@ -15,11 +43,18 @@
     #define MAP_FILE 0
     #endif
     
    +#include "xmltchar.h"
     #include "filemap.h"
     
    +#ifdef XML_UNICODE_WCHAR_T
    +# define XML_FMT_STR "ls"
    +#else
    +# define XML_FMT_STR "s"
    +#endif
    +
     int
    -filemap(const char *name,
    -        void (*processor)(const void *, size_t, const char *, void *arg),
    +filemap(const tchar *name,
    +        void (*processor)(const void *, size_t, const tchar *, void *arg),
             void *arg)
     {
       int fd;
    @@ -27,21 +62,25 @@ filemap(const char *name,
       struct stat sb;
       void *p;
     
    -  fd = open(name, O_RDONLY);
    +  fd = topen(name, O_RDONLY);
       if (fd < 0) {
    -    perror(name);
    +    tperror(name);
         return 0;
       }
       if (fstat(fd, &sb) < 0) {
    -    perror(name);
    +    tperror(name);
         close(fd);
         return 0;
       }
       if (!S_ISREG(sb.st_mode)) {
         close(fd);
    -    fprintf(stderr, "%s: not a regular file\n", name);
    +    fprintf(stderr, "%" XML_FMT_STR ": not a regular file\n", name);
         return 0;
       }
    +  if (sb.st_size > XML_MAX_CHUNK_LEN) {
    +    close(fd);
    +    return 2;  /* Cannot be passed to XML_Parse in one go */
    +  }
     
       nbytes = sb.st_size;
       /* mmap fails for zero length files */
    @@ -54,7 +93,7 @@ filemap(const char *name,
       p = (void *)mmap((void *)0, (size_t)nbytes, PROT_READ,
                        MAP_FILE|MAP_PRIVATE, fd, (off_t)0);
       if (p == (void *)-1) {
    -    perror(name);
    +    tperror(name);
         close(fd);
         return 0;
       }
    diff --git a/contrib/expat/xmlwf/win32filemap.c b/contrib/expat/xmlwf/win32filemap.c
    index 41dc35b614db..a040a097db4c 100644
    --- a/contrib/expat/xmlwf/win32filemap.c
    +++ b/contrib/expat/xmlwf/win32filemap.c
    @@ -1,19 +1,47 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #define STRICT 1
     #define WIN32_LEAN_AND_MEAN 1
     
     #ifdef XML_UNICODE_WCHAR_T
    -#ifndef XML_UNICODE
    -#define XML_UNICODE
    -#endif
    +# ifndef XML_UNICODE
    +#  define XML_UNICODE
    +# endif
     #endif
     
     #ifdef XML_UNICODE
    -#define UNICODE
    -#define _UNICODE
    +# define UNICODE
    +# define _UNICODE
     #endif /* XML_UNICODE */
     #include 
     #include 
    @@ -42,11 +70,12 @@ filemap(const TCHAR *name,
       size = GetFileSize(f, &sizeHi);
       if (size == (DWORD)-1) {
         win32perror(name);
    +    CloseHandle(f);
         return 0;
       }
    -  if (sizeHi) {
    -    _ftprintf(stderr, _T("%s: bigger than 2Gb\n"), name);
    -    return 0;
    +  if (sizeHi || (size > XML_MAX_CHUNK_LEN)) {
    +    CloseHandle(f);
    +    return 2;  /* Cannot be passed to XML_Parse in one go */
       }
       /* CreateFileMapping barfs on zero length files */
       if (size == 0) {
    diff --git a/contrib/expat/xmlwf/xmlfile.c b/contrib/expat/xmlwf/xmlfile.c
    index 2f769aa894cf..4075f5710cad 100644
    --- a/contrib/expat/xmlwf/xmlfile.c
    +++ b/contrib/expat/xmlwf/xmlfile.c
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #include 
    @@ -8,17 +36,11 @@
     #include 
     #include 
     
    -#ifdef WIN32
    +#ifdef _WIN32
     #include "winconfig.h"
    -#elif defined(MACOS_CLASSIC)
    -#include "macconfig.h"
    -#elif defined(__amigaos__)
    -#include "amigaconfig.h"
    -#elif defined(__WATCOMC__)
    -#include "watcomconfig.h"
     #elif defined(HAVE_EXPAT_CONFIG_H)
     #include 
    -#endif /* ndef WIN32 */
    +#endif /* ndef _WIN32 */
     
     #include "expat.h"
     #include "internal.h"  /* for UNUSED_P only */
    @@ -26,14 +48,10 @@
     #include "xmltchar.h"
     #include "filemap.h"
     
    -#if (defined(_MSC_VER) || (defined(__WATCOMC__) && !defined(__LINUX__)))
    +#if defined(_MSC_VER)
     #include 
     #endif
     
    -#if defined(__amigaos__) && defined(__USE_INLINE__)
    -#include 
    -#endif
    -
     #ifdef HAVE_UNISTD_H
     #include 
     #endif
    @@ -58,13 +76,20 @@ typedef struct {
       int *retPtr;
     } PROCESS_ARGS;
     
    +static int
    +processStream(const XML_Char *filename, XML_Parser parser);
    +
     static void
     reportError(XML_Parser parser, const XML_Char *filename)
     {
       enum XML_Error code = XML_GetErrorCode(parser);
       const XML_Char *message = XML_ErrorString(code);
       if (message)
    -    ftprintf(stdout, T("%s:%" XML_FMT_INT_MOD "u:%" XML_FMT_INT_MOD "u: %s\n"),
    +    ftprintf(stdout,
    +             T("%s")
    +               T(":%") T(XML_FMT_INT_MOD) T("u")
    +               T(":%") T(XML_FMT_INT_MOD) T("u")
    +               T(": %s\n"),
                  filename,
                  XML_GetErrorLineNumber(parser),
                  XML_GetErrorColumnNumber(parser),
    @@ -88,7 +113,7 @@ processFile(const void *data, size_t size,
         *retPtr = 1;
     }
     
    -#if (defined(WIN32) || defined(__WATCOMC__))
    +#if defined(_WIN32)
     
     static int
     isAsciiLetter(XML_Char c)
    @@ -96,7 +121,7 @@ isAsciiLetter(XML_Char c)
       return (T('a') <= c && c <= T('z')) || (T('A') <= c && c <= T('Z'));
     }
     
    -#endif /* WIN32 */
    +#endif /* _WIN32 */
     
     static const XML_Char *
     resolveSystemId(const XML_Char *base, const XML_Char *systemId,
    @@ -106,7 +131,7 @@ resolveSystemId(const XML_Char *base, const XML_Char *systemId,
       *toFree = 0;
       if (!base
           || *systemId == T('/')
    -#if (defined(WIN32) || defined(__WATCOMC__))
    +#if defined(_WIN32)
           || *systemId == T('\\')
           || (isAsciiLetter(systemId[0]) && systemId[1] == T(':'))
     #endif
    @@ -120,7 +145,7 @@ resolveSystemId(const XML_Char *base, const XML_Char *systemId,
       s = *toFree;
       if (tcsrchr(s, T('/')))
         s = tcsrchr(s, T('/')) + 1;
    -#if (defined(WIN32) || defined(__WATCOMC__))
    +#if defined(_WIN32)
       if (tcsrchr(s, T('\\')))
         s = tcsrchr(s, T('\\')) + 1;
     #endif
    @@ -139,13 +164,23 @@ externalEntityRefFilemap(XML_Parser parser,
       XML_Char *s;
       const XML_Char *filename;
       XML_Parser entParser = XML_ExternalEntityParserCreate(parser, context, 0);
    +  int filemapRes;
       PROCESS_ARGS args;
       args.retPtr = &result;
       args.parser = entParser;
       filename = resolveSystemId(base, systemId, &s);
       XML_SetBase(entParser, filename);
    -  if (!filemap(filename, processFile, &args))
    +  filemapRes = filemap(filename, processFile, &args);
    +  switch (filemapRes) {
    +  case 0:
         result = 0;
    +    break;
    +  case 2:
    +    ftprintf(stderr, T("%s: file too large for memory-mapping")
    +        T(", switching to streaming\n"), filename);
    +    result = processStream(filename, entParser);
    +    break;
    +  }
       free(s);
       XML_ParserFree(entParser);
       return result;
    @@ -171,18 +206,18 @@ processStream(const XML_Char *filename, XML_Parser parser)
           if (filename != NULL)
             close(fd);
           ftprintf(stderr, T("%s: out of memory\n"),
    -               filename != NULL ? filename : "xmlwf");
    +               filename != NULL ? filename : T("xmlwf"));
           return 0;
         }
         nread = read(fd, buf, READ_SIZE);
         if (nread < 0) {
    -      tperror(filename != NULL ? filename : "STDIN");
    +      tperror(filename != NULL ? filename : T("STDIN"));
           if (filename != NULL)
             close(fd);
           return 0;
         }
         if (XML_ParseBuffer(parser, nread, nread == 0) == XML_STATUS_ERROR) {
    -      reportError(parser, filename != NULL ? filename : "STDIN");
    +        reportError(parser, filename != NULL ? filename : T("STDIN"));
           if (filename != NULL)
             close(fd);
           return 0;
    @@ -233,11 +268,21 @@ XML_ProcessFile(XML_Parser parser,
                                           ? externalEntityRefFilemap
                                           : externalEntityRefStream);
       if (flags & XML_MAP_FILE) {
    +    int filemapRes;
         PROCESS_ARGS args;
         args.retPtr = &result;
         args.parser = parser;
    -    if (!filemap(filename, processFile, &args))
    +    filemapRes = filemap(filename, processFile, &args);
    +    switch (filemapRes) {
    +    case 0:
           result = 0;
    +      break;
    +    case 2:
    +      ftprintf(stderr, T("%s: file too large for memory-mapping")
    +          T(", switching to streaming\n"), filename);
    +      result = processStream(filename, parser);
    +      break;
    +    }
       }
       else
         result = processStream(filename, parser);
    diff --git a/contrib/expat/xmlwf/xmlfile.h b/contrib/expat/xmlwf/xmlfile.h
    index d093ecc06f9c..c47ea2cf5947 100644
    --- a/contrib/expat/xmlwf/xmlfile.h
    +++ b/contrib/expat/xmlwf/xmlfile.h
    @@ -1,5 +1,33 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
     #define XML_MAP_FILE 01
    diff --git a/contrib/expat/xmlwf/xmlmime.c b/contrib/expat/xmlwf/xmlmime.c
    index 56a0e7f40e49..c530979060f4 100644
    --- a/contrib/expat/xmlwf/xmlmime.c
    +++ b/contrib/expat/xmlwf/xmlmime.c
    @@ -1,3 +1,35 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     #include 
     #include "xmlmime.h"
     
    diff --git a/contrib/expat/xmlwf/xmlmime.h b/contrib/expat/xmlwf/xmlmime.h
    index bf0356df0d91..0471286234a1 100644
    --- a/contrib/expat/xmlwf/xmlmime.h
    +++ b/contrib/expat/xmlwf/xmlmime.h
    @@ -1,3 +1,35 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     #ifdef __cplusplus
     extern "C" {
     #endif
    diff --git a/contrib/expat/xmlwf/xmltchar.h b/contrib/expat/xmlwf/xmltchar.h
    index 1088575512de..cdfaea79552f 100644
    --- a/contrib/expat/xmlwf/xmltchar.h
    +++ b/contrib/expat/xmlwf/xmltchar.h
    @@ -1,36 +1,74 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
    +/* Ensures compile-time constants are consistent */
    +#include "expat_external.h"
    +
     #ifdef XML_UNICODE
    -#ifndef XML_UNICODE_WCHAR_T
    -#error xmlwf requires a 16-bit Unicode-compatible wchar_t 
    -#endif
    -#define T(x) L ## x
    -#define ftprintf fwprintf
    -#define tfopen _wfopen
    -#define fputts fputws
    -#define puttc putwc
    -#define tcscmp wcscmp
    -#define tcscpy wcscpy
    -#define tcscat wcscat
    -#define tcschr wcschr
    -#define tcsrchr wcsrchr
    -#define tcslen wcslen
    -#define tperror _wperror
    -#define topen _wopen
    -#define tmain wmain
    -#define tremove _wremove
    +# ifndef XML_UNICODE_WCHAR_T
    +#  error xmlwf requires a 16-bit Unicode-compatible wchar_t
    +# endif
    +# define _PREPEND_BIG_L(x) L ## x
    +# define T(x) _PREPEND_BIG_L(x)
    +# define ftprintf fwprintf
    +# define tfopen _wfopen
    +# define fputts fputws
    +# define puttc putwc
    +# define tcscmp wcscmp
    +# define tcscpy wcscpy
    +# define tcscat wcscat
    +# define tcschr wcschr
    +# define tcsrchr wcsrchr
    +# define tcslen wcslen
    +# define tperror _wperror
    +# define topen _wopen
    +# define tmain wmain
    +# define tremove _wremove
    +# define tchar wchar_t
     #else /* not XML_UNICODE */
    -#define T(x) x
    -#define ftprintf fprintf
    -#define tfopen fopen
    -#define fputts fputs
    -#define puttc putc
    -#define tcscmp strcmp
    -#define tcscpy strcpy
    -#define tcscat strcat
    -#define tcschr strchr
    -#define tcsrchr strrchr
    -#define tcslen strlen
    -#define tperror perror
    -#define topen open
    -#define tmain main
    -#define tremove remove
    +# define T(x) x
    +# define ftprintf fprintf
    +# define tfopen fopen
    +# define fputts fputs
    +# define puttc putc
    +# define tcscmp strcmp
    +# define tcscpy strcpy
    +# define tcscat strcat
    +# define tcschr strchr
    +# define tcsrchr strrchr
    +# define tcslen strlen
    +# define tperror perror
    +# define topen open
    +# define tmain main
    +# define tremove remove
    +# define tchar char
     #endif /* not XML_UNICODE */
    diff --git a/contrib/expat/xmlwf/xmlurl.h b/contrib/expat/xmlwf/xmlurl.h
    index d329913ac853..f2cff093e2ea 100644
    --- a/contrib/expat/xmlwf/xmlurl.h
    +++ b/contrib/expat/xmlwf/xmlurl.h
    @@ -1,3 +1,35 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     #ifdef __cplusplus
     extern "C" {
     #endif
    diff --git a/contrib/expat/xmlwf/xmlwf.c b/contrib/expat/xmlwf/xmlwf.c
    index 66d6c9ef4b71..82d028ea56fd 100644
    --- a/contrib/expat/xmlwf/xmlwf.c
    +++ b/contrib/expat/xmlwf/xmlwf.c
    @@ -1,7 +1,36 @@
    -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
    -   See the file COPYING for copying permission.
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
     
    +#include 
     #include 
     #include 
     #include 
    @@ -14,13 +43,28 @@
     #include "xmltchar.h"
     
     #ifdef _MSC_VER
    -#include 
    +# include 
     #endif
     
    -#if defined(__amigaos__) && defined(__USE_INLINE__)
    -#include 
    +#ifdef XML_UNICODE
    +# include 
     #endif
     
    +/* Structures for handler user data */
    +typedef struct NotationList {
    +  struct NotationList *next;
    +  const XML_Char *notationName;
    +  const XML_Char *systemId;
    +  const XML_Char *publicId;
    +} NotationList;
    +
    +typedef struct xmlwfUserData {
    +  FILE *fp;
    +  NotationList *notationListHead;
    +  const XML_Char *currentDoctypeName;
    +} XmlwfUserData;
    +
    +
     /* This ensures proper sorting. */
     
     #define NSSEP T('\001')
    @@ -28,7 +72,7 @@
     static void XMLCALL
     characterData(void *userData, const XML_Char *s, int len)
     {
    -  FILE *fp = (FILE *)userData;
    +  FILE *fp = ((XmlwfUserData *)userData)->fp;
       for (; len > 0; --len, ++s) {
         switch (*s) {
         case T('&'):
    @@ -66,6 +110,7 @@ attributeValue(FILE *fp, const XML_Char *s)
     {
       puttc(T('='), fp);
       puttc(T('"'), fp);
    +  assert(s);
       for (;;) {
         switch (*s) {
         case 0:
    @@ -123,7 +168,7 @@ startElement(void *userData, const XML_Char *name, const XML_Char **atts)
     {
       int nAtts;
       const XML_Char **p;
    -  FILE *fp = (FILE *)userData;
    +  FILE *fp = ((XmlwfUserData *)userData)->fp;
       puttc(T('<'), fp);
       fputts(name, fp);
     
    @@ -145,7 +190,7 @@ startElement(void *userData, const XML_Char *name, const XML_Char **atts)
     static void XMLCALL
     endElement(void *userData, const XML_Char *name)
     {
    -  FILE *fp = (FILE *)userData;
    +  FILE *fp = ((XmlwfUserData *)userData)->fp;
       puttc(T('<'), fp);
       puttc(T('/'), fp);
       fputts(name, fp);
    @@ -170,7 +215,7 @@ startElementNS(void *userData, const XML_Char *name, const XML_Char **atts)
       int nAtts;
       int nsi;
       const XML_Char **p;
    -  FILE *fp = (FILE *)userData;
    +  FILE *fp = ((XmlwfUserData *)userData)->fp;
       const XML_Char *sep;
       puttc(T('<'), fp);
     
    @@ -216,7 +261,7 @@ startElementNS(void *userData, const XML_Char *name, const XML_Char **atts)
     static void XMLCALL
     endElementNS(void *userData, const XML_Char *name)
     {
    -  FILE *fp = (FILE *)userData;
    +  FILE *fp = ((XmlwfUserData *)userData)->fp;
       const XML_Char *sep;
       puttc(T('<'), fp);
       puttc(T('/'), fp);
    @@ -236,7 +281,7 @@ static void XMLCALL
     processingInstruction(void *userData, const XML_Char *target,
                           const XML_Char *data)
     {
    -  FILE *fp = (FILE *)userData;
    +  FILE *fp = ((XmlwfUserData *)userData)->fp;
       puttc(T('<'), fp);
       puttc(T('?'), fp);
       fputts(target, fp);
    @@ -246,6 +291,200 @@ processingInstruction(void *userData, const XML_Char *target,
       puttc(T('>'), fp);
     }
     
    +
    +static XML_Char *xcsdup(const XML_Char *s)
    +{
    +  XML_Char *result;
    +  int count = 0;
    +  int numBytes;
    +
    +  /* Get the length of the string, including terminator */
    +  while (s[count++] != 0) {
    +    /* Do nothing */
    +  }
    +  numBytes = count * sizeof(XML_Char);
    +  result = malloc(numBytes);
    +  if (result == NULL)
    +    return NULL;
    +  memcpy(result, s, numBytes);
    +  return result;
    +}
    +
    +static void XMLCALL
    +startDoctypeDecl(void *userData,
    +                 const XML_Char *doctypeName,
    +                 const XML_Char *UNUSED_P(sysid),
    +                 const XML_Char *UNUSED_P(publid),
    +                 int UNUSED_P(has_internal_subset))
    +{
    +  XmlwfUserData *data = (XmlwfUserData *)userData;
    +  data->currentDoctypeName = xcsdup(doctypeName);
    +}
    +
    +static void
    +freeNotations(XmlwfUserData *data)
    +{
    +  NotationList *notationListHead = data->notationListHead;
    +
    +  while (notationListHead != NULL) {
    +    NotationList *next = notationListHead->next;
    +    free((void *)notationListHead->notationName);
    +    free((void *)notationListHead->systemId);
    +    free((void *)notationListHead->publicId);
    +    free(notationListHead);
    +    notationListHead = next;
    +  }
    +  data->notationListHead = NULL;
    +}
    +
    +static int xcscmp(const XML_Char *xs, const XML_Char *xt)
    +{
    +  while (*xs != 0 && *xt != 0) {
    +    if (*xs < *xt)
    +      return -1;
    +    if (*xs > *xt)
    +      return 1;
    +    xs++;
    +    xt++;
    +  }
    +  if (*xs < *xt)
    +    return -1;
    +  if (*xs > *xt)
    +    return 1;
    +  return 0;
    +}
    +
    +static int
    +notationCmp(const void *a, const void *b)
    +{
    +  const NotationList * const n1 = *(NotationList **)a;
    +  const NotationList * const n2 = *(NotationList **)b;
    +
    +  return xcscmp(n1->notationName, n2->notationName);
    +}
    +
    +static void XMLCALL
    +endDoctypeDecl(void *userData)
    +{
    +  XmlwfUserData *data = (XmlwfUserData *)userData;
    +  NotationList **notations;
    +  int notationCount = 0;
    +  NotationList *p;
    +  int i;
    +
    +  /* How many notations do we have? */
    +  for (p = data->notationListHead; p != NULL; p = p->next)
    +    notationCount++;
    +  if (notationCount == 0) {
    +    /* Nothing to report */
    +    free((void *)data->currentDoctypeName);
    +    data->currentDoctypeName = NULL;
    +    return;
    +  }
    +
    +  notations = malloc(notationCount * sizeof(NotationList *));
    +  if (notations == NULL) {
    +    fprintf(stderr, "Unable to sort notations");
    +    freeNotations(data);
    +    return;
    +  }
    +
    +  for (p = data->notationListHead, i = 0;
    +       i < notationCount;
    +       p = p->next, i++) {
    +    notations[i] = p;
    +  }
    +  qsort(notations, notationCount, sizeof(NotationList *), notationCmp);
    +
    +  /* Output the DOCTYPE header */
    +  fputts(T("fp);
    +  fputts(data->currentDoctypeName, data->fp);
    +  fputts(T(" [\n"), data->fp);
    +
    +  /* Now the NOTATIONs */
    +  for (i = 0; i < notationCount; i++) {
    +    fputts(T("fp);
    +    fputts(notations[i]->notationName, data->fp);
    +    if (notations[i]->publicId != NULL) {
    +      fputts(T(" PUBLIC '"), data->fp);
    +      fputts(notations[i]->publicId, data->fp);
    +      puttc(T('\''), data->fp);
    +      if (notations[i]->systemId != NULL) {
    +        puttc(T(' '), data->fp);
    +        puttc(T('\''), data->fp);
    +        fputts(notations[i]->systemId, data->fp);
    +        puttc(T('\''), data->fp);
    +      }
    +    }
    +    else if (notations[i]->systemId != NULL) {
    +      fputts(T(" SYSTEM '"), data->fp);
    +      fputts(notations[i]->systemId, data->fp);
    +      puttc(T('\''), data->fp);
    +    }
    +    puttc(T('>'), data->fp);
    +    puttc(T('\n'), data->fp);
    +  }
    +
    +  /* Finally end the DOCTYPE */
    +  fputts(T("]>\n"), data->fp);
    +
    +  free(notations);
    +  freeNotations(data);
    +  free((void *)data->currentDoctypeName);
    +  data->currentDoctypeName = NULL;
    +}
    +
    +static void XMLCALL
    +notationDecl(void *userData,
    +             const XML_Char *notationName,
    +             const XML_Char *UNUSED_P(base),
    +             const XML_Char *systemId,
    +             const XML_Char *publicId)
    +{
    +  XmlwfUserData *data = (XmlwfUserData *)userData;
    +  NotationList *entry = malloc(sizeof(NotationList));
    +  const char *errorMessage = "Unable to store NOTATION for output\n";
    +
    +  if (entry == NULL) {
    +    fputs(errorMessage, stderr);
    +    return; /* Nothing we can really do about this */
    +  }
    +  entry->notationName = xcsdup(notationName);
    +  if (entry->notationName == NULL) {
    +    fputs(errorMessage, stderr);
    +    free(entry);
    +    return;
    +  }
    +  if (systemId != NULL) {
    +    entry->systemId = xcsdup(systemId);
    +    if (entry->systemId == NULL) {
    +      fputs(errorMessage, stderr);
    +      free((void *)entry->notationName);
    +      free(entry);
    +      return;
    +    }
    +  }
    +  else {
    +    entry->systemId = NULL;
    +  }
    +  if (publicId != NULL) {
    +    entry->publicId = xcsdup(publicId);
    +    if (entry->publicId == NULL) {
    +      fputs(errorMessage, stderr);
    +      free((void *)entry->systemId); /* Safe if it's NULL */
    +      free((void *)entry->notationName);
    +      free(entry);
    +      return;
    +    }
    +  }
    +  else {
    +    entry->publicId = NULL;
    +  }
    +
    +  entry->next = data->notationListHead;
    +  data->notationListHead = entry;
    +}
    +
     #endif /* not W3C14N */
     
     static void XMLCALL
    @@ -298,7 +537,7 @@ nopProcessingInstruction(void *UNUSED_P(userData), const XML_Char *UNUSED_P(targ
     static void XMLCALL
     markup(void *userData, const XML_Char *s, int len)
     {
    -  FILE *fp = (FILE *)XML_GetUserData((XML_Parser) userData);
    +  FILE *fp = ((XmlwfUserData *)XML_GetUserData((XML_Parser) userData))->fp;
       for (; len > 0; --len, ++s)
         puttc(*s, fp);
     }
    @@ -307,11 +546,14 @@ static void
     metaLocation(XML_Parser parser)
     {
       const XML_Char *uri = XML_GetBase(parser);
    +  FILE *fp = ((XmlwfUserData *)XML_GetUserData(parser))->fp;
       if (uri)
    -    ftprintf((FILE *)XML_GetUserData(parser), T(" uri=\"%s\""), uri);
    -  ftprintf((FILE *)XML_GetUserData(parser),
    -           T(" byte=\"%" XML_FMT_INT_MOD "d\" nbytes=\"%d\" \
    -			 line=\"%" XML_FMT_INT_MOD "u\" col=\"%" XML_FMT_INT_MOD "u\""),
    +    ftprintf(fp, T(" uri=\"%s\""), uri);
    +  ftprintf(fp,
    +           T(" byte=\"%") T(XML_FMT_INT_MOD) T("d\"")
    +             T(" nbytes=\"%d\"")
    +             T(" line=\"%") T(XML_FMT_INT_MOD) T("u\"")
    +             T(" col=\"%") T(XML_FMT_INT_MOD) T("u\""),
                XML_GetCurrentByteIndex(parser),
                XML_GetCurrentByteCount(parser),
                XML_GetCurrentLineNumber(parser),
    @@ -321,13 +563,15 @@ metaLocation(XML_Parser parser)
     static void
     metaStartDocument(void *userData)
     {
    -  fputts(T("\n"), (FILE *)XML_GetUserData((XML_Parser) userData));
    +  fputts(T("\n"),
    +         ((XmlwfUserData *)XML_GetUserData((XML_Parser) userData))->fp);
     }
     
     static void
     metaEndDocument(void *userData)
     {
    -  fputts(T("\n"), (FILE *)XML_GetUserData((XML_Parser) userData));
    +  fputts(T("\n"),
    +         ((XmlwfUserData *)XML_GetUserData((XML_Parser) userData))->fp);
     }
     
     static void XMLCALL
    @@ -335,7 +579,8 @@ metaStartElement(void *userData, const XML_Char *name,
                      const XML_Char **atts)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       const XML_Char **specifiedAttsEnd
         = atts + XML_GetSpecifiedAttributeCount(parser);
       const XML_Char **idAttPtr;
    @@ -344,14 +589,14 @@ metaStartElement(void *userData, const XML_Char *name,
         idAttPtr = 0;
       else
         idAttPtr = atts + idAttIndex;
    -    
    +
       ftprintf(fp, T("\n"), fp);
         do {
           ftprintf(fp, T("= specifiedAttsEnd)
             fputts(T("\" defaulted=\"yes\"/>\n"), fp);
           else if (atts == idAttPtr)
    @@ -369,7 +614,8 @@ static void XMLCALL
     metaEndElement(void *userData, const XML_Char *name)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       ftprintf(fp, T("\n"), fp);
    @@ -380,9 +626,10 @@ metaProcessingInstruction(void *userData, const XML_Char *target,
                               const XML_Char *data)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *usrData = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = usrData->fp;
       ftprintf(fp, T("\n"), fp);
    @@ -392,9 +639,10 @@ static void XMLCALL
     metaComment(void *userData, const XML_Char *data)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *usrData = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = usrData->fp;
       fputts(T("\n"), fp);
    @@ -404,7 +652,8 @@ static void XMLCALL
     metaStartCdataSection(void *userData)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       fputts(T("\n"), fp);
    @@ -414,7 +663,8 @@ static void XMLCALL
     metaEndCdataSection(void *userData)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       fputts(T("\n"), fp);
    @@ -424,9 +674,10 @@ static void XMLCALL
     metaCharacterData(void *userData, const XML_Char *s, int len)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       fputts(T("\n"), fp);
    @@ -440,7 +691,8 @@ metaStartDoctypeDecl(void *userData,
                          int UNUSED_P(has_internal_subset))
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       ftprintf(fp, T("\n"), fp);
    @@ -450,7 +702,8 @@ static void XMLCALL
     metaEndDoctypeDecl(void *userData)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       fputts(T("\n"), fp);
    @@ -464,13 +717,14 @@ metaNotationDecl(void *userData,
                      const XML_Char *publicId)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       ftprintf(fp, T("fp;
     
       if (value) {
         ftprintf(fp, T("'), fp);
    -    characterData(fp, value, value_length);
    +    characterData(data, value, value_length);
         fputts(T("\n"), fp);
       }
       else if (notationName) {
    @@ -504,7 +759,7 @@ metaEntityDecl(void *userData,
         if (publicId)
           ftprintf(fp, T(" public=\"%s\""), publicId);
         fputts(T(" system=\""), fp);
    -    characterData(fp, systemId, (int)tcslen(systemId));
    +    characterData(data, systemId, (int)tcslen(systemId));
         puttc(T('"'), fp);
         ftprintf(fp, T(" notation=\"%s\""), notationName);
         metaLocation(parser);
    @@ -515,7 +770,7 @@ metaEntityDecl(void *userData,
         if (publicId)
           ftprintf(fp, T(" public=\"%s\""), publicId);
         fputts(T(" system=\""), fp);
    -    characterData(fp, systemId, (int)tcslen(systemId));
    +    characterData(data, systemId, (int)tcslen(systemId));
         puttc(T('"'), fp);
         metaLocation(parser);
         fputts(T("/>\n"), fp);
    @@ -528,13 +783,14 @@ metaStartNamespaceDecl(void *userData,
                            const XML_Char *uri)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       fputts(T("\n"), fp);
       }
       else
    @@ -545,7 +801,8 @@ static void XMLCALL
     metaEndNamespaceDecl(void *userData, const XML_Char *prefix)
     {
       XML_Parser parser = (XML_Parser) userData;
    -  FILE *fp = (FILE *)XML_GetUserData(parser);
    +  XmlwfUserData *data = (XmlwfUserData *)XML_GetUserData(parser);
    +  FILE *fp = data->fp;
       if (!prefix)
         fputts(T("\n"), fp);
       else
    @@ -608,7 +865,7 @@ showVersion(XML_Char *prog)
       const XML_Feature *features = XML_GetFeatureList();
       while ((ch = *s) != 0) {
         if (ch == '/'
    -#if (defined(WIN32) || defined(__WATCOMC__))
    +#if defined(_WIN32)
             || ch == '\\'
     #endif
             )
    @@ -635,10 +892,15 @@ static void
     usage(const XML_Char *prog, int rc)
     {
       ftprintf(stderr,
    -           T("usage: %s [-s] [-n] [-p] [-x] [-e encoding] [-w] [-d output-dir] [-c] [-m] [-r] [-t] [file ...]\n"), prog);
    +           T("usage: %s [-s] [-n] [-p] [-x] [-e encoding] [-w] [-d output-dir] [-c] [-m] [-r] [-t] [-N] [file ...]\n"), prog);
       exit(rc);
     }
     
    +#if defined(__MINGW32__) && defined(XML_UNICODE)
    +/* Silence warning about missing prototype */
    +int wmain(int argc, XML_Char **argv);
    +#endif
    +
     int
     tmain(int argc, XML_Char **argv)
     {
    @@ -650,9 +912,11 @@ tmain(int argc, XML_Char **argv)
       int outputType = 0;
       int useNamespaces = 0;
       int requireStandalone = 0;
    +  int requiresNotations = 0;
       enum XML_ParamEntityParsing paramEntityParsing = 
         XML_PARAM_ENTITY_PARSING_NEVER;
       int useStdin = 0;
    +  XmlwfUserData userData = { NULL, NULL, NULL };
     
     #ifdef _MSC_VER
       _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
    @@ -707,6 +971,10 @@ tmain(int argc, XML_Char **argv)
           outputType = 't';
           j++;
           break;
    +    case T('N'):
    +      requiresNotations = 1;
    +      j++;
    +      break;
         case T('d'):
           if (argv[i][j + 1] == T('\0')) {
             if (++i == argc)
    @@ -752,7 +1020,6 @@ tmain(int argc, XML_Char **argv)
         i--;
       }
       for (; i < argc; i++) {
    -    FILE *fp = 0;
         XML_Char *outName = 0;
         int result;
         XML_Parser parser;
    @@ -762,7 +1029,7 @@ tmain(int argc, XML_Char **argv)
           parser = XML_ParserCreate(encoding);
     
         if (! parser) {
    -      tperror("Could not instantiate parser");
    +      tperror(T("Could not instantiate parser"));
           exit(1);
         }
     
    @@ -785,7 +1052,7 @@ tmain(int argc, XML_Char **argv)
             const XML_Char * lastDelim = tcsrchr(file, delim[0]);
             if (lastDelim)
               file = lastDelim + 1;
    -#if (defined(WIN32) || defined(__WATCOMC__))
    +#if defined(_WIN32)
             else {
               const XML_Char * winDelim = T("\\");
               lastDelim = tcsrchr(file, winDelim[0]);
    @@ -801,16 +1068,16 @@ tmain(int argc, XML_Char **argv)
           tcscpy(outName, outputDir);
           tcscat(outName, delim);
           tcscat(outName, file);
    -      fp = tfopen(outName, T("wb"));
    -      if (!fp) {
    +      userData.fp = tfopen(outName, T("wb"));
    +      if (!userData.fp) {
             tperror(outName);
             exit(1);
           }
    -      setvbuf(fp, NULL, _IOFBF, 16384);
    +      setvbuf(userData.fp, NULL, _IOFBF, 16384);
     #ifdef XML_UNICODE
    -      puttc(0xFEFF, fp);
    +      puttc(0xFEFF, userData.fp);
     #endif
    -      XML_SetUserData(parser, fp);
    +      XML_SetUserData(parser, &userData);
           switch (outputType) {
           case 'm':
             XML_UseParserAsHandlerArg(parser);
    @@ -844,6 +1111,10 @@ tmain(int argc, XML_Char **argv)
             XML_SetCharacterDataHandler(parser, characterData);
     #ifndef W3C14N
             XML_SetProcessingInstructionHandler(parser, processingInstruction);
    +        if (requiresNotations) {
    +          XML_SetDoctypeDeclHandler(parser, startDoctypeDecl, endDoctypeDecl);
    +          XML_SetNotationDeclHandler(parser, notationDecl);
    +        }
     #endif /* not W3C14N */
             break;
           }
    @@ -854,7 +1125,7 @@ tmain(int argc, XML_Char **argv)
         if (outputDir) {
           if (outputType == 'm')
             metaEndDocument(parser);
    -      fclose(fp);
    +      fclose(userData.fp);
           if (!result) {
             tremove(outName);
             exit(2);
    diff --git a/contrib/expat/xmlwf/xmlwin32url.cxx b/contrib/expat/xmlwf/xmlwin32url.cxx
    index bbfcce22c964..ef2a137452e7 100644
    --- a/contrib/expat/xmlwf/xmlwin32url.cxx
    +++ b/contrib/expat/xmlwf/xmlwin32url.cxx
    @@ -1,3 +1,35 @@
    +/*
    +                            __  __            _
    +                         ___\ \/ /_ __   __ _| |_
    +                        / _ \\  /| '_ \ / _` | __|
    +                       |  __//  \| |_) | (_| | |_
    +                        \___/_/\_\ .__/ \__,_|\__|
    +                                 |_| XML parser
    +
    +   Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
    +   Copyright (c) 2000-2017 Expat development team
    +   Licensed under the MIT license:
    +
    +   Permission is  hereby granted,  free of charge,  to any  person obtaining
    +   a  copy  of  this  software   and  associated  documentation  files  (the
    +   "Software"),  to  deal in  the  Software  without restriction,  including
    +   without  limitation the  rights  to use,  copy,  modify, merge,  publish,
    +   distribute, sublicense, and/or sell copies of the Software, and to permit
    +   persons  to whom  the Software  is  furnished to  do so,  subject to  the
    +   following conditions:
    +
    +   The above copyright  notice and this permission notice  shall be included
    +   in all copies or substantial portions of the Software.
    +
    +   THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
    +   EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
    +   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
    +   NO EVENT SHALL THE AUTHORS OR  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    +   DAMAGES OR  OTHER LIABILITY, WHETHER  IN AN  ACTION OF CONTRACT,  TORT OR
    +   OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
    +   USE OR OTHER DEALINGS IN THE SOFTWARE.
    +*/
    +
     #include "expat.h"
     #ifdef XML_UNICODE
     #define UNICODE
    diff --git a/contrib/jemalloc/src/pages.c b/contrib/jemalloc/src/pages.c
    index 96836f75cb4c..69a6c599c043 100644
    --- a/contrib/jemalloc/src/pages.c
    +++ b/contrib/jemalloc/src/pages.c
    @@ -186,6 +186,10 @@ pages_map(void *addr, size_t size, size_t alignment, bool *commit) {
     	 * touching existing mappings, and to mmap with specific alignment.
     	 */
     	{
    +		if (os_overcommits) {
    +			*commit = true;
    +		}
    +
     		int prot = *commit ? PAGES_PROT_COMMIT : PAGES_PROT_DECOMMIT;
     		int flags = mmap_flags;
     
    diff --git a/lib/Makefile b/lib/Makefile
    index 4332aa13a70c..58c3753ec8e5 100644
    --- a/lib/Makefile
    +++ b/lib/Makefile
    @@ -70,8 +70,6 @@ SUBDIR=	${SUBDIR_BOOTSTRAP} \
     	libpathconv \
     	libpcap \
     	libpjdlog \
    -	libpmc \
    -	libpmcstat \
     	${_libproc} \
     	libprocstat \
     	libregex \
    @@ -200,6 +198,7 @@ _libdl=		libdl
     .endif
     
     SUBDIR.${MK_OPENSSL}+=	libmp
    +SUBDIR.${MK_PMC}+=	libpmc libpmcstat
     SUBDIR.${MK_RADIUS_SUPPORT}+=	libradius
     SUBDIR.${MK_SENDMAIL}+=	libmilter libsm libsmdb libsmutil
     SUBDIR.${MK_TELNET}+=	libtelnet
    diff --git a/lib/libc/locale/collate.c b/lib/libc/locale/collate.c
    index 5017433a9d98..15ce3b2f52e8 100644
    --- a/lib/libc/locale/collate.c
    +++ b/lib/libc/locale/collate.c
    @@ -84,7 +84,8 @@ destruct_collate(void *t)
     void *
     __collate_load(const char *encoding, __unused locale_t unused)
     {
    -	if (strcmp(encoding, "C") == 0 || strcmp(encoding, "POSIX") == 0) {
    +	if (strcmp(encoding, "C") == 0 || strcmp(encoding, "POSIX") == 0 ||
    +	    strncmp(encoding, "C.", 2) == 0) {
     		return &__xlocale_C_collate;
     	}
     	struct xlocale_collate *table = calloc(sizeof(struct xlocale_collate), 1);
    @@ -122,7 +123,8 @@ __collate_load_tables_l(const char *encoding, struct xlocale_collate *table)
     	table->__collate_load_error = 1;
     
     	/* 'encoding' must be already checked. */
    -	if (strcmp(encoding, "C") == 0 || strcmp(encoding, "POSIX") == 0) {
    +	if (strcmp(encoding, "C") == 0 || strcmp(encoding, "POSIX") == 0 ||
    +	    strncmp(encoding, "C.", 2) == 0) {
     		return (_LDP_CACHE);
     	}
     
    diff --git a/lib/libc/locale/ldpart.c b/lib/libc/locale/ldpart.c
    index ed794337e115..889291cf3168 100644
    --- a/lib/libc/locale/ldpart.c
    +++ b/lib/libc/locale/ldpart.c
    @@ -63,7 +63,8 @@ __part_load_locale(const char *name,
     	size_t		namesize, bufsize;
     
     	/* 'name' must be already checked. */
    -	if (strcmp(name, "C") == 0 || strcmp(name, "POSIX") == 0) {
    +	if (strcmp(name, "C") == 0 || strcmp(name, "POSIX") == 0 ||
    +	    strncmp(name, "C.", 2) == 0) {
     		*using_locale = 0;
     		return (_LDP_CACHE);
     	}
    diff --git a/lib/libcapsicum/Makefile b/lib/libcapsicum/Makefile
    index 85a0a56c2ba2..1adf57666f7e 100644
    --- a/lib/libcapsicum/Makefile
    +++ b/lib/libcapsicum/Makefile
    @@ -8,6 +8,7 @@ MAN+=	capsicum_helpers.3
     
     MLINKS+=capsicum_helpers.3 caph_enter.3
     MLINKS+=capsicum_helpers.3 caph_enter_casper.3
    +MLINKS+=capsicum_helpers.3 caph_rights_limit.3
     MLINKS+=capsicum_helpers.3 caph_limit_stream.3
     MLINKS+=capsicum_helpers.3 caph_limit_stdin.3
     MLINKS+=capsicum_helpers.3 caph_limit_stderr.3
    diff --git a/lib/libcapsicum/capsicum_helpers.3 b/lib/libcapsicum/capsicum_helpers.3
    index c22a201d8f43..8d4b875bf94c 100644
    --- a/lib/libcapsicum/capsicum_helpers.3
    +++ b/lib/libcapsicum/capsicum_helpers.3
    @@ -24,7 +24,7 @@
     .\"
     .\" $FreeBSD$
     .\"
    -.Dd July 18, 2018
    +.Dd November 4, 2018
     .Dt CAPSICUM_HELPERS 3
     .Os
     .Sh NAME
    @@ -34,7 +34,12 @@
     .Nm caph_limit_stdout ,
     .Nm caph_limit_stdio ,
     .Nm caph_cache_tzdata ,
    -.Nm caph_cache_catpages
    +.Nm caph_cache_catpages ,
    +.Nm caph_enter ,
    +.Nm caph_enter_casper ,
    +.Nm caph_rights_limit ,
    +.Nm caph_ioctls_limit ,
    +.Nm caph_fcntls_limit
     .Nd "set of the capsicum helpers, part of the libcapsicum"
     .Sh LIBRARY
     .Lb libcapsicum
    @@ -45,7 +50,11 @@
     .Ft int
     .Fn caph_enter_casper "void"
     .Ft int
    -.Fn caph_limit_stream "int fd" "int flags"
    +.Fn caph_rights_limit "inf fd" "const cap_righst_t *rights"
    +.Ft int
    +.Fn caph_ioctls_limit "inf fd" "const unsigned long *cmds" "size_t ncmds"
    +.Ft int
    +.Fn caph_fcntls_limit "inf fd" "uint32_t fcntlrights"
     .Ft int
     .Fn caph_limit_stdin "void"
     .Ft int
    @@ -60,9 +69,17 @@
     .Fn caph_cache_catpages "void"
     .Sh DESCRIPTION
     The
    -.Nm caph_enter
    -is equivalent to the
    -.Xr cap_enter 2
    +.Nm caph_enter ,
    +.Nm caph_rights_limit ,
    +.Nm caph_ioctls_limit
    +and
    +.Nm caph_fcntls_limit
    +are respectively equivalent to
    +.Xr cap_enter 2 ,
    +.Xr cap_rights_limit 2 ,
    +.Xr cap_ioctls_limit 2
    +and
    +.Xr cap_fcntls_limit 2 ,
     it returns success when the kernel is built without support of the capability
     mode.
     .Pp
    @@ -125,4 +142,5 @@ among others.
     .Ed
     .Sh SEE ALSO
     .Xr cap_enter 2 ,
    +.Xr cap_rights_limit 2 ,
     .Xr rights 4
    diff --git a/lib/libcapsicum/capsicum_helpers.h b/lib/libcapsicum/capsicum_helpers.h
    index 60c894f35a6e..d1c46e74f388 100644
    --- a/lib/libcapsicum/capsicum_helpers.h
    +++ b/lib/libcapsicum/capsicum_helpers.h
    @@ -136,6 +136,35 @@ caph_enter(void)
     	return (0);
     }
     
    +static __inline int
    +caph_rights_limit(int fd, const cap_rights_t *rights)
    +{
    +
    +	if (cap_rights_limit(fd, rights) < 0 && errno != ENOSYS)
    +		return (-1);
    +
    +	return (0);
    +}
    +
    +static __inline int
    +caph_ioctls_limit(int fd, const unsigned long *cmds, size_t ncmds)
    +{
    +
    +	if (cap_ioctls_limit(fd, cmds, ncmds) < 0 && errno != ENOSYS)
    +		return (-1);
    +
    +	return (0);
    +}
    +
    +static __inline int
    +caph_fcntls_limit(int fd, uint32_t fcntlrights)
    +{
    +
    +	if (cap_fcntls_limit(fd, fcntlrights) < 0 && errno != ENOSYS)
    +		return (-1);
    +
    +	return (0);
    +}
     
     static __inline int
     caph_enter_casper(void)
    diff --git a/lib/libcasper/libcasper/libcasper.3 b/lib/libcasper/libcasper/libcasper.3
    index 95a6e21014f4..d1804b8ab25a 100644
    --- a/lib/libcasper/libcasper/libcasper.3
    +++ b/lib/libcasper/libcasper/libcasper.3
    @@ -28,7 +28,7 @@
     .\"
     .\" $FreeBSD$
     .\"
    -.Dd March 6, 2018
    +.Dd November 5, 2018
     .Dt LIBCASPER 3
     .Os
     .Sh NAME
    @@ -161,9 +161,11 @@ it means there are no limits set.
     The
     .Fn cap_limit_set
     function sets limits for the given capability.
    -The limits are provided as
    +The limits are provided as a
     .Xr nvlist 9 .
     The exact format depends on the service the capability represents.
    +.Fn cap_limit_set
    +frees the limits regardless of whether the operation succeeds or fails.
     .Pp
     The
     .Fn cap_send_nvlist
    diff --git a/lib/libcasper/services/cap_dns/Makefile b/lib/libcasper/services/cap_dns/Makefile
    index eebe1d000c9c..cec3bb180a6a 100644
    --- a/lib/libcasper/services/cap_dns/Makefile
    +++ b/lib/libcasper/services/cap_dns/Makefile
    @@ -30,6 +30,7 @@ MLINKS+=cap_dns.3 libcap_dns.3
     MLINKS+=cap_dns.3 cap_gethostbyname.3
     MLINKS+=cap_dns.3 cap_gethostbyname2.3
     MLINKS+=cap_dns.3 cap_gethostbyaddr.3
    +MLINKS+=cap_dns.3 cap_getaddrinfo.3
     MLINKS+=cap_dns.3 cap_getnameinfo.3
     MLINKS+=cap_dns.3 cap_dns_type_limit.3
     MLINKS+=cap_dns.3 cap_dns_family_limit.3
    diff --git a/lib/libcasper/services/cap_dns/cap_dns.3 b/lib/libcasper/services/cap_dns/cap_dns.3
    index da0e511cdca4..bc38e6bf3dd8 100644
    --- a/lib/libcasper/services/cap_dns/cap_dns.3
    +++ b/lib/libcasper/services/cap_dns/cap_dns.3
    @@ -24,14 +24,15 @@
     .\"
     .\" $FreeBSD$
     .\"
    -.Dd March 18, 2018
    +.Dd November 4, 2018
     .Dt CAP_DNS 3
     .Os
     .Sh NAME
    +.Nm cap_getaddrinfo ,
    +.Nm cap_getnameinfo ,
     .Nm cap_gethostbyname ,
     .Nm cap_gethostbyname2 ,
     .Nm cap_gethostbyaddr ,
    -.Nm cap_getnameinfo ,
     .Nm cap_dns_type_limit ,
     .Nm cap_dns_family_limit
     .Nd "library for getting network host entry in capability mode"
    @@ -41,6 +42,10 @@
     .In sys/nv.h
     .In libcasper.h
     .In casper/cap_dns.h
    +.Ft int
    +.Fn cap_getaddrinfo "cap_channel_t *chan" "const char *hostname" "const char *servname" "const struct addrinfo *hints" "struct addrinfo **res"
    +.Ft int
    +.Fn cap_getnameinfo "cap_channel_t *chan" "const struct sockaddr *sa" "socklen_t salen" "char *host" "size_t hostlen" "char *serv" "size_t servlen" "int flags"
     .Ft "struct hostent *"
     .Fn cap_gethostbyname "const cap_channel_t *chan" "const char *name"
     .Ft "struct hostent *"
    @@ -48,12 +53,23 @@
     .Ft "struct hostent *"
     .Fn cap_gethostbyaddr "const cap_channel_t *chan" "const void *addr" "socklen_t len" "int af"
     .Ft "int"
    -.Fn cap_getnameinfo "const cap_channel_t *chan" "const void *name" "int namelen"
    -.Ft "int"
     .Fn cap_dns_type_limit "cap_channel_t *chan" "const char * const *types" "size_t ntypes"
     .Ft "int"
     .Fn cap_dns_family_limit "const cap_channel_t *chan" "const int *families" "size_t nfamilies"
     .Sh DESCRIPTION
    +.Bf -symbolic
    +The
    +.Fn cap_getaddrinfo ,
    +and
    +.Fn cap_getnameinfo ,
    +functions are preferred over the
    +.Fn cap_gethostbyname ,
    +.Fn cap_gethostbyname2 ,
    +and
    +.Fn cap_gethostbyaddr
    +functions.
    +.Ef
    +.Pp
     The functions
     .Fn cap_gethostbyname ,
     .Fn cap_gethostbyname2 ,
    @@ -118,19 +134,21 @@ or
     .Dv NAME .
     The
     .Dv ADDR
    -means that functions
    -.Fn cap_gethostbyname ,
    -.Fn cap_gethostbyname2
    +means that reverse DNS lookups are allowed with
    +.Fn cap_getnameinfo
     and
     .Fn cap_gethostbyaddr
    -are allowed.
    +functions.
     In case when
     .Va type
     is set to
     .Dv NAME
    -the
    -.Fn cap_getnameinfo
    -function is allowed.
    +the name resolution is allowed with
    +.Fn cap_getaddrinfo ,
    +.Fn cap_gethostbyname ,
    +and
    +.Fn cap_gethostbyname2
    +functions.
     .It family ( NV_TYPE_NUMBER )
     The
     .Va family
    @@ -144,19 +162,22 @@ capability to create the
     casper service and uses it to resolve an IP address.
     .Bd -literal
     cap_channel_t *capcas, *capdns;
    -const char *typelimit = "ADDR";
    -int familylimit;
    +int familylimit, error;
     const char *ipstr = "127.0.0.1";
    -struct in_addr ip;
    -struct hostent *hp;
    +const char *typelimit = "ADDR";
    +char hname[NI_MAXHOST];
    +struct addrinfo hints, *res;
     
     /* Open capability to Casper. */
     capcas = cap_init();
     if (capcas == NULL)
     	err(1, "Unable to contact Casper");
     
    +/* Cache NLA for gai_strerror. */
    +caph_cache_catpages();
    +
     /* Enter capability mode sandbox. */
    -if (cap_enter() < 0 && errno != ENOSYS)
    +if (caph_enter() < 0)
     	err(1, "Unable to enter capability mode");
     
     /* Use Casper capability to create capability to the system.dns service. */
    @@ -167,28 +188,34 @@ if (capdns == NULL)
     /* Close Casper capability, we don't need it anymore. */
     cap_close(capcas);
     
    -/* Limit system.dns to reverse DNS lookups. */
    -if (cap_dns_type_limit(capdns, &typelimit, 1) < 0)
    -	err(1, "Unable to limit access to the system.dns service");
    -
     /* Limit system.dns to reserve IPv4 addresses */
     familylimit = AF_INET;
     if (cap_dns_family_limit(capdns, &familylimit, 1) < 0)
     	err(1, "Unable to limit access to the system.dns service");
     
    -/* Convert IP address in C-string to in_addr. */
    -if (!inet_aton(ipstr, &ip))
    -	errx(1, "Unable to parse IP address %s.", ipstr);
    +/* Convert IP address in C-string to struct sockaddr. */
    +memset(&hints, 0, sizeof(hints));
    +hints.ai_family = familylimit;
    +hints.ai_flags = AI_NUMERICHOST;
    +error = cap_getaddrinfo(capdns, ipstr, NULL, &hints, &res);
    +if (error != 0)
    +       errx(1, "cap_getaddrinfo(): %s: %s", ipstr, gai_strerror(error));
    +
    +/* Limit system.dns to reverse DNS lookups. */
    +if (cap_dns_type_limit(capdns, &typelimit, 1) < 0)
    +	err(1, "Unable to limit access to the system.dns service");
     
     /* Find hostname for the given IP address. */
    -hp = cap_gethostbyaddr(capdns, (const void *)&ip, sizeof(ip), AF_INET);
    -if (hp == NULL)
    -	errx(1, "No name associated with %s.", ipstr);
    +error = cap_getnameinfo(capdns, res->ai_addr, res->ai_addrlen, hname, sizeof(hname),
    +    NULL, 0, 0);
    +if (error != 0)
    +	errx(1, "cap_getnameinfo(): %s: %s", ipstr, gai_strerror(error));
     
    -printf("Name associated with %s is %s.\\n", ipstr, hp->h_name);
    +printf("Name associated with %s is %s.\\n", ipstr, hname);
     .Ed
     .Sh SEE ALSO
     .Xr cap_enter 2 ,
    +.Xr caph_enter 3 ,
     .Xr err 3 ,
     .Xr gethostbyaddr 3 ,
     .Xr gethostbyname 3 ,
    diff --git a/lib/libcasper/services/cap_dns/cap_dns.c b/lib/libcasper/services/cap_dns/cap_dns.c
    index 6f8de34713d8..319abb35f4ee 100644
    --- a/lib/libcasper/services/cap_dns/cap_dns.c
    +++ b/lib/libcasper/services/cap_dns/cap_dns.c
    @@ -524,7 +524,7 @@ dns_getnameinfo(const nvlist_t *limits, const nvlist_t *nvlin, nvlist_t *nvlout)
     	socklen_t salen;
     	int error, flags;
     
    -	if (!dns_allowed_type(limits, "NAME"))
    +	if (!dns_allowed_type(limits, "ADDR"))
     		return (NO_RECOVERY);
     
     	error = 0;
    @@ -617,7 +617,7 @@ dns_getaddrinfo(const nvlist_t *limits, const nvlist_t *nvlin, nvlist_t *nvlout)
     	unsigned int ii;
     	int error, family, n;
     
    -	if (!dns_allowed_type(limits, "ADDR"))
    +	if (!dns_allowed_type(limits, "NAME"))
     		return (NO_RECOVERY);
     
     	hostname = dnvlist_get_string(nvlin, "hostname", NULL);
    diff --git a/lib/libcasper/services/cap_dns/tests/dns_test.c b/lib/libcasper/services/cap_dns/tests/dns_test.c
    index ce99b54f2942..f95209b3320e 100644
    --- a/lib/libcasper/services/cap_dns/tests/dns_test.c
    +++ b/lib/libcasper/services/cap_dns/tests/dns_test.c
    @@ -393,7 +393,8 @@ main(void)
     	CHECK(cap_dns_family_limit(capdns, families, 2) == 0);
     
     	CHECK(runtest(capdns) ==
    -	    (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET | GETHOSTBYNAME2_AF_INET6));
    +	    (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET | GETHOSTBYNAME2_AF_INET6 |
    +	    GETADDRINFO_AF_INET | GETADDRINFO_AF_INET6));
     
     	cap_close(capdns);
     
    @@ -419,9 +420,7 @@ main(void)
     	CHECK(cap_dns_family_limit(capdns, families, 2) == 0);
     
     	CHECK(runtest(capdns) ==
    -	    (GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6 |
    -	    GETADDRINFO_AF_INET | GETADDRINFO_AF_INET6));
    -
    +	    (GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6));
     	cap_close(capdns);
     
     	/*
    @@ -512,7 +511,8 @@ main(void)
     	CHECK(cap_dns_family_limit(capdns, families, 1) == -1 &&
     	    errno == ENOTCAPABLE);
     
    -	CHECK(runtest(capdns) == (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET));
    +	CHECK(runtest(capdns) ==
    +	    (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET | GETADDRINFO_AF_INET));
     
     	cap_close(capdns);
     
    @@ -548,7 +548,8 @@ main(void)
     	CHECK(cap_dns_family_limit(capdns, families, 1) == -1 &&
     	    errno == ENOTCAPABLE);
     
    -	CHECK(runtest(capdns) == GETHOSTBYNAME2_AF_INET6);
    +	CHECK(runtest(capdns) ==
    +	    (GETHOSTBYNAME2_AF_INET6 | GETADDRINFO_AF_INET6));
     
     	cap_close(capdns);
     
    @@ -584,7 +585,7 @@ main(void)
     	CHECK(cap_dns_family_limit(capdns, families, 1) == -1 &&
     	    errno == ENOTCAPABLE);
     
    -	CHECK(runtest(capdns) == (GETHOSTBYADDR_AF_INET | GETADDRINFO_AF_INET));
    +	CHECK(runtest(capdns) == GETHOSTBYADDR_AF_INET);
     
     	cap_close(capdns);
     
    @@ -620,8 +621,7 @@ main(void)
     	CHECK(cap_dns_family_limit(capdns, families, 1) == -1 &&
     	    errno == ENOTCAPABLE);
     
    -	CHECK(runtest(capdns) == (GETHOSTBYADDR_AF_INET6 |
    -	    GETADDRINFO_AF_INET6));
    +	CHECK(runtest(capdns) == GETHOSTBYADDR_AF_INET6);
     
     	cap_close(capdns);
     
    @@ -657,7 +657,8 @@ main(void)
     	    errno == ENOTCAPABLE);
     
     	/* Do the limits still hold? */
    -	CHECK(runtest(capdns) == (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET));
    +	CHECK(runtest(capdns) == (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET |
    +	    GETADDRINFO_AF_INET));
     
     	cap_close(capdns);
     
    @@ -691,8 +692,7 @@ main(void)
     	    errno == ENOTCAPABLE);
     
     	/* Do the limits still hold? */
    -	CHECK(runtest(capdns) == (GETHOSTBYADDR_AF_INET6 |
    -	    GETADDRINFO_AF_INET6));
    +	CHECK(runtest(capdns) == GETHOSTBYADDR_AF_INET6);
     
     	cap_close(capdns);
     
    diff --git a/lib/libcasper/services/cap_grp/cap_grp.c b/lib/libcasper/services/cap_grp/cap_grp.c
    index 4347f4fbc942..7134b0cd8432 100644
    --- a/lib/libcasper/services/cap_grp/cap_grp.c
    +++ b/lib/libcasper/services/cap_grp/cap_grp.c
    @@ -157,7 +157,7 @@ group_unpack(const nvlist_t *nvl, struct group *grp, char *buffer,
     	if (!nvlist_exists_string(nvl, "gr_name"))
     		return (EINVAL);
     
    -	memset(grp, 0, sizeof(*grp));
    +	explicit_bzero(grp, sizeof(*grp));
     
     	error = group_unpack_string(nvl, "gr_name", &grp->gr_name, &buffer,
     	    &bufsize);
    diff --git a/lib/libexpat/expat_config.h b/lib/libexpat/expat_config.h
    index 6deefc419f46..d335df9f776d 100644
    --- a/lib/libexpat/expat_config.h
    +++ b/lib/libexpat/expat_config.h
    @@ -1,5 +1,8 @@
     /* $FreeBSD$ */
     
    +/* expat_config.h.  Generated from expat_config.h.in by configure.  */
    +/* expat_config.h.in.  Generated from configure.ac by autoheader.  */
    +
     #include 
     
     /* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */
    @@ -9,6 +12,12 @@
     #define BYTEORDER 4321
     #endif
     
    +/* Define to 1 if you have the `arc4random' function. */
    +#define HAVE_ARC4RANDOM 1
    +
    +/* Define to 1 if you have the `arc4random_buf' function. */
    +#define HAVE_ARC4RANDOM_BUF 1
    +
     /* Define to 1 if you have the `bcopy' function. */
     #define HAVE_BCOPY 1
     
    @@ -21,9 +30,15 @@
     /* Define to 1 if you have the `getpagesize' function. */
     #define HAVE_GETPAGESIZE 1
     
    +/* Define to 1 if you have the `getrandom' function. */
    +#define HAVE_GETRANDOM 1
    +
     /* Define to 1 if you have the  header file. */
     #define HAVE_INTTYPES_H 1
     
    +/* Define to 1 if you have the `bsd' library (-lbsd). */
    +/* #undef HAVE_LIBBSD */
    +
     /* Define to 1 if you have the `memmove' function. */
     #define HAVE_MEMMOVE 1
     
    @@ -45,6 +60,9 @@
     /* Define to 1 if you have the  header file. */
     #define HAVE_STRING_H 1
     
    +/* Define to 1 if you have `syscall' and `SYS_getrandom'. */
    +#define HAVE_SYSCALL_GETRANDOM 1
    +
     /* Define to 1 if you have the  header file. */
     #define HAVE_SYS_PARAM_H 1
     
    @@ -57,9 +75,11 @@
     /* Define to 1 if you have the  header file. */
     #define HAVE_UNISTD_H 1
     
    -/* Define to the sub-directory in which libtool stores uninstalled libraries.
    -   */
    -#undef LT_OBJDIR
    +/* Define to the sub-directory where libtool stores uninstalled libraries. */
    +#define LT_OBJDIR ".libs/"
    +
    +/* Name of package */
    +#define PACKAGE "expat"
     
     /* Define to the address where bug reports for this package should be sent. */
     #define PACKAGE_BUGREPORT "expat-bugs@libexpat.org"
    @@ -68,7 +88,7 @@
     #define PACKAGE_NAME "expat"
     
     /* Define to the full name and version of this package. */
    -#define PACKAGE_STRING "expat 2.1.0"
    +#define PACKAGE_STRING "expat 2.2.6"
     
     /* Define to the one symbol short name of this package. */
     #define PACKAGE_TARNAME "expat"
    @@ -77,11 +97,14 @@
     #define PACKAGE_URL ""
     
     /* Define to the version of this package. */
    -#define PACKAGE_VERSION "2.1.0"
    +#define PACKAGE_VERSION "2.2.6"
     
     /* Define to 1 if you have the ANSI C header files. */
     #define STDC_HEADERS 1
     
    +/* Version number of package */
    +#define VERSION "2.2.6"
    +
     /* whether byteorder is bigendian */
     #if BYTE_ORDER == BIG_ENDIAN
     #define WORDS_BIGENDIAN
    @@ -93,15 +116,15 @@
        point. */
     #define XML_CONTEXT_BYTES 1024
     
    +/* Define to include code reading entropy from `/dev/urandom'. */
    +#define XML_DEV_URANDOM 1
    +
     /* Define to make parameter entity parsing functionality available. */
     #define XML_DTD 1
     
     /* Define to make XML Namespaces functionality available. */
     #define XML_NS 1
     
    -/* Define to __FUNCTION__ or "" if `__func__' does not conform to ANSI C. */
    -/* #undef __func__ */
    -
     /* Define to empty if `const' does not conform to ANSI C. */
     /* #undef const */
     
    diff --git a/lib/libexpat/libbsdxml.3 b/lib/libexpat/libbsdxml.3
    index 0d706ea7219d..d93dae89e7d4 100644
    --- a/lib/libexpat/libbsdxml.3
    +++ b/lib/libexpat/libbsdxml.3
    @@ -25,7 +25,7 @@
     .\"
     .\" $FreeBSD$
     .\"/
    -.Dd February 26, 2013
    +.Dd November 2, 2018
     .Dt LIBBSDXML 3
     .Os
     .Sh NAME
    @@ -36,7 +36,7 @@
     .Sh DESCRIPTION
     The
     .Nm
    -library is a verbatim copy of the eXpat XML library version 2.1.0.
    +library is a verbatim copy of the eXpat XML library version 2.2.6.
     .Pp
     The
     .Nm
    diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c
    index 72d8f07c6b88..8c034305f7d7 100644
    --- a/libexec/rtld-elf/rtld.c
    +++ b/libexec/rtld-elf/rtld.c
    @@ -700,10 +700,6 @@ _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
         if (do_copy_relocations(obj_main) == -1)
     	rtld_die();
     
    -    dbg("enforcing main obj relro");
    -    if (obj_enforce_relro(obj_main) == -1)
    -	rtld_die();
    -
         if (getenv(_LD("DUMP_REL_POST")) != NULL) {
            dump_relocations(obj_main);
            exit (0);
    @@ -739,6 +735,10 @@ _rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
           NULL) == -1)
     	rtld_die();
     
    +    dbg("enforcing main obj relro");
    +    if (obj_enforce_relro(obj_main) == -1)
    +	rtld_die();
    +
         if (!obj_main->crt_no_init) {
     	/*
     	 * Make sure we don't call the main program's init and fini
    diff --git a/sbin/dhclient/bpf.c b/sbin/dhclient/bpf.c
    index 3fe76f6e5579..4a753fd27595 100644
    --- a/sbin/dhclient/bpf.c
    +++ b/sbin/dhclient/bpf.c
    @@ -57,6 +57,8 @@ __FBSDID("$FreeBSD$");
     #include 
     #include 
     
    +#include 
    +
     #define BPF_FORMAT "/dev/bpf%d"
     
     /*
    @@ -164,7 +166,7 @@ if_register_send(struct interface_info *info)
     		error("Cannot lock bpf");
     
     	cap_rights_init(&rights, CAP_WRITE);
    -	if (cap_rights_limit(info->wfdesc, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(info->wfdesc, &rights) < 0)
     		error("Can't limit bpf descriptor: %m");
     
     	/*
    @@ -270,9 +272,9 @@ if_register_receive(struct interface_info *info)
     		error("Cannot lock bpf");
     
     	cap_rights_init(&rights, CAP_IOCTL, CAP_EVENT, CAP_READ);
    -	if (cap_rights_limit(info->rfdesc, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(info->rfdesc, &rights) < 0)
     		error("Can't limit bpf descriptor: %m");
    -	if (cap_ioctls_limit(info->rfdesc, cmds, 2) < 0 && errno != ENOSYS)
    +	if (caph_ioctls_limit(info->rfdesc, cmds, 2) < 0)
     		error("Can't limit ioctls for bpf descriptor: %m");
     }
     
    diff --git a/sbin/dhclient/dhclient.c b/sbin/dhclient/dhclient.c
    index 907a721512a7..b903f13597d0 100644
    --- a/sbin/dhclient/dhclient.c
    +++ b/sbin/dhclient/dhclient.c
    @@ -512,7 +512,7 @@ main(int argc, char *argv[])
     	close(pipe_fd[0]);
     	privfd = pipe_fd[1];
     	cap_rights_init(&rights, CAP_READ, CAP_WRITE);
    -	if (cap_rights_limit(privfd, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(privfd, &rights) < 0)
     		error("can't limit private descriptor: %m");
     
     	if ((fd = open(path_dhclient_db, O_RDONLY|O_EXLOCK|O_CREAT, 0)) == -1)
    @@ -526,7 +526,7 @@ main(int argc, char *argv[])
     	if (shutdown(routefd, SHUT_WR) < 0)
     		error("can't shutdown route socket: %m");
     	cap_rights_init(&rights, CAP_EVENT, CAP_READ);
    -	if (cap_rights_limit(routefd, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(routefd, &rights) < 0)
     		error("can't limit route socket: %m");
     
     	endpwent();
    @@ -1928,12 +1928,10 @@ rewrite_client_leases(void)
     			error("can't create %s: %m", path_dhclient_db);
     		cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_FSYNC,
     		    CAP_FTRUNCATE, CAP_SEEK, CAP_WRITE);
    -		if (cap_rights_limit(fileno(leaseFile), &rights) < 0 &&
    -		    errno != ENOSYS) {
    +		if (caph_rights_limit(fileno(leaseFile), &rights) < 0) {
     			error("can't limit lease descriptor: %m");
     		}
    -		if (cap_fcntls_limit(fileno(leaseFile), CAP_FCNTL_GETFL) < 0 &&
    -		    errno != ENOSYS) {
    +		if (caph_fcntls_limit(fileno(leaseFile), CAP_FCNTL_GETFL) < 0) {
     			error("can't limit lease descriptor fcntls: %m");
     		}
     	} else {
    @@ -2460,20 +2458,24 @@ go_daemon(void)
     
     	cap_rights_init(&rights);
     
    -	if (pidfile != NULL)
    +	if (pidfile != NULL) {
     		pidfile_write(pidfile);
     
    +		if (caph_rights_limit(pidfile_fileno(pidfile), &rights) < 0)
    +			error("can't limit pidfile descriptor: %m");
    +	}
    +
     	if (nullfd != -1) {
     		close(nullfd);
     		nullfd = -1;
     	}
     
    -	if (cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(STDIN_FILENO, &rights) < 0)
     		error("can't limit stdin: %m");
     	cap_rights_init(&rights, CAP_WRITE);
    -	if (cap_rights_limit(STDOUT_FILENO, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(STDOUT_FILENO, &rights) < 0)
     		error("can't limit stdout: %m");
    -	if (cap_rights_limit(STDERR_FILENO, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(STDERR_FILENO, &rights) < 0)
     		error("can't limit stderr: %m");
     }
     
    diff --git a/sbin/ipfw/ipv6.c b/sbin/ipfw/ipv6.c
    index 4a81203bc5b3..3bc5789fda41 100644
    --- a/sbin/ipfw/ipv6.c
    +++ b/sbin/ipfw/ipv6.c
    @@ -169,7 +169,7 @@ print_icmp6types(struct buf_pr *bp, ipfw_insn_u32 *cmd)
     	int i, j;
     	char sep= ' ';
     
    -	bprintf(bp, " ip6 icmp6types");
    +	bprintf(bp, " icmp6types");
     	for (i = 0; i < 7; i++)
     		for (j=0; j < 32; ++j) {
     			if ( (cmd->d[i] & (1 << (j))) == 0)
    diff --git a/sbin/md5/md5.c b/sbin/md5/md5.c
    index 3a52ddf1c0b1..1242d0fe906f 100644
    --- a/sbin/md5/md5.c
    +++ b/sbin/md5/md5.c
    @@ -242,8 +242,8 @@ main(int argc, char *argv[])
     			if (*(argv + 1) == NULL) {
     #ifdef HAVE_CAPSICUM
     				cap_rights_init(&rights, CAP_READ);
    -				if ((cap_rights_limit(fd, &rights) < 0 &&
    -				    errno != ENOSYS) || caph_enter() < 0)
    +				if (caph_rights_limit(fd, &rights) < 0 ||
    +				    caph_enter() < 0)
     					err(1, "capsicum");
     #endif
     			}
    diff --git a/sbin/ping/ping.c b/sbin/ping/ping.c
    index 492e21cbb8f9..81db0d5c24b4 100644
    --- a/sbin/ping/ping.c
    +++ b/sbin/ping/ping.c
    @@ -566,11 +566,7 @@ main(int argc, char *const *argv)
     		if (inet_aton(source, &sock_in.sin_addr) != 0) {
     			shostname = source;
     		} else {
    -			if (capdns != NULL)
    -				hp = cap_gethostbyname2(capdns, source,
    -				    AF_INET);
    -			else
    -				hp = gethostbyname2(source, AF_INET);
    +			hp = cap_gethostbyname2(capdns, source, AF_INET);
     			if (!hp)
     				errx(EX_NOHOST, "cannot resolve %s: %s",
     				    source, hstrerror(h_errno));
    @@ -598,10 +594,7 @@ main(int argc, char *const *argv)
     	if (inet_aton(target, &to->sin_addr) != 0) {
     		hostname = target;
     	} else {
    -		if (capdns != NULL)
    -			hp = cap_gethostbyname2(capdns, target, AF_INET);
    -		else
    -			hp = gethostbyname2(target, AF_INET);
    +		hp = cap_gethostbyname2(capdns, target, AF_INET);
     		if (!hp)
     			errx(EX_NOHOST, "cannot resolve %s: %s",
     			    target, hstrerror(h_errno));
    @@ -1693,10 +1686,7 @@ pr_addr(struct in_addr ina)
     	if (options & F_NUMERIC)
     		return inet_ntoa(ina);
     
    -	if (capdns != NULL)
    -		hp = cap_gethostbyaddr(capdns, (char *)&ina, 4, AF_INET);
    -	else
    -		hp = gethostbyaddr((char *)&ina, 4, AF_INET);
    +	hp = cap_gethostbyaddr(capdns, (char *)&ina, 4, AF_INET);
     
     	if (hp == NULL)
     		return inet_ntoa(ina);
    diff --git a/share/ctypedef/en_US.UTF-8.src b/share/ctypedef/C.UTF-8.src
    similarity index 100%
    rename from share/ctypedef/en_US.UTF-8.src
    rename to share/ctypedef/C.UTF-8.src
    diff --git a/share/ctypedef/Makefile b/share/ctypedef/Makefile
    index 279e7e4492c6..ab002fc82c92 100644
    --- a/share/ctypedef/Makefile
    +++ b/share/ctypedef/Makefile
    @@ -14,6 +14,7 @@ MAPLOC=		${.CURDIR}/../../tools/tools/locale/etc/final-maps
     	-f ${MAPLOC}/map.${.IMPSRC:T:R:E} \
     	-i ${.IMPSRC} ${.OBJDIR}/${.IMPSRC:T:R}  || true
     
    +LOCALES+=	C.UTF-8
     LOCALES+=	be_BY.CP1131
     LOCALES+=	ca_IT.ISO8859-1
     LOCALES+=	ca_IT.ISO8859-15
    @@ -21,7 +22,6 @@ LOCALES+=	el_GR.ISO8859-7
     LOCALES+=	en_US.ISO8859-1
     LOCALES+=	en_US.ISO8859-15
     LOCALES+=	en_US.US-ASCII
    -LOCALES+=	en_US.UTF-8
     LOCALES+=	hi_IN.ISCII-DEV
     LOCALES+=	hy_AM.ARMSCII-8
     LOCALES+=	ja_JP.SJIS
    @@ -45,82 +45,83 @@ LOCALES+=	zh_TW.Big5
     
     
     
    -SAME+=		en_US.UTF-8 ru_RU.UTF-8
    -SAME+=		en_US.UTF-8 zh_TW.UTF-8
    -SAME+=		en_US.UTF-8 zh_HK.UTF-8
    -SAME+=		en_US.UTF-8 zh_CN.UTF-8
    -SAME+=		en_US.UTF-8 uk_UA.UTF-8
    -SAME+=		en_US.UTF-8 tr_TR.UTF-8
    -SAME+=		en_US.UTF-8 sv_SE.UTF-8
    -SAME+=		en_US.UTF-8 sv_FI.UTF-8
    -SAME+=		en_US.UTF-8 sr_RS.UTF-8@latin
    -SAME+=		en_US.UTF-8 sr_RS.UTF-8
    -SAME+=		en_US.UTF-8 sl_SI.UTF-8
    -SAME+=		en_US.UTF-8 sk_SK.UTF-8
    -SAME+=		en_US.UTF-8 se_NO.UTF-8
    -SAME+=		en_US.UTF-8 se_FI.UTF-8
    -SAME+=		en_US.UTF-8 ro_RO.UTF-8
    -SAME+=		en_US.UTF-8 pt_PT.UTF-8
    -SAME+=		en_US.UTF-8 pt_BR.UTF-8
    -SAME+=		en_US.UTF-8 pl_PL.UTF-8
    -SAME+=		en_US.UTF-8 nn_NO.UTF-8
    -SAME+=		en_US.UTF-8 nl_NL.UTF-8
    -SAME+=		en_US.UTF-8 nl_BE.UTF-8
    -SAME+=		en_US.UTF-8 nb_NO.UTF-8
    -SAME+=		en_US.UTF-8 mn_MN.UTF-8
    -SAME+=		en_US.UTF-8 lv_LV.UTF-8
    -SAME+=		en_US.UTF-8 lt_LT.UTF-8
    -SAME+=		en_US.UTF-8 ko_KR.UTF-8
    -SAME+=		en_US.UTF-8 kk_KZ.UTF-8
    -SAME+=		en_US.UTF-8 ja_JP.UTF-8
    -SAME+=		en_US.UTF-8 it_IT.UTF-8
    -SAME+=		en_US.UTF-8 it_CH.UTF-8
    -SAME+=		en_US.UTF-8 is_IS.UTF-8
    -SAME+=		en_US.UTF-8 hy_AM.UTF-8
    -SAME+=		en_US.UTF-8 hu_HU.UTF-8
    -SAME+=		en_US.UTF-8 hr_HR.UTF-8
    -SAME+=		en_US.UTF-8 hi_IN.UTF-8
    -SAME+=		en_US.UTF-8 he_IL.UTF-8
    -SAME+=		en_US.UTF-8 fr_FR.UTF-8
    -SAME+=		en_US.UTF-8 fr_CH.UTF-8
    -SAME+=		en_US.UTF-8 fr_CA.UTF-8
    -SAME+=		en_US.UTF-8 fr_BE.UTF-8
    -SAME+=		en_US.UTF-8 fi_FI.UTF-8
    -SAME+=		en_US.UTF-8 eu_ES.UTF-8
    -SAME+=		en_US.UTF-8 et_EE.UTF-8
    -SAME+=		en_US.UTF-8 es_MX.UTF-8
    -SAME+=		en_US.UTF-8 es_ES.UTF-8
    -SAME+=		en_US.UTF-8 es_CR.UTF-8
    -SAME+=		en_US.UTF-8 es_AR.UTF-8
    -SAME+=		en_US.UTF-8 en_ZA.UTF-8
    -SAME+=		en_US.UTF-8 en_SG.UTF-8
    -SAME+=		en_US.UTF-8 en_PH.UTF-8
    -SAME+=		en_US.UTF-8 en_NZ.UTF-8
    -SAME+=		en_US.UTF-8 en_IE.UTF-8
    -SAME+=		en_US.UTF-8 en_HK.UTF-8
    -SAME+=		en_US.UTF-8 en_GB.UTF-8
    -SAME+=		en_US.UTF-8 en_CA.UTF-8
    -SAME+=		en_US.UTF-8 en_AU.UTF-8
    -SAME+=		en_US.UTF-8 el_GR.UTF-8
    -SAME+=		en_US.UTF-8 de_DE.UTF-8
    -SAME+=		en_US.UTF-8 de_CH.UTF-8
    -SAME+=		en_US.UTF-8 de_AT.UTF-8
    -SAME+=		en_US.UTF-8 da_DK.UTF-8
    -SAME+=		en_US.UTF-8 cs_CZ.UTF-8
    -SAME+=		en_US.UTF-8 ca_IT.UTF-8
    -SAME+=		en_US.UTF-8 ca_FR.UTF-8
    -SAME+=		en_US.UTF-8 ca_ES.UTF-8
    -SAME+=		en_US.UTF-8 ca_AD.UTF-8
    -SAME+=		en_US.UTF-8 bg_BG.UTF-8
    -SAME+=		en_US.UTF-8 be_BY.UTF-8
    -SAME+=		en_US.UTF-8 ar_SA.UTF-8
    -SAME+=		en_US.UTF-8 ar_QA.UTF-8
    -SAME+=		en_US.UTF-8 ar_MA.UTF-8
    -SAME+=		en_US.UTF-8 ar_JO.UTF-8
    -SAME+=		en_US.UTF-8 ar_EG.UTF-8
    -SAME+=		en_US.UTF-8 ar_AE.UTF-8
    -SAME+=		en_US.UTF-8 am_ET.UTF-8
    -SAME+=		en_US.UTF-8 af_ZA.UTF-8
    +SAME+=		C.UTF-8 en_US.UTF-8
    +SAME+=		C.UTF-8 ru_RU.UTF-8
    +SAME+=		C.UTF-8 zh_TW.UTF-8
    +SAME+=		C.UTF-8 zh_HK.UTF-8
    +SAME+=		C.UTF-8 zh_CN.UTF-8
    +SAME+=		C.UTF-8 uk_UA.UTF-8
    +SAME+=		C.UTF-8 tr_TR.UTF-8
    +SAME+=		C.UTF-8 sv_SE.UTF-8
    +SAME+=		C.UTF-8 sv_FI.UTF-8
    +SAME+=		C.UTF-8 sr_RS.UTF-8@latin
    +SAME+=		C.UTF-8 sr_RS.UTF-8
    +SAME+=		C.UTF-8 sl_SI.UTF-8
    +SAME+=		C.UTF-8 sk_SK.UTF-8
    +SAME+=		C.UTF-8 se_NO.UTF-8
    +SAME+=		C.UTF-8 se_FI.UTF-8
    +SAME+=		C.UTF-8 ro_RO.UTF-8
    +SAME+=		C.UTF-8 pt_PT.UTF-8
    +SAME+=		C.UTF-8 pt_BR.UTF-8
    +SAME+=		C.UTF-8 pl_PL.UTF-8
    +SAME+=		C.UTF-8 nn_NO.UTF-8
    +SAME+=		C.UTF-8 nl_NL.UTF-8
    +SAME+=		C.UTF-8 nl_BE.UTF-8
    +SAME+=		C.UTF-8 nb_NO.UTF-8
    +SAME+=		C.UTF-8 mn_MN.UTF-8
    +SAME+=		C.UTF-8 lv_LV.UTF-8
    +SAME+=		C.UTF-8 lt_LT.UTF-8
    +SAME+=		C.UTF-8 ko_KR.UTF-8
    +SAME+=		C.UTF-8 kk_KZ.UTF-8
    +SAME+=		C.UTF-8 ja_JP.UTF-8
    +SAME+=		C.UTF-8 it_IT.UTF-8
    +SAME+=		C.UTF-8 it_CH.UTF-8
    +SAME+=		C.UTF-8 is_IS.UTF-8
    +SAME+=		C.UTF-8 hy_AM.UTF-8
    +SAME+=		C.UTF-8 hu_HU.UTF-8
    +SAME+=		C.UTF-8 hr_HR.UTF-8
    +SAME+=		C.UTF-8 hi_IN.UTF-8
    +SAME+=		C.UTF-8 he_IL.UTF-8
    +SAME+=		C.UTF-8 fr_FR.UTF-8
    +SAME+=		C.UTF-8 fr_CH.UTF-8
    +SAME+=		C.UTF-8 fr_CA.UTF-8
    +SAME+=		C.UTF-8 fr_BE.UTF-8
    +SAME+=		C.UTF-8 fi_FI.UTF-8
    +SAME+=		C.UTF-8 eu_ES.UTF-8
    +SAME+=		C.UTF-8 et_EE.UTF-8
    +SAME+=		C.UTF-8 es_MX.UTF-8
    +SAME+=		C.UTF-8 es_ES.UTF-8
    +SAME+=		C.UTF-8 es_CR.UTF-8
    +SAME+=		C.UTF-8 es_AR.UTF-8
    +SAME+=		C.UTF-8 en_ZA.UTF-8
    +SAME+=		C.UTF-8 en_SG.UTF-8
    +SAME+=		C.UTF-8 en_PH.UTF-8
    +SAME+=		C.UTF-8 en_NZ.UTF-8
    +SAME+=		C.UTF-8 en_IE.UTF-8
    +SAME+=		C.UTF-8 en_HK.UTF-8
    +SAME+=		C.UTF-8 en_GB.UTF-8
    +SAME+=		C.UTF-8 en_CA.UTF-8
    +SAME+=		C.UTF-8 en_AU.UTF-8
    +SAME+=		C.UTF-8 el_GR.UTF-8
    +SAME+=		C.UTF-8 de_DE.UTF-8
    +SAME+=		C.UTF-8 de_CH.UTF-8
    +SAME+=		C.UTF-8 de_AT.UTF-8
    +SAME+=		C.UTF-8 da_DK.UTF-8
    +SAME+=		C.UTF-8 cs_CZ.UTF-8
    +SAME+=		C.UTF-8 ca_IT.UTF-8
    +SAME+=		C.UTF-8 ca_FR.UTF-8
    +SAME+=		C.UTF-8 ca_ES.UTF-8
    +SAME+=		C.UTF-8 ca_AD.UTF-8
    +SAME+=		C.UTF-8 bg_BG.UTF-8
    +SAME+=		C.UTF-8 be_BY.UTF-8
    +SAME+=		C.UTF-8 ar_SA.UTF-8
    +SAME+=		C.UTF-8 ar_QA.UTF-8
    +SAME+=		C.UTF-8 ar_MA.UTF-8
    +SAME+=		C.UTF-8 ar_JO.UTF-8
    +SAME+=		C.UTF-8 ar_EG.UTF-8
    +SAME+=		C.UTF-8 ar_AE.UTF-8
    +SAME+=		C.UTF-8 am_ET.UTF-8
    +SAME+=		C.UTF-8 af_ZA.UTF-8
     SAME+=		en_US.ISO8859-1 sv_SE.ISO8859-1
     SAME+=		en_US.ISO8859-1 sv_FI.ISO8859-1
     SAME+=		en_US.ISO8859-1 pt_PT.ISO8859-1
    diff --git a/share/man/man4/ng_pptpgre.4 b/share/man/man4/ng_pptpgre.4
    index 867c86cd523f..632bc7b555d4 100644
    --- a/share/man/man4/ng_pptpgre.4
    +++ b/share/man/man4/ng_pptpgre.4
    @@ -35,7 +35,7 @@
     .\" $FreeBSD$
     .\" $Whistle: ng_pptpgre.8,v 1.2 1999/12/08 00:20:53 archie Exp $
     .\"
    -.Dd November 13, 2012
    +.Dd November 4, 2018
     .Dt NG_PPTPGRE 4
     .Os
     .Sh NAME
    @@ -141,11 +141,33 @@ This command atomically gets and resets the node statistics, returning a
     This node shuts down upon receipt of a
     .Dv NGM_SHUTDOWN
     control message, or when both hooks have been disconnected.
    +.Sh SYSCTL VARIABLES
    +A set of
    +.Xr sysctl 8
    +variables controls ability of this node to deal with some
    +amount of packet reorder that sometimes happens in transit.
    +Packet reorder results in packet drops (unless the order is restored)
    +as PPP protocol can not deliver reordered data.
    +These variables are shown below together
    +with their default value and meaning:
    +.Bl -tag -width indent
    +.It Va net.graph.pptpgre.reorder_max: 1
    +Defines maximum length of node's private reorder queue
    +used to keep data waiting for late packets.
    +Zero value disables reordering.
    +Default value allows the node to restore the order for two packets swapped
    +in transit.
    +Greater values allow the node to deliver packets being late after more
    +packets in sequence at cost of increased kernel memory usage.
    +.It Va net.graph.pptpgre.reorder_timeout: 1
    +Defines time value in miliseconds used to wait for late packets.
    +.El
     .Sh SEE ALSO
     .Xr netgraph 4 ,
     .Xr ng_ksocket 4 ,
     .Xr ng_ppp 4 ,
    -.Xr ngctl 8
    +.Xr ngctl 8 ,
    +.Xr sysctl 8
     .Rs
     .%A K. Hamzeh
     .%A G. Pall
    diff --git a/share/man/man5/src.conf.5 b/share/man/man5/src.conf.5
    index c62a6d605615..31d9fb4e9133 100644
    --- a/share/man/man5/src.conf.5
    +++ b/share/man/man5/src.conf.5
    @@ -1,6 +1,6 @@
     .\" DO NOT EDIT-- this file is @generated by tools/build/options/makeman.
     .\" $FreeBSD$
    -.Dd October 30, 2018
    +.Dd November 6, 2018
     .Dt SRC.CONF 5
     .Os
     .Sh NAME
    @@ -143,6 +143,11 @@ Set to not build or install
     associated utilities, and examples.
     .Pp
     This option only affects amd64/amd64.
    +.It Va WITH_BIND_NOW
    +Build all binaries with the
    +.Dv DF_BIND_NOW
    +flag set to indicate that the run-time loader should perform all relocation
    +processing at process startup rather than on demand.
     .It Va WITHOUT_BINUTILS
     Set to not build or install binutils (as, ld, and objdump) as part
     of the normal system build.
    @@ -624,10 +629,6 @@ Set this if you do not want to link
     and
     .Pa /sbin
     dynamically.
    -.It Va WITHOUT_ED_CRYPTO
    -Set to build
    -.Xr ed 1
    -without support for encryption/decryption.
     .It Va WITHOUT_EE
     Set to not build and install
     .Xr edit 1 ,
    @@ -1018,7 +1019,8 @@ enabled unless an alternate linker is provided via XLD.
     This is a default setting on
     arm/arm, arm/armv6, mips/mipsel, mips/mips, mips/mips64el, mips/mips64, mips/mipsn32, mips/mipselhf, mips/mipshf, mips/mips64elhf, mips/mips64hf, powerpc/powerpc, powerpc/powerpc64, powerpc/powerpcspe, riscv/riscv64 and sparc64/sparc64.
     .It Va WITH_LLD_BOOTSTRAP
    -Set to build the LLD linker during the bootstrap phase of the build.
    +Set to build the LLD linker during the bootstrap phase of the build,
    +and use it during buildworld and buildkernel.
     .Pp
     This is a default setting on
     amd64/amd64, arm/armv7, arm64/aarch64 and i386/i386.
    diff --git a/share/mk/bsd.lib.mk b/share/mk/bsd.lib.mk
    index 2dfac241122a..5c1a38ce7ccd 100644
    --- a/share/mk/bsd.lib.mk
    +++ b/share/mk/bsd.lib.mk
    @@ -69,6 +69,10 @@ TAGS+=		package=${PACKAGE:Uruntime}
     TAG_ARGS=	-T ${TAGS:[*]:S/ /,/g}
     .endif
     
    +# ELF hardening knobs
    +.if ${MK_BIND_NOW} != "no"
    +LDFLAGS+= -Wl,-znow
    +.endif
     .if ${MK_RETPOLINE} != "no"
     CFLAGS+= -mretpoline
     CXXFLAGS+= -mretpoline
    diff --git a/share/mk/bsd.opts.mk b/share/mk/bsd.opts.mk
    index 30255dd9b4dd..5a5bf811ddf9 100644
    --- a/share/mk/bsd.opts.mk
    +++ b/share/mk/bsd.opts.mk
    @@ -69,6 +69,7 @@ __DEFAULT_YES_OPTIONS = \
         WARNS
     
     __DEFAULT_NO_OPTIONS = \
    +    BIND_NOW \
         CCACHE_BUILD \
         CTF \
         INSTALL_AS_USER \
    diff --git a/share/mk/bsd.prog.mk b/share/mk/bsd.prog.mk
    index b82a89d42adc..2b151c0af7b0 100644
    --- a/share/mk/bsd.prog.mk
    +++ b/share/mk/bsd.prog.mk
    @@ -34,6 +34,10 @@ PROG=	${PROG_CXX}
     MK_DEBUG_FILES=	no
     .endif
     
    +# ELF hardening knobs
    +.if ${MK_BIND_NOW} != "no"
    +LDFLAGS+= -Wl,-znow
    +.endif
     .if ${MK_RETPOLINE} != "no"
     CFLAGS+= -mretpoline
     CXXFLAGS+= -mretpoline
    diff --git a/share/mk/src.opts.mk b/share/mk/src.opts.mk
    index 10aa1e8986ac..dc017618db4f 100644
    --- a/share/mk/src.opts.mk
    +++ b/share/mk/src.opts.mk
    @@ -90,7 +90,6 @@ __DEFAULT_YES_OPTIONS = \
         DICT \
         DMAGENT \
         DYNAMICROOT \
    -    ED_CRYPTO \
         EE \
         EFI \
         ELFTOOLCHAIN_BOOTSTRAP \
    diff --git a/stand/lua/menu.lua b/stand/lua/menu.lua
    index 03c44bfb7c48..41c23273fadd 100644
    --- a/stand/lua/menu.lua
    +++ b/stand/lua/menu.lua
    @@ -337,6 +337,22 @@ menu.welcome = {
     			submenu = menu.boot_environments,
     			alias = {"e", "E"},
     		},
    +		-- chainload
    +		{
    +			entry_type = core.MENU_ENTRY,
    +			name = function()
    +				return 'Chain' .. color.highlight("L") ..
    +				    "oad " .. loader.getenv('chain_disk')
    +			end,
    +			func = function()
    +				loader.perform("chain " ..
    +				    loader.getenv('chain_disk'))
    +			end,
    +			visible = function()
    +				return loader.getenv('chain_disk') ~= nil
    +			end,
    +			alias = {"l", "L"},
    +		},
     	},
     }
     
    diff --git a/sys/amd64/conf/GENERIC b/sys/amd64/conf/GENERIC
    index f74db37a283e..34fb1e8e4370 100644
    --- a/sys/amd64/conf/GENERIC
    +++ b/sys/amd64/conf/GENERIC
    @@ -100,6 +100,8 @@ options 	WITNESS			# Enable checks to detect deadlocks and cycles
     options 	WITNESS_SKIPSPIN	# Don't run witness on spinlocks for speed
     options 	MALLOC_DEBUG_MAXZONES=8	# Separate malloc(9) zones
     options 	VERBOSE_SYSINIT=0	# Support debug.verbose_sysinit, off by default
    +# Warning: KUBSAN can result in a kernel too large for loader to load
    +#options 	KUBSAN			# Kernel Undefined Behavior Sanitizer
     
     # Kernel dump features.
     options 	EKCD			# Support for encrypted kernel dumps
    diff --git a/sys/amd64/include/cpu.h b/sys/amd64/include/cpu.h
    index db3554fad84f..1b8a552d3e7c 100644
    --- a/sys/amd64/include/cpu.h
    +++ b/sys/amd64/include/cpu.h
    @@ -77,6 +77,7 @@ extern char	etext[];
     extern	void (*vmm_resume_p)(void);
     
     void	cpu_halt(void);
    +void	cpu_lock_delay(void);
     void	cpu_reset(void);
     void	fork_trampoline(void);
     void	swi_vm(void *);
    diff --git a/sys/amd64/linux32/linux32_sysvec.c b/sys/amd64/linux32/linux32_sysvec.c
    index 66d441e96c68..bcaa0cd45459 100644
    --- a/sys/amd64/linux32/linux32_sysvec.c
    +++ b/sys/amd64/linux32/linux32_sysvec.c
    @@ -32,6 +32,8 @@
      * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      */
     
    +#include "opt_compat.h"
    +
     #include 
     __FBSDID("$FreeBSD$");
     
    @@ -1071,7 +1073,7 @@ linux_elf_modevent(module_t mod, int type, void *data)
     				error = EINVAL;
     		if (error == 0) {
     			SET_FOREACH(lihp, linux_ioctl_handler_set)
    -				linux_ioctl_register_handler(*lihp);
    +				linux32_ioctl_register_handler(*lihp);
     			LIST_INIT(&futex_list);
     			mtx_init(&futex_mtx, "ftllk", NULL, MTX_DEF);
     			stclohz = (stathz ? stathz : hz);
    @@ -1093,7 +1095,7 @@ linux_elf_modevent(module_t mod, int type, void *data)
     		}
     		if (error == 0) {
     			SET_FOREACH(lihp, linux_ioctl_handler_set)
    -				linux_ioctl_unregister_handler(*lihp);
    +				linux32_ioctl_unregister_handler(*lihp);
     			mtx_destroy(&futex_mtx);
     			if (bootverbose)
     				printf("Linux ELF exec handler removed\n");
    diff --git a/sys/arm/include/cpu.h b/sys/arm/include/cpu.h
    index 1ef5798ecddb..7c7de38a2536 100644
    --- a/sys/arm/include/cpu.h
    +++ b/sys/arm/include/cpu.h
    @@ -61,6 +61,7 @@ get_cyclecount(void)
     #define cpu_getstack(td)	((td)->td_frame->tf_usr_sp)
     #define cpu_setstack(td, sp)	((td)->td_frame->tf_usr_sp = (sp))
     #define cpu_spinwait()		/* nothing */
    +#define	cpu_lock_delay()	DELAY(1)
     
     #define ARM_NVEC		8
     #define ARM_VEC_ALL		0xffffffff
    diff --git a/sys/arm/include/elf.h b/sys/arm/include/elf.h
    index 7424b45e78f4..28fc14e3dae3 100644
    --- a/sys/arm/include/elf.h
    +++ b/sys/arm/include/elf.h
    @@ -84,7 +84,7 @@ __ElfType(Auxinfo);
      */
     #define	MAGIC_TRAMP_NUMBER	0x5c000003
     
    -#define	ET_DYN_LOAD_ADDR	0x12000
    +#define	ET_DYN_LOAD_ADDR	0x500000
     
     /* Flags passed in AT_HWCAP. */
     #define	HWCAP_SWP		0x00000001	/* Unsupported, never set.    */
    diff --git a/sys/arm64/conf/GENERIC b/sys/arm64/conf/GENERIC
    index ee4ab292928f..c626727d5209 100644
    --- a/sys/arm64/conf/GENERIC
    +++ b/sys/arm64/conf/GENERIC
    @@ -92,6 +92,8 @@ options 	MALLOC_DEBUG_MAXZONES=8	# Separate malloc(9) zones
     options 	ALT_BREAK_TO_DEBUGGER	# Enter debugger on keyboard escape sequence
     options 	USB_DEBUG		# enable debug msgs
     options 	VERBOSE_SYSINIT=0	# Support debug.verbose_sysinit, off by default
    +# Warning: KUBSAN can result in a kernel too large for loader to load
    +#options 	KUBSAN			# Kernel Undefined Behavior Sanitizer
     
     # Kernel dump features.
     options 	EKCD			# Support for encrypted kernel dumps
    diff --git a/sys/arm64/include/cpu.h b/sys/arm64/include/cpu.h
    index f5d7909b7899..3cfc59c25bff 100644
    --- a/sys/arm64/include/cpu.h
    +++ b/sys/arm64/include/cpu.h
    @@ -51,6 +51,7 @@
     #define	cpu_getstack(td)	((td)->td_frame->tf_sp)
     #define	cpu_setstack(td, sp)	((td)->td_frame->tf_sp = (sp))
     #define	cpu_spinwait()		__asm __volatile("yield" ::: "memory")
    +#define	cpu_lock_delay()	DELAY(1)
     
     /* Extract CPU affinity levels 0-3 */
     #define	CPU_AFF0(mpidr)	(u_int)(((mpidr) >> 0) & 0xff)
    diff --git a/sys/cam/scsi/scsi_da.c b/sys/cam/scsi/scsi_da.c
    index 2483c5e7633e..a1ac49d146db 100644
    --- a/sys/cam/scsi/scsi_da.c
    +++ b/sys/cam/scsi/scsi_da.c
    @@ -2005,7 +2005,7 @@ daasync(void *callback_arg, u_int32_t code,
     
     	periph = (struct cam_periph *)callback_arg;
     	switch (code) {
    -	case AC_FOUND_DEVICE:
    +	case AC_FOUND_DEVICE:	/* callback to create periph, no locking yet */
     	{
     		struct ccb_getdev *cgd;
     		cam_status status;
    @@ -2041,7 +2041,7 @@ daasync(void *callback_arg, u_int32_t code,
     				"due to status 0x%x\n", status);
     		return;
     	}
    -	case AC_ADVINFO_CHANGED:
    +	case AC_ADVINFO_CHANGED:	/* Doesn't touch periph */
     	{
     		uintptr_t buftype;
     
    @@ -2064,8 +2064,10 @@ daasync(void *callback_arg, u_int32_t code,
     		ccb = (union ccb *)arg;
     
     		/*
    -		 * Handle all UNIT ATTENTIONs except our own,
    -		 * as they will be handled by daerror().
    +		 * Handle all UNIT ATTENTIONs except our own, as they will be
    +		 * handled by daerror(). Since this comes from a different periph,
    +		 * that periph's lock is held, not ours, so we have to take it ours
    +		 * out to touch softc flags.
     		 */
     		if (xpt_path_periph(ccb->ccb_h.path) != periph &&
     		    scsi_extract_sense_ccb(ccb,
    @@ -2093,9 +2095,13 @@ daasync(void *callback_arg, u_int32_t code,
     		}
     		break;
     	}
    -	case AC_SCSI_AEN:
    +	case AC_SCSI_AEN:		/* Called for this path: periph locked */
    +		/*
    +		 * Appears to be currently unused for SCSI devices, only ata SIMs
    +		 * generate this.
    +		 */
    +		cam_periph_assert(periph, MA_OWNED);
     		softc = (struct da_softc *)periph->softc;
    -		cam_periph_lock(periph);
     		if (!cam_iosched_has_work_flags(softc->cam_iosched, DA_WORK_TUR) &&
     		    (softc->flags & DA_FLAG_TUR_PENDING) == 0) {
     			if (da_periph_acquire(periph, DA_REF_TUR) == 0) {
    @@ -2103,31 +2109,28 @@ daasync(void *callback_arg, u_int32_t code,
     				daschedule(periph);
     			}
     		}
    -		cam_periph_unlock(periph);
     		/* FALLTHROUGH */
    -	case AC_SENT_BDR:
    -	case AC_BUS_RESET:
    +	case AC_SENT_BDR:		/* Called for this path: periph locked */
    +	case AC_BUS_RESET:		/* Called for this path: periph locked */
     	{
     		struct ccb_hdr *ccbh;
     
    +		cam_periph_assert(periph, MA_OWNED);
     		softc = (struct da_softc *)periph->softc;
     		/*
     		 * Don't fail on the expected unit attention
     		 * that will occur.
     		 */
    -		cam_periph_lock(periph);
     		softc->flags |= DA_FLAG_RETRY_UA;
     		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
     			ccbh->ccb_state |= DA_CCB_RETRY_UA;
    -		cam_periph_unlock(periph);
     		break;
     	}
    -	case AC_INQ_CHANGED:
    -		cam_periph_lock(periph);
    +	case AC_INQ_CHANGED:		/* Called for this path: periph locked */
    +		cam_periph_assert(periph, MA_OWNED);
     		softc = (struct da_softc *)periph->softc;
     		softc->flags &= ~DA_FLAG_PROBED;
     		dareprobe(periph);
    -		cam_periph_unlock(periph);
     		break;
     	default:
     		break;
    diff --git a/sys/compat/freebsd32/capabilities.conf b/sys/compat/freebsd32/capabilities.conf
    index c96dab7aa9d4..8d7105cef948 100644
    --- a/sys/compat/freebsd32/capabilities.conf
    +++ b/sys/compat/freebsd32/capabilities.conf
    @@ -203,6 +203,7 @@ pdkill
     freebsd32_pipe
     pipe2
     poll
    +freebsd32_ppoll
     freebsd32_posix_fallocate
     freebsd32_pread
     freebsd32_preadv
    diff --git a/sys/compat/freebsd32/freebsd32_proto.h b/sys/compat/freebsd32/freebsd32_proto.h
    index ed48baf7295f..9f15277fc77c 100644
    --- a/sys/compat/freebsd32/freebsd32_proto.h
    +++ b/sys/compat/freebsd32/freebsd32_proto.h
    @@ -55,10 +55,10 @@ struct freebsd32_sendmsg_args {
     };
     struct freebsd32_recvfrom_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char buf_l_[PADL_(uint32_t)]; uint32_t buf; char buf_r_[PADR_(uint32_t)];
    +	char buf_l_[PADL_(void *)]; void * buf; char buf_r_[PADR_(void *)];
     	char len_l_[PADL_(uint32_t)]; uint32_t len; char len_r_[PADR_(uint32_t)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    -	char from_l_[PADL_(uint32_t)]; uint32_t from; char from_r_[PADR_(uint32_t)];
    +	char from_l_[PADL_(struct sockaddr *)]; struct sockaddr * from; char from_r_[PADR_(struct sockaddr *)];
     	char fromlenaddr_l_[PADL_(uint32_t)]; uint32_t fromlenaddr; char fromlenaddr_r_[PADR_(uint32_t)];
     };
     struct freebsd10_freebsd32_pipe_args {
    @@ -417,7 +417,7 @@ struct freebsd32_pwrite_args {
     	char offset2_l_[PADL_(uint32_t)]; uint32_t offset2; char offset2_r_[PADR_(uint32_t)];
     };
     struct freebsd32_mmap_args {
    -	char addr_l_[PADL_(caddr_t)]; caddr_t addr; char addr_r_[PADR_(caddr_t)];
    +	char addr_l_[PADL_(void *)]; void * addr; char addr_r_[PADR_(void *)];
     	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
     	char prot_l_[PADL_(int)]; int prot; char prot_r_[PADR_(int)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    @@ -461,7 +461,7 @@ struct freebsd32_pwrite_args {
     	char offset2_l_[PADL_(uint32_t)]; uint32_t offset2; char offset2_r_[PADR_(uint32_t)];
     };
     struct freebsd32_mmap_args {
    -	char addr_l_[PADL_(caddr_t)]; caddr_t addr; char addr_r_[PADR_(caddr_t)];
    +	char addr_l_[PADL_(void *)]; void * addr; char addr_r_[PADR_(void *)];
     	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
     	char prot_l_[PADL_(int)]; int prot; char prot_r_[PADR_(int)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    @@ -1020,7 +1020,7 @@ struct freebsd6_freebsd32_pwrite_args {
     	char offset2_l_[PADL_(uint32_t)]; uint32_t offset2; char offset2_r_[PADR_(uint32_t)];
     };
     struct freebsd6_freebsd32_mmap_args {
    -	char addr_l_[PADL_(caddr_t)]; caddr_t addr; char addr_r_[PADR_(caddr_t)];
    +	char addr_l_[PADL_(void *)]; void * addr; char addr_r_[PADR_(void *)];
     	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
     	char prot_l_[PADL_(int)]; int prot; char prot_r_[PADR_(int)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    diff --git a/sys/compat/freebsd32/freebsd32_sysent.c b/sys/compat/freebsd32/freebsd32_sysent.c
    index 1a6ff314dfa2..de97d29af51e 100644
    --- a/sys/compat/freebsd32/freebsd32_sysent.c
    +++ b/sys/compat/freebsd32/freebsd32_sysent.c
    @@ -624,7 +624,7 @@ struct sysent freebsd32_sysent[] = {
     #else
     	{ AS(freebsd32_procctl_args), (sy_call_t *)freebsd32_procctl, AUE_PROCCTL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 544 = freebsd32_procctl */
     #endif
    -	{ AS(freebsd32_ppoll_args), (sy_call_t *)freebsd32_ppoll, AUE_POLL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 545 = freebsd32_ppoll */
    +	{ AS(freebsd32_ppoll_args), (sy_call_t *)freebsd32_ppoll, AUE_POLL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 545 = freebsd32_ppoll */
     	{ AS(freebsd32_futimens_args), (sy_call_t *)freebsd32_futimens, AUE_FUTIMES, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 546 = freebsd32_futimens */
     	{ AS(freebsd32_utimensat_args), (sy_call_t *)freebsd32_utimensat, AUE_FUTIMESAT, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 547 = freebsd32_utimensat */
     	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 548 = obsolete numa_getaffinity */
    diff --git a/sys/compat/freebsd32/freebsd32_systrace_args.c b/sys/compat/freebsd32/freebsd32_systrace_args.c
    index 59d97c7a74ce..116d6c40716d 100644
    --- a/sys/compat/freebsd32/freebsd32_systrace_args.c
    +++ b/sys/compat/freebsd32/freebsd32_systrace_args.c
    @@ -139,7 +139,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		uarg[0] = (intptr_t) p->type; /* const char * */
     		uarg[1] = (intptr_t) p->path; /* const char * */
     		iarg[2] = p->flags; /* int */
    -		uarg[3] = (intptr_t) p->data; /* caddr_t */
    +		uarg[3] = (intptr_t) p->data; /* void * */
     		*n_args = 4;
     		break;
     	}
    @@ -200,10 +200,10 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 29: {
     		struct freebsd32_recvfrom_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = p->buf; /* uint32_t */
    +		uarg[1] = (intptr_t) p->buf; /* void * */
     		uarg[2] = p->len; /* uint32_t */
     		iarg[3] = p->flags; /* int */
    -		uarg[4] = p->from; /* uint32_t */
    +		uarg[4] = (intptr_t) p->from; /* struct sockaddr * */
     		uarg[5] = p->fromlenaddr; /* uint32_t */
     		*n_args = 6;
     		break;
    @@ -212,7 +212,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 30: {
     		struct accept_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->name; /* caddr_t */
    +		uarg[1] = (intptr_t) p->name; /* struct sockaddr * */
     		uarg[2] = (intptr_t) p->anamelen; /* int * */
     		*n_args = 3;
     		break;
    @@ -221,7 +221,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 31: {
     		struct getpeername_args *p = params;
     		iarg[0] = p->fdes; /* int */
    -		uarg[1] = (intptr_t) p->asa; /* caddr_t */
    +		uarg[1] = (intptr_t) p->asa; /* struct sockaddr * */
     		uarg[2] = (intptr_t) p->alen; /* int * */
     		*n_args = 3;
     		break;
    @@ -230,7 +230,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 32: {
     		struct getsockname_args *p = params;
     		iarg[0] = p->fdes; /* int */
    -		uarg[1] = (intptr_t) p->asa; /* caddr_t */
    +		uarg[1] = (intptr_t) p->asa; /* struct sockaddr * */
     		uarg[2] = (intptr_t) p->alen; /* int * */
     		*n_args = 3;
     		break;
    @@ -292,7 +292,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	/* profil */
     	case 44: {
     		struct profil_args *p = params;
    -		uarg[0] = (intptr_t) p->samples; /* caddr_t */
    +		uarg[0] = (intptr_t) p->samples; /* char * */
     		uarg[1] = p->size; /* size_t */
     		uarg[2] = p->offset; /* size_t */
     		uarg[3] = p->scale; /* u_int */
    @@ -585,7 +585,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 98: {
     		struct connect_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->name; /* caddr_t */
    +		uarg[1] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[2] = p->namelen; /* int */
     		*n_args = 3;
     		break;
    @@ -602,7 +602,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 104: {
     		struct bind_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->name; /* caddr_t */
    +		uarg[1] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[2] = p->namelen; /* int */
     		*n_args = 3;
     		break;
    @@ -613,7 +613,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		iarg[0] = p->s; /* int */
     		iarg[1] = p->level; /* int */
     		iarg[2] = p->name; /* int */
    -		uarg[3] = (intptr_t) p->val; /* caddr_t */
    +		uarg[3] = (intptr_t) p->val; /* const void * */
     		iarg[4] = p->valsize; /* int */
     		*n_args = 5;
     		break;
    @@ -648,7 +648,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		iarg[0] = p->s; /* int */
     		iarg[1] = p->level; /* int */
     		iarg[2] = p->name; /* int */
    -		uarg[3] = (intptr_t) p->val; /* caddr_t */
    +		uarg[3] = (intptr_t) p->val; /* void * */
     		uarg[4] = (intptr_t) p->avalsize; /* int * */
     		*n_args = 5;
     		break;
    @@ -740,10 +740,10 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 133: {
     		struct sendto_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->buf; /* caddr_t */
    +		uarg[1] = (intptr_t) p->buf; /* const void * */
     		uarg[2] = p->len; /* size_t */
     		iarg[3] = p->flags; /* int */
    -		uarg[4] = (intptr_t) p->to; /* caddr_t */
    +		uarg[4] = (intptr_t) p->to; /* const struct sockaddr * */
     		iarg[5] = p->tolen; /* int */
     		*n_args = 6;
     		break;
    @@ -808,7 +808,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		uarg[0] = (intptr_t) p->path; /* const char * */
     		iarg[1] = p->cmd; /* int */
     		iarg[2] = p->uid; /* int */
    -		uarg[3] = (intptr_t) p->arg; /* caddr_t */
    +		uarg[3] = (intptr_t) p->arg; /* void * */
     		*n_args = 4;
     		break;
     	}
    @@ -2312,9 +2312,9 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 472: {
     		struct sctp_generic_sendmsg_args *p = params;
     		iarg[0] = p->sd; /* int */
    -		uarg[1] = (intptr_t) p->msg; /* caddr_t */
    +		uarg[1] = (intptr_t) p->msg; /* void * */
     		iarg[2] = p->mlen; /* int */
    -		uarg[3] = (intptr_t) p->to; /* caddr_t */
    +		uarg[3] = (intptr_t) p->to; /* struct sockaddr * */
     		iarg[4] = p->tolen; /* __socklen_t */
     		uarg[5] = (intptr_t) p->sinfo; /* struct sctp_sndrcvinfo * */
     		iarg[6] = p->flags; /* int */
    @@ -2327,7 +2327,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		iarg[0] = p->sd; /* int */
     		uarg[1] = (intptr_t) p->iov; /* struct iovec * */
     		iarg[2] = p->iovlen; /* int */
    -		uarg[3] = (intptr_t) p->to; /* caddr_t */
    +		uarg[3] = (intptr_t) p->to; /* struct sockaddr * */
     		iarg[4] = p->tolen; /* __socklen_t */
     		uarg[5] = (intptr_t) p->sinfo; /* struct sctp_sndrcvinfo * */
     		iarg[6] = p->flags; /* int */
    @@ -2375,7 +2375,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	/* freebsd32_mmap */
     	case 477: {
     		struct freebsd32_mmap_args *p = params;
    -		uarg[0] = (intptr_t) p->addr; /* caddr_t */
    +		uarg[0] = (intptr_t) p->addr; /* void * */
     		uarg[1] = p->len; /* size_t */
     		iarg[2] = p->prot; /* int */
     		iarg[3] = p->flags; /* int */
    @@ -2443,7 +2443,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	/* freebsd32_mmap */
     	case 477: {
     		struct freebsd32_mmap_args *p = params;
    -		uarg[0] = (intptr_t) p->addr; /* caddr_t */
    +		uarg[0] = (intptr_t) p->addr; /* void * */
     		uarg[1] = p->len; /* size_t */
     		iarg[2] = p->prot; /* int */
     		iarg[3] = p->flags; /* int */
    @@ -3021,7 +3021,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		struct bindat_args *p = params;
     		iarg[0] = p->fd; /* int */
     		iarg[1] = p->s; /* int */
    -		uarg[2] = (intptr_t) p->name; /* caddr_t */
    +		uarg[2] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[3] = p->namelen; /* int */
     		*n_args = 4;
     		break;
    @@ -3031,7 +3031,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		struct connectat_args *p = params;
     		iarg[0] = p->fd; /* int */
     		iarg[1] = p->s; /* int */
    -		uarg[2] = (intptr_t) p->name; /* caddr_t */
    +		uarg[2] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[3] = p->namelen; /* int */
     		*n_args = 4;
     		break;
    @@ -3462,7 +3462,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		default:
     			break;
    @@ -3555,7 +3555,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "uint32_t";
    +			p = "userland void *";
     			break;
     		case 2:
     			p = "uint32_t";
    @@ -3564,7 +3564,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 4:
    -			p = "uint32_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 5:
     			p = "uint32_t";
    @@ -3580,7 +3580,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 2:
     			p = "userland int *";
    @@ -3596,7 +3596,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 2:
     			p = "userland int *";
    @@ -3612,7 +3612,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 2:
     			p = "userland int *";
    @@ -3696,7 +3696,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     	case 44:
     		switch(ndx) {
     		case 0:
    -			p = "caddr_t";
    +			p = "userland char *";
     			break;
     		case 1:
     			p = "size_t";
    @@ -4164,7 +4164,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 2:
     			p = "int";
    @@ -4193,7 +4193,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 2:
     			p = "int";
    @@ -4215,7 +4215,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland const void *";
     			break;
     		case 4:
     			p = "int";
    @@ -4276,7 +4276,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 4:
     			p = "userland int *";
    @@ -4431,7 +4431,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland const void *";
     			break;
     		case 2:
     			p = "size_t";
    @@ -4440,7 +4440,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 4:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 5:
     			p = "int";
    @@ -4546,7 +4546,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		default:
     			break;
    @@ -6996,13 +6996,13 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 2:
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 4:
     			p = "__socklen_t";
    @@ -7030,7 +7030,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 4:
     			p = "__socklen_t";
    @@ -7128,7 +7128,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     	case 477:
     		switch(ndx) {
     		case 0:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 1:
     			p = "size_t";
    @@ -7264,7 +7264,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     	case 477:
     		switch(ndx) {
     		case 0:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 1:
     			p = "size_t";
    @@ -8323,7 +8323,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 2:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 3:
     			p = "int";
    @@ -8342,7 +8342,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 2:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 3:
     			p = "int";
    diff --git a/sys/compat/freebsd32/syscalls.master b/sys/compat/freebsd32/syscalls.master
    index 36d2d65fa3ce..980c4194f184 100644
    --- a/sys/compat/freebsd32/syscalls.master
    +++ b/sys/compat/freebsd32/syscalls.master
    @@ -97,7 +97,7 @@
     20	AUE_GETPID	NOPROTO	{ pid_t getpid(void); }
     21	AUE_MOUNT	NOPROTO	{ int mount(const char *type, \
     				    const char *path, \
    -				    int flags, caddr_t data); }
    +				    int flags, void *data); }
     22	AUE_UMOUNT	NOPROTO	{ int unmount(const char *path, int flags); }
     23	AUE_SETUID	NOPROTO	{ int setuid(uid_t uid); }
     24	AUE_GETUID	NOPROTO	{ uid_t getuid(void); }
    @@ -108,14 +108,17 @@
     				    int flags); }
     28	AUE_SENDMSG	STD	{ int freebsd32_sendmsg(int s, struct msghdr32 *msg, \
     				    int flags); }
    -29	AUE_RECVFROM	STD	{ int freebsd32_recvfrom(int s, uint32_t buf, \
    -				    uint32_t len, int flags, uint32_t from, \
    +29	AUE_RECVFROM	STD	{ int freebsd32_recvfrom(int s, void *buf, \
    +				    uint32_t len, int flags, \
    +				    struct sockaddr *from, \
     				    uint32_t fromlenaddr); }
    -30	AUE_ACCEPT	NOPROTO	{ int accept(int s, caddr_t name, \
    +30	AUE_ACCEPT	NOPROTO	{ int accept(int s, struct sockaddr *name, \
     				    int *anamelen); }
    -31	AUE_GETPEERNAME	NOPROTO	{ int getpeername(int fdes, caddr_t asa, \
    +31	AUE_GETPEERNAME	NOPROTO	{ int getpeername(int fdes, \
    +				    struct sockaddr *asa, \
     				    int *alen); }
    -32	AUE_GETSOCKNAME	NOPROTO	{ int getsockname(int fdes, caddr_t asa, \
    +32	AUE_GETSOCKNAME	NOPROTO	{ int getsockname(int fdes, \
    +				    struct sockaddr *asa, \
     				    int *alen); }
     33	AUE_ACCESS	NOPROTO	{ int access(const char *path, int amode); }
     34	AUE_CHFLAGS	NOPROTO	{ int chflags(const char *path, u_long flags); }
    @@ -130,7 +133,7 @@
     41	AUE_DUP		NOPROTO	{ int dup(u_int fd); }
     42	AUE_PIPE	COMPAT10	{ int freebsd32_pipe(void); }
     43	AUE_GETEGID	NOPROTO	{ gid_t getegid(void); }
    -44	AUE_PROFILE	NOPROTO	{ int profil(caddr_t samples, size_t size, \
    +44	AUE_PROFILE	NOPROTO	{ int profil(char *samples, size_t size, \
     				    size_t offset, u_int scale); }
     45	AUE_KTRACE	NOPROTO	{ int ktrace(const char *fname, int ops, \
     				    int facs, int pid); }
    @@ -214,7 +217,8 @@
     				    int prio); }
     97	AUE_SOCKET	NOPROTO	{ int socket(int domain, int type, \
     				    int protocol); }
    -98	AUE_CONNECT	NOPROTO	{ int connect(int s, caddr_t name, \
    +98	AUE_CONNECT	NOPROTO	{ int connect(int s, \
    +				    const struct sockaddr *name, \
     				    int namelen); }
     99	AUE_NULL	OBSOL	oaccept
     100	AUE_GETPRIORITY	NOPROTO	{ int getpriority(int which, int who); }
    @@ -222,10 +226,10 @@
     102	AUE_NULL	OBSOL	orecv
     103	AUE_SIGRETURN	COMPAT	{ int freebsd32_sigreturn( \
     				    struct ia32_sigcontext3 *sigcntxp); }
    -104	AUE_BIND	NOPROTO	{ int bind(int s, caddr_t name, \
    +104	AUE_BIND	NOPROTO	{ int bind(int s, const struct sockaddr *name, \
     				    int namelen); }
     105	AUE_SETSOCKOPT	NOPROTO	{ int setsockopt(int s, int level, \
    -				    int name, caddr_t val, int valsize); }
    +				    int name, const void *val, int valsize); }
     106	AUE_LISTEN	NOPROTO	{ int listen(int s, int backlog); }
     107	AUE_NULL	OBSOL	vtimes
     108	AUE_O_SIGVEC	COMPAT	{ int freebsd32_sigvec(int signum, \
    @@ -246,7 +250,7 @@
     117	AUE_GETRUSAGE	STD	{ int freebsd32_getrusage(int who, \
     				    struct rusage32 *rusage); }
     118	AUE_GETSOCKOPT	NOPROTO	{ int getsockopt(int s, int level, \
    -				    int name, caddr_t val, int *avalsize); }
    +				    int name, void *val, int *avalsize); }
     119	AUE_NULL	UNIMPL	resuba (BSD/OS 2.x)
     120	AUE_READV	STD	{ int freebsd32_readv(int fd, \
     				    struct iovec32 *iovp, u_int iovcnt); }
    @@ -267,8 +271,9 @@
     130	AUE_FTRUNCATE	COMPAT|NOPROTO	{ int ftruncate(int fd, int length); }
     131	AUE_FLOCK	NOPROTO	{ int flock(int fd, int how); }
     132	AUE_MKFIFO	NOPROTO	{ int mkfifo(const char *path, mode_t mode); }
    -133	AUE_SENDTO	NOPROTO	{ int sendto(int s, caddr_t buf, \
    -				    size_t len, int flags, caddr_t to, \
    +133	AUE_SENDTO	NOPROTO	{ int sendto(int s, const void *buf, \
    +				    size_t len, int flags, \
    +				    const struct sockaddr *to, \
     				    int tolen); }
     134	AUE_SHUTDOWN	NOPROTO	{ int shutdown(int s, int how); }
     135	AUE_SOCKETPAIR	NOPROTO	{ int socketpair(int domain, int type, \
    @@ -289,7 +294,7 @@
     146	AUE_KILLPG	OBSOL	killpg
     147	AUE_SETSID	NOPROTO	{ int setsid(void); }
     148	AUE_QUOTACTL	NOPROTO	{ int quotactl(const char *path, int cmd, \
    -				    int uid, caddr_t arg); }
    +				    int uid, void *arg); }
     149	AUE_O_QUOTA	OBSOL oquota
     150	AUE_GETSOCKNAME	OBSOL ogetsockname
     
    @@ -368,7 +373,7 @@
     				    __setrlimit_args int
     196	AUE_GETDIRENTRIES COMPAT11 { int freebsd32_getdirentries(int fd, \
     				    char *buf, u_int count, int32_t *basep); }
    -197	AUE_MMAP	COMPAT6	{ caddr_t freebsd32_mmap(caddr_t addr, \
    +197	AUE_MMAP	COMPAT6	{ caddr_t freebsd32_mmap(void *addr, \
     				    size_t len, int prot, int flags, int fd, \
     				    int pad, uint32_t pos1, uint32_t pos2); }
     198	AUE_NULL	NOPROTO	{ int nosys(void); } __syscall \
    @@ -852,11 +857,12 @@
     469	AUE_NULL	UNIMPL	__getpath_fromfd
     470	AUE_NULL	UNIMPL	__getpath_fromaddr
     471	AUE_SCTP_PEELOFF	NOPROTO|NOSTD	{ int sctp_peeloff(int sd, uint32_t name); }
    -472	AUE_SCTP_GENERIC_SENDMSG	NOPROTO|NOSTD	{ int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \
    -				    caddr_t to, __socklen_t tolen, \
    +472	AUE_SCTP_GENERIC_SENDMSG	NOPROTO|NOSTD	{ int sctp_generic_sendmsg( \
    +				    int sd, void *msg, int mlen, \
    +				    struct sockaddr *to, __socklen_t tolen, \
     				    struct sctp_sndrcvinfo *sinfo, int flags); }
     473	AUE_SCTP_GENERIC_SENDMSG_IOV	NOPROTO|NOSTD	{ int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \
    -				    caddr_t to, __socklen_t tolen, \
    +				    struct sockaddr *to, __socklen_t tolen, \
     				    struct sctp_sndrcvinfo *sinfo, int flags); }
     474	AUE_SCTP_GENERIC_RECVMSG	NOPROTO|NOSTD	{ int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \
     				    struct sockaddr * from, __socklen_t *fromlenaddr, \
    @@ -870,7 +876,7 @@
     				    const void *buf, size_t nbyte, \
     				    int pad, \
     				    uint32_t offset1, uint32_t offset2); }
    -477	AUE_MMAP	STD 	{ caddr_t freebsd32_mmap(caddr_t addr, \
    +477	AUE_MMAP	STD 	{ caddr_t freebsd32_mmap(void *addr, \
     				    size_t len, int prot, int flags, int fd, \
     				    int pad, \
     				    uint32_t pos1, uint32_t pos2); }
    @@ -891,7 +897,7 @@
     476	AUE_PWRITE	STD	{ ssize_t freebsd32_pwrite(int fd, \
     				    const void *buf, size_t nbyte, \
     				    uint32_t offset1, uint32_t offset2); }
    -477	AUE_MMAP	STD 	{ caddr_t freebsd32_mmap(caddr_t addr, \
    +477	AUE_MMAP	STD 	{ caddr_t freebsd32_mmap(void *addr, \
     				    size_t len, int prot, int flags, int fd, \
     				    uint32_t pos1, uint32_t pos2); }
     478	AUE_LSEEK	STD	{ off_t freebsd32_lseek(int fd, \
    @@ -1054,9 +1060,11 @@
     				    uint32_t fcntlrights); }
     537	AUE_CAP_FCNTLS_GET	NOPROTO	{ int cap_fcntls_get(int fd, \
     				    uint32_t *fcntlrightsp); }
    -538	AUE_BINDAT	NOPROTO	{ int bindat(int fd, int s, caddr_t name, \
    +538	AUE_BINDAT	NOPROTO	{ int bindat(int fd, int s, \
    +				    const struct sockaddr *name, \
     				    int namelen); }
    -539	AUE_CONNECTAT	NOPROTO	{ int connectat(int fd, int s, caddr_t name, \
    +539	AUE_CONNECTAT	NOPROTO	{ int connectat(int fd, int s, \
    +				    const struct sockaddr *name, \
     				    int namelen); }
     540	AUE_CHFLAGSAT	NOPROTO	{ int chflagsat(int fd, const char *path, \
     				    u_long flags, int atflag); }
    diff --git a/sys/compat/linux/linux_common.c b/sys/compat/linux/linux_common.c
    index b9e35311bdfe..551823d7e0de 100644
    --- a/sys/compat/linux/linux_common.c
    +++ b/sys/compat/linux/linux_common.c
    @@ -35,9 +35,11 @@ __FBSDID("$FreeBSD$");
     #include 
     #include 
     #include 
    +#include 
     #include 
     
     #include 
    +#include 
     #include 
     #include 
     
    @@ -48,6 +50,11 @@ MODULE_VERSION(linux_common, 1);
     
     SET_DECLARE(linux_device_handler_set, struct linux_device_handler);
     
    +TAILQ_HEAD(, linux_ioctl_handler_element) linux_ioctl_handlers =
    +    TAILQ_HEAD_INITIALIZER(linux_ioctl_handlers);
    +struct sx linux_ioctl_sx;
    +SX_SYSINIT(linux_ioctl, &linux_ioctl_sx, "Linux ioctl handlers");
    +
     static eventhandler_tag linux_exec_tag;
     static eventhandler_tag linux_thread_dtor_tag;
     static eventhandler_tag	linux_exit_tag;
    diff --git a/sys/compat/linux/linux_ioctl.c b/sys/compat/linux/linux_ioctl.c
    index cea8721f096e..0a8e5087984b 100644
    --- a/sys/compat/linux/linux_ioctl.c
    +++ b/sys/compat/linux/linux_ioctl.c
    @@ -161,17 +161,19 @@ DATA_SET(linux_ioctl_handler_set, video2_handler);
     DATA_SET(linux_ioctl_handler_set, fbsd_usb);
     DATA_SET(linux_ioctl_handler_set, evdev_handler);
     
    -struct handler_element
    -{
    -	TAILQ_ENTRY(handler_element) list;
    -	int	(*func)(struct thread *, struct linux_ioctl_args *);
    -	int	low, high, span;
    -};
    -
    -static TAILQ_HEAD(, handler_element) handlers =
    -    TAILQ_HEAD_INITIALIZER(handlers);
    +#ifdef __i386__
    +static TAILQ_HEAD(, linux_ioctl_handler_element) linux_ioctl_handlers =
    +    TAILQ_HEAD_INITIALIZER(linux_ioctl_handlers);
     static struct sx linux_ioctl_sx;
     SX_SYSINIT(linux_ioctl, &linux_ioctl_sx, "Linux ioctl handlers");
    +#else
    +extern TAILQ_HEAD(, linux_ioctl_handler_element) linux_ioctl_handlers;
    +extern struct sx linux_ioctl_sx;
    +#endif
    +#ifdef COMPAT_LINUX32
    +static TAILQ_HEAD(, linux_ioctl_handler_element) linux32_ioctl_handlers =
    +    TAILQ_HEAD_INITIALIZER(linux32_ioctl_handlers);
    +#endif
     
     /*
      * hdio related ioctls for VMWare support
    @@ -3684,7 +3686,7 @@ int
     linux_ioctl(struct thread *td, struct linux_ioctl_args *args)
     {
     	struct file *fp;
    -	struct handler_element *he;
    +	struct linux_ioctl_handler_element *he;
     	int error, cmd;
     
     #ifdef DEBUG
    @@ -3705,7 +3707,20 @@ linux_ioctl(struct thread *td, struct linux_ioctl_args *args)
     	cmd = args->cmd & 0xffff;
     	sx_slock(&linux_ioctl_sx);
     	mtx_lock(&Giant);
    -	TAILQ_FOREACH(he, &handlers, list) {
    +#ifdef COMPAT_LINUX32
    +	TAILQ_FOREACH(he, &linux32_ioctl_handlers, list) {
    +		if (cmd >= he->low && cmd <= he->high) {
    +			error = (*he->func)(td, args);
    +			if (error != ENOIOCTL) {
    +				mtx_unlock(&Giant);
    +				sx_sunlock(&linux_ioctl_sx);
    +				fdrop(fp, td);
    +				return (error);
    +			}
    +		}
    +	}
    +#endif
    +	TAILQ_FOREACH(he, &linux_ioctl_handlers, list) {
     		if (cmd >= he->low && cmd <= he->high) {
     			error = (*he->func)(td, args);
     			if (error != ENOIOCTL) {
    @@ -3737,7 +3752,7 @@ linux_ioctl(struct thread *td, struct linux_ioctl_args *args)
     int
     linux_ioctl_register_handler(struct linux_ioctl_handler *h)
     {
    -	struct handler_element *he, *cur;
    +	struct linux_ioctl_handler_element *he, *cur;
     
     	if (h == NULL || h->func == NULL)
     		return (EINVAL);
    @@ -3747,7 +3762,7 @@ linux_ioctl_register_handler(struct linux_ioctl_handler *h)
     	 * create a new element.
     	 */
     	sx_xlock(&linux_ioctl_sx);
    -	TAILQ_FOREACH(he, &handlers, list) {
    +	TAILQ_FOREACH(he, &linux_ioctl_handlers, list) {
     		if (he->func == h->func)
     			break;
     	}
    @@ -3756,7 +3771,7 @@ linux_ioctl_register_handler(struct linux_ioctl_handler *h)
     		    M_LINUX, M_WAITOK);
     		he->func = h->func;
     	} else
    -		TAILQ_REMOVE(&handlers, he, list);
    +		TAILQ_REMOVE(&linux_ioctl_handlers, he, list);
     
     	/* Initialize range information. */
     	he->low = h->low;
    @@ -3764,14 +3779,14 @@ linux_ioctl_register_handler(struct linux_ioctl_handler *h)
     	he->span = h->high - h->low + 1;
     
     	/* Add the element to the list, sorted on span. */
    -	TAILQ_FOREACH(cur, &handlers, list) {
    +	TAILQ_FOREACH(cur, &linux_ioctl_handlers, list) {
     		if (cur->span > he->span) {
     			TAILQ_INSERT_BEFORE(cur, he, list);
     			sx_xunlock(&linux_ioctl_sx);
     			return (0);
     		}
     	}
    -	TAILQ_INSERT_TAIL(&handlers, he, list);
    +	TAILQ_INSERT_TAIL(&linux_ioctl_handlers, he, list);
     	sx_xunlock(&linux_ioctl_sx);
     
     	return (0);
    @@ -3780,15 +3795,15 @@ linux_ioctl_register_handler(struct linux_ioctl_handler *h)
     int
     linux_ioctl_unregister_handler(struct linux_ioctl_handler *h)
     {
    -	struct handler_element *he;
    +	struct linux_ioctl_handler_element *he;
     
     	if (h == NULL || h->func == NULL)
     		return (EINVAL);
     
     	sx_xlock(&linux_ioctl_sx);
    -	TAILQ_FOREACH(he, &handlers, list) {
    +	TAILQ_FOREACH(he, &linux_ioctl_handlers, list) {
     		if (he->func == h->func) {
    -			TAILQ_REMOVE(&handlers, he, list);
    +			TAILQ_REMOVE(&linux_ioctl_handlers, he, list);
     			sx_xunlock(&linux_ioctl_sx);
     			free(he, M_LINUX);
     			return (0);
    @@ -3798,3 +3813,69 @@ linux_ioctl_unregister_handler(struct linux_ioctl_handler *h)
     
     	return (EINVAL);
     }
    +
    +#ifdef COMPAT_LINUX32
    +int
    +linux32_ioctl_register_handler(struct linux_ioctl_handler *h)
    +{
    +	struct linux_ioctl_handler_element *he, *cur;
    +
    +	if (h == NULL || h->func == NULL)
    +		return (EINVAL);
    +
    +	/*
    +	 * Reuse the element if the handler is already on the list, otherwise
    +	 * create a new element.
    +	 */
    +	sx_xlock(&linux_ioctl_sx);
    +	TAILQ_FOREACH(he, &linux32_ioctl_handlers, list) {
    +		if (he->func == h->func)
    +			break;
    +	}
    +	if (he == NULL) {
    +		he = malloc(sizeof(*he), M_LINUX, M_WAITOK);
    +		he->func = h->func;
    +	} else
    +		TAILQ_REMOVE(&linux32_ioctl_handlers, he, list);
    +
    +	/* Initialize range information. */
    +	he->low = h->low;
    +	he->high = h->high;
    +	he->span = h->high - h->low + 1;
    +
    +	/* Add the element to the list, sorted on span. */
    +	TAILQ_FOREACH(cur, &linux32_ioctl_handlers, list) {
    +		if (cur->span > he->span) {
    +			TAILQ_INSERT_BEFORE(cur, he, list);
    +			sx_xunlock(&linux_ioctl_sx);
    +			return (0);
    +		}
    +	}
    +	TAILQ_INSERT_TAIL(&linux32_ioctl_handlers, he, list);
    +	sx_xunlock(&linux_ioctl_sx);
    +
    +	return (0);
    +}
    +
    +int
    +linux32_ioctl_unregister_handler(struct linux_ioctl_handler *h)
    +{
    +	struct linux_ioctl_handler_element *he;
    +
    +	if (h == NULL || h->func == NULL)
    +		return (EINVAL);
    +
    +	sx_xlock(&linux_ioctl_sx);
    +	TAILQ_FOREACH(he, &linux32_ioctl_handlers, list) {
    +		if (he->func == h->func) {
    +			TAILQ_REMOVE(&linux32_ioctl_handlers, he, list);
    +			sx_xunlock(&linux_ioctl_sx);
    +			free(he, M_LINUX);
    +			return (0);
    +		}
    +	}
    +	sx_xunlock(&linux_ioctl_sx);
    +
    +	return (EINVAL);
    +}
    +#endif
    diff --git a/sys/compat/linux/linux_ioctl.h b/sys/compat/linux/linux_ioctl.h
    index d8aaadd62ddd..519f55e6c161 100644
    --- a/sys/compat/linux/linux_ioctl.h
    +++ b/sys/compat/linux/linux_ioctl.h
    @@ -770,7 +770,18 @@ struct linux_ioctl_handler {
     	int	low, high;
     };
     
    +struct linux_ioctl_handler_element
    +{
    +	TAILQ_ENTRY(linux_ioctl_handler_element) list;
    +	int	(*func)(struct thread *, struct linux_ioctl_args *);
    +	int	low, high, span;
    +};
    +
     int	linux_ioctl_register_handler(struct linux_ioctl_handler *h);
     int	linux_ioctl_unregister_handler(struct linux_ioctl_handler *h);
    +#ifdef COMPAT_LINUX32
    +int	linux32_ioctl_register_handler(struct linux_ioctl_handler *h);
    +int	linux32_ioctl_unregister_handler(struct linux_ioctl_handler *h);
    +#endif
     
     #endif /* !_LINUX_IOCTL_H_ */
    diff --git a/sys/compat/linux/linux_socket.c b/sys/compat/linux/linux_socket.c
    index 415bc1024252..15a137a5dd73 100644
    --- a/sys/compat/linux/linux_socket.c
    +++ b/sys/compat/linux/linux_socket.c
    @@ -1520,7 +1520,7 @@ linux_setsockopt(struct thread *td, struct linux_setsockopt_args *args)
     		int s;
     		int level;
     		int name;
    -		caddr_t val;
    +		const void *val;
     		int valsize;
     	} */ bsd_args;
     	l_timeval linux_tv;
    @@ -1570,10 +1570,11 @@ linux_setsockopt(struct thread *td, struct linux_setsockopt_args *args)
     	bsd_args.valsize = args->optlen;
     
     	if (name == IPV6_NEXTHOP) {
    -		linux_to_bsd_sockaddr((struct sockaddr *)bsd_args.val,
    -			bsd_args.valsize);
    +		linux_to_bsd_sockaddr(__DECONST(struct sockaddr *,
    +		    bsd_args.val), bsd_args.valsize);
     		error = sys_setsockopt(td, &bsd_args);
    -		bsd_to_linux_sockaddr((struct sockaddr *)bsd_args.val);
    +		bsd_to_linux_sockaddr(__DECONST(struct sockaddr *,
    +		    bsd_args.val));
     	} else
     		error = sys_setsockopt(td, &bsd_args);
     
    diff --git a/sys/conf/files b/sys/conf/files
    index 1ca735ba9957..9294d67aa172 100644
    --- a/sys/conf/files
    +++ b/sys/conf/files
    @@ -3824,6 +3824,7 @@ kern/kern_thread.c		standard
     kern/kern_time.c		standard
     kern/kern_timeout.c		standard
     kern/kern_tslog.c		optional tslog
    +kern/kern_ubsan.c		optional kubsan
     kern/kern_umtx.c		standard
     kern/kern_uuid.c		standard
     kern/kern_xxx.c			standard
    diff --git a/sys/conf/kern.post.mk b/sys/conf/kern.post.mk
    index 98d179446905..398dc7165984 100644
    --- a/sys/conf/kern.post.mk
    +++ b/sys/conf/kern.post.mk
    @@ -28,6 +28,10 @@ MKMODULESENV+=	WITH_CTF="${WITH_CTF}"
     MKMODULESENV+=	WITH_EXTRA_TCP_STACKS="${WITH_EXTRA_TCP_STACKS}"
     .endif
     
    +.if defined(SAN_CFLAGS)
    +MKMODULESENV+=	SAN_CFLAGS="${SAN_CFLAGS}"
    +.endif
    +
     # Allow overriding the kernel debug directory, so kernel and user debug may be
     # installed in different directories. Setting it to "" restores the historical
     # behavior of installing debug files in the kernel directory.
    diff --git a/sys/conf/kern.pre.mk b/sys/conf/kern.pre.mk
    index 38a9c14ddbb5..bca9ff79e756 100644
    --- a/sys/conf/kern.pre.mk
    +++ b/sys/conf/kern.pre.mk
    @@ -113,6 +113,12 @@ PROF=		-pg
     .endif
     DEFINED_PROF=	${PROF}
     
    +KUBSAN_ENABLED!=	grep KUBSAN opt_global.h || true ; echo
    +.if !empty(KUBSAN_ENABLED)
    +SAN_CFLAGS+=	-fsanitize=undefined
    +.endif
    +CFLAGS+=	${SAN_CFLAGS}
    +
     # Put configuration-specific C flags last (except for ${PROF}) so that they
     # can override the others.
     CFLAGS+=	${CONF_CFLAGS}
    diff --git a/sys/conf/kmod.mk b/sys/conf/kmod.mk
    index a357c565ab5f..4f239d10bd3a 100644
    --- a/sys/conf/kmod.mk
    +++ b/sys/conf/kmod.mk
    @@ -377,6 +377,9 @@ ${_src}:
     .endfor
     .endif
     
    +# Add the sanitizer C flags
    +CFLAGS+=	${SAN_CFLAGS}
    +
     # Respect configuration-specific C flags.
     CFLAGS+=	${ARCH_FLAGS} ${CONF_CFLAGS}
     
    diff --git a/sys/conf/options b/sys/conf/options
    index 9d86cbdfd663..240b1d606df5 100644
    --- a/sys/conf/options
    +++ b/sys/conf/options
    @@ -232,6 +232,9 @@ UMTX_CHAINS	opt_global.h
     VERBOSE_SYSINIT
     ZSTDIO		opt_zstdio.h
     
    +# Sanitizers
    +KUBSAN		opt_global.h
    +
     # POSIX kernel options
     P1003_1B_MQUEUE			opt_posix.h
     P1003_1B_SEMAPHORES		opt_posix.h
    diff --git a/sys/dev/cxgbe/adapter.h b/sys/dev/cxgbe/adapter.h
    index dbebe5b0ece7..52734ed98246 100644
    --- a/sys/dev/cxgbe/adapter.h
    +++ b/sys/dev/cxgbe/adapter.h
    @@ -574,6 +574,7 @@ struct sge_txq {
     	uint64_t txpkts1_wrs;	/* # of type1 coalesced tx work requests */
     	uint64_t txpkts0_pkts;	/* # of frames in type0 coalesced tx WRs */
     	uint64_t txpkts1_pkts;	/* # of frames in type1 coalesced tx WRs */
    +	uint64_t raw_wrs;	/* # of raw work requests (alloc_wr_mbuf) */
     
     	/* stats for not-that-common events */
     } __aligned(CACHE_LINE_SIZE);
    @@ -1170,6 +1171,7 @@ void t4_intr_err(void *);
     void t4_intr_evt(void *);
     void t4_wrq_tx_locked(struct adapter *, struct sge_wrq *, struct wrqe *);
     void t4_update_fl_bufsize(struct ifnet *);
    +struct mbuf *alloc_wr_mbuf(int, int);
     int parse_pkt(struct adapter *, struct mbuf **);
     void *start_wrq_wr(struct sge_wrq *, int, struct wrq_cookie *);
     void commit_wrq_wr(struct sge_wrq *, void *, struct wrq_cookie *);
    diff --git a/sys/dev/cxgbe/t4_main.c b/sys/dev/cxgbe/t4_main.c
    index 7593f9366f8f..3090bca5565a 100644
    --- a/sys/dev/cxgbe/t4_main.c
    +++ b/sys/dev/cxgbe/t4_main.c
    @@ -529,9 +529,9 @@ struct intrs_and_queues {
     
     static void setup_memwin(struct adapter *);
     static void position_memwin(struct adapter *, int, uint32_t);
    -static int validate_mem_range(struct adapter *, uint32_t, int);
    +static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
     static int fwmtype_to_hwmtype(int);
    -static int validate_mt_off_len(struct adapter *, int, uint32_t, int,
    +static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
         uint32_t *);
     static int fixup_devlog_params(struct adapter *);
     static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
    @@ -2826,14 +2826,14 @@ t4_range_cmp(const void *a, const void *b)
      * the card's address space.
      */
     static int
    -validate_mem_range(struct adapter *sc, uint32_t addr, int len)
    +validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
     {
     	struct t4_range mem_ranges[4], *r, *next;
     	uint32_t em, addr_len;
     	int i, n, remaining;
     
     	/* Memory can only be accessed in naturally aligned 4 byte units */
    -	if (addr & 3 || len & 3 || len <= 0)
    +	if (addr & 3 || len & 3 || len == 0)
     		return (EINVAL);
     
     	/* Enabled memories */
    @@ -2972,7 +2972,7 @@ fwmtype_to_hwmtype(int mtype)
      * the start of the range is returned in addr.
      */
     static int
    -validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, int len,
    +validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
         uint32_t *addr)
     {
     	uint32_t em, addr_len, maddr;
    @@ -9804,6 +9804,7 @@ t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
     					txq->txpkts1_wrs = 0;
     					txq->txpkts0_pkts = 0;
     					txq->txpkts1_pkts = 0;
    +					txq->raw_wrs = 0;
     					mp_ring_reset_stats(txq->r);
     				}
     
    diff --git a/sys/dev/cxgbe/t4_sge.c b/sys/dev/cxgbe/t4_sge.c
    index 643eb29ffb9a..3660e333654e 100644
    --- a/sys/dev/cxgbe/t4_sge.c
    +++ b/sys/dev/cxgbe/t4_sge.c
    @@ -82,6 +82,9 @@ __FBSDID("$FreeBSD$");
     #define RX_COPY_THRESHOLD MINCLSIZE
     #endif
     
    +/* Internal mbuf flags stored in PH_loc.eight[1]. */
    +#define	MC_RAW_WR		0x02
    +
     /*
      * Ethernet frames are DMA'd at this byte offset into the freelist buffer.
      * 0-7 are valid values.
    @@ -270,6 +273,7 @@ static inline u_int txpkt_len16(u_int, u_int);
     static inline u_int txpkt_vm_len16(u_int, u_int);
     static inline u_int txpkts0_len16(u_int);
     static inline u_int txpkts1_len16(void);
    +static u_int write_raw_wr(struct sge_txq *, void *, struct mbuf *, u_int);
     static u_int write_txpkt_wr(struct sge_txq *, struct fw_eth_tx_pkt_wr *,
         struct mbuf *, u_int);
     static u_int write_txpkt_vm_wr(struct adapter *, struct sge_txq *,
    @@ -2195,6 +2199,22 @@ set_mbuf_nsegs(struct mbuf *m, uint8_t nsegs)
     	m->m_pkthdr.l5hlen = nsegs;
     }
     
    +static inline int
    +mbuf_cflags(struct mbuf *m)
    +{
    +
    +	M_ASSERTPKTHDR(m);
    +	return (m->m_pkthdr.PH_loc.eight[4]);
    +}
    +
    +static inline void
    +set_mbuf_cflags(struct mbuf *m, uint8_t flags)
    +{
    +
    +	M_ASSERTPKTHDR(m);
    +	m->m_pkthdr.PH_loc.eight[4] = flags;
    +}
    +
     static inline int
     mbuf_len16(struct mbuf *m)
     {
    @@ -2276,6 +2296,31 @@ needs_eo(struct mbuf *m)
     }
     #endif
     
    +/*
    + * Try to allocate an mbuf to contain a raw work request.  To make it
    + * easy to construct the work request, don't allocate a chain but a
    + * single mbuf.
    + */
    +struct mbuf *
    +alloc_wr_mbuf(int len, int how)
    +{
    +	struct mbuf *m;
    +
    +	if (len <= MHLEN)
    +		m = m_gethdr(how, MT_DATA);
    +	else if (len <= MCLBYTES)
    +		m = m_getcl(how, MT_DATA, M_PKTHDR);
    +	else
    +		m = NULL;
    +	if (m == NULL)
    +		return (NULL);
    +	m->m_pkthdr.len = len;
    +	m->m_len = len;
    +	set_mbuf_cflags(m, MC_RAW_WR);
    +	set_mbuf_len16(m, howmany(len, 16));
    +	return (m);
    +}
    +
     static inline int
     needs_tso(struct mbuf *m)
     {
    @@ -2449,6 +2494,7 @@ parse_pkt(struct adapter *sc, struct mbuf **mp)
     		goto restart;
     	}
     	set_mbuf_nsegs(m0, nsegs);
    +	set_mbuf_cflags(m0, 0);
     	if (sc->flags & IS_VF)
     		set_mbuf_len16(m0, txpkt_vm_len16(nsegs, needs_tso(m0)));
     	else
    @@ -2691,7 +2737,7 @@ cannot_use_txpkts(struct mbuf *m)
     {
     	/* maybe put a GL limit too, to avoid silliness? */
     
    -	return (needs_tso(m));
    +	return (needs_tso(m) || (mbuf_cflags(m) & MC_RAW_WR) != 0);
     }
     
     static inline int
    @@ -2701,6 +2747,21 @@ discard_tx(struct sge_eq *eq)
     	return ((eq->flags & (EQ_ENABLED | EQ_QFLUSH)) != EQ_ENABLED);
     }
     
    +static inline int
    +wr_can_update_eq(struct fw_eth_tx_pkts_wr *wr)
    +{
    +
    +	switch (G_FW_WR_OP(be32toh(wr->op_pkd))) {
    +	case FW_ULPTX_WR:
    +	case FW_ETH_TX_PKT_WR:
    +	case FW_ETH_TX_PKTS_WR:
    +	case FW_ETH_TX_PKT_VM_WR:
    +		return (1);
    +	default:
    +		return (0);
    +	}
    +}
    +
     /*
      * r->items[cidx] to r->items[pidx], with a wraparound at r->size, are ready to
      * be consumed.  Return the actual number consumed.  0 indicates a stall.
    @@ -2796,6 +2857,10 @@ eth_tx(struct mp_ring *r, u_int cidx, u_int pidx)
     			n = write_txpkts_wr(txq, wr, m0, &txp, available);
     			total += txp.npkt;
     			remaining -= txp.npkt;
    +		} else if (mbuf_cflags(m0) & MC_RAW_WR) {
    +			total++;
    +			remaining--;
    +			n = write_raw_wr(txq, (void *)wr, m0, available);
     		} else {
     			total++;
     			remaining--;
    @@ -2808,14 +2873,17 @@ eth_tx(struct mp_ring *r, u_int cidx, u_int pidx)
     		dbdiff += n;
     		IDXINCR(eq->pidx, n, eq->sidx);
     
    -		if (total_available_tx_desc(eq) < eq->sidx / 4 &&
    -		    atomic_cmpset_int(&eq->equiq, 0, 1)) {
    -			wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUIQ |
    -			    F_FW_WR_EQUEQ);
    -			eq->equeqidx = eq->pidx;
    -		} else if (IDXDIFF(eq->pidx, eq->equeqidx, eq->sidx) >= 32) {
    -			wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUEQ);
    -			eq->equeqidx = eq->pidx;
    +		if (wr_can_update_eq(wr)) {
    +			if (total_available_tx_desc(eq) < eq->sidx / 4 &&
    +			    atomic_cmpset_int(&eq->equiq, 0, 1)) {
    +				wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUIQ |
    +				    F_FW_WR_EQUEQ);
    +				eq->equeqidx = eq->pidx;
    +			} else if (IDXDIFF(eq->pidx, eq->equeqidx, eq->sidx) >=
    +			    32) {
    +				wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUEQ);
    +				eq->equeqidx = eq->pidx;
    +			}
     		}
     
     		if (dbdiff >= 16 && remaining >= 4) {
    @@ -4010,6 +4078,8 @@ alloc_txq(struct vi_info *vi, struct sge_txq *txq, int idx,
     	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts1_pkts",
     	    CTLFLAG_RD, &txq->txpkts1_pkts,
     	    "# of frames tx'd using type1 txpkts work requests");
    +	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "raw_wrs", CTLFLAG_RD,
    +	    &txq->raw_wrs, "# of raw work requests (non-packets)");
     
     	SYSCTL_ADD_COUNTER_U64(&vi->ctx, children, OID_AUTO, "r_enqueues",
     	    CTLFLAG_RD, &txq->r->enqueues,
    @@ -4556,6 +4626,39 @@ write_txpkt_vm_wr(struct adapter *sc, struct sge_txq *txq,
     	return (ndesc);
     }
     
    +/*
    + * Write a raw WR to the hardware descriptors, update the software
    + * descriptor, and advance the pidx.  It is guaranteed that enough
    + * descriptors are available.
    + *
    + * The return value is the # of hardware descriptors used.
    + */
    +static u_int
    +write_raw_wr(struct sge_txq *txq, void *wr, struct mbuf *m0, u_int available)
    +{
    +	struct sge_eq *eq = &txq->eq;
    +	struct tx_sdesc *txsd;
    +	struct mbuf *m;
    +	caddr_t dst;
    +	int len16, ndesc;
    +
    +	len16 = mbuf_len16(m0);
    +	ndesc = howmany(len16, EQ_ESIZE / 16);
    +	MPASS(ndesc <= available);
    +
    +	dst = wr;
    +	for (m = m0; m != NULL; m = m->m_next)
    +		copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);
    +
    +	txq->raw_wrs++;
    +
    +	txsd = &txq->sdesc[eq->pidx];
    +	txsd->m = m0;
    +	txsd->desc_used = ndesc;
    +
    +	return (ndesc);
    +}
    +
     /*
      * Write a txpkt WR for this packet to the hardware descriptors, update the
      * software descriptor, and advance the pidx.  It is guaranteed that enough
    diff --git a/sys/dev/hwpmc/hwpmc_mod.c b/sys/dev/hwpmc/hwpmc_mod.c
    index f94f645b2e39..f0c0d41fa2b1 100644
    --- a/sys/dev/hwpmc/hwpmc_mod.c
    +++ b/sys/dev/hwpmc/hwpmc_mod.c
    @@ -4949,8 +4949,11 @@ pmc_process_samples(int cpu, ring_type_t ring)
     
     		/* If there is a pending AST wait for completion */
     		if (ps->ps_nsamples == PMC_USER_CALLCHAIN_PENDING) {
    -			/* if sample is more than 65 ms old, drop it */
    -			if (ticks - ps->ps_ticks > (hz >> 4)) {
    +			/* if we've been waiting more than 1 tick to 
    +			 * collect a callchain for this record then
    +			 * drop it and move on.
    +			 */
    +			if (ticks - ps->ps_ticks > 1) {
     				/*
     				 * track how often we hit this as it will
     				 * preferentially lose user samples
    diff --git a/sys/dev/mrsas/mrsas.h b/sys/dev/mrsas/mrsas.h
    index 672b177ba908..280e1ed2f27b 100644
    --- a/sys/dev/mrsas/mrsas.h
    +++ b/sys/dev/mrsas/mrsas.h
    @@ -612,8 +612,8 @@ typedef union {
     
     #define	mrsas_atomic_read(v)	atomic_load_acq_int(&(v)->val)
     #define	mrsas_atomic_set(v,i)	atomic_store_rel_int(&(v)->val, i)
    -#define	mrsas_atomic_dec(v)	atomic_fetchadd_int(&(v)->val, -1)
    -#define	mrsas_atomic_inc(v)	atomic_fetchadd_int(&(v)->val, 1)
    +#define	mrsas_atomic_dec(v)	atomic_subtract_int(&(v)->val, 1)
    +#define	mrsas_atomic_inc(v)	atomic_add_int(&(v)->val, 1)
     
     /* IOCInit Request message */
     typedef struct _MPI2_IOC_INIT_REQUEST {
    diff --git a/sys/dev/usb/controller/dwc_otg.c b/sys/dev/usb/controller/dwc_otg.c
    index 6c7b52fe76a6..35ce4eee52df 100644
    --- a/sys/dev/usb/controller/dwc_otg.c
    +++ b/sys/dev/usb/controller/dwc_otg.c
    @@ -1432,6 +1432,19 @@ dwc_otg_host_data_rx(struct dwc_otg_softc *sc, struct dwc_otg_td *td)
     					goto receive_pkt;
     				}
     			} else if (td->ep_type == UE_ISOCHRONOUS) {
    +				if (td->hcsplt != 0) {
    +					/*
    +					 * Sometimes the complete
    +					 * split packet may be queued
    +					 * too early and the
    +					 * transaction translator will
    +					 * return a NAK. Ignore
    +					 * this message and retry the
    +					 * complete split instead.
    +					 */
    +					DPRINTF("Retrying complete split\n");
    +					goto receive_pkt;
    +				}
     				goto complete;
     			}
     			td->did_nak = 1;
    diff --git a/sys/fs/nfsclient/nfs_clvfsops.c b/sys/fs/nfsclient/nfs_clvfsops.c
    index 96f93c060aba..d3587e89c552 100644
    --- a/sys/fs/nfsclient/nfs_clvfsops.c
    +++ b/sys/fs/nfsclient/nfs_clvfsops.c
    @@ -1238,8 +1238,7 @@ nfs_mount(struct mount *mp)
     		bzero(&hst[hstlen], MNAMELEN - hstlen);
     		args.hostname = hst;
     		/* getsockaddr() call must be after above copyin() calls */
    -		error = getsockaddr(&nam, (caddr_t)args.addr,
    -		    args.addrlen);
    +		error = getsockaddr(&nam, args.addr, args.addrlen);
     		if (error != 0)
     			goto out;
     	} else if (nfs_mount_parse_from(mp->mnt_optnew,
    diff --git a/sys/fs/nfsclient/nfs_clvnops.c b/sys/fs/nfsclient/nfs_clvnops.c
    index 47fd735d3b9e..7f9eb26e6ad3 100644
    --- a/sys/fs/nfsclient/nfs_clvnops.c
    +++ b/sys/fs/nfsclient/nfs_clvnops.c
    @@ -3030,16 +3030,16 @@ nfs_advlock(struct vop_advlock_args *ap)
     	struct proc *p = (struct proc *)ap->a_id;
     	struct thread *td = curthread;	/* XXX */
     	struct vattr va;
    -	int ret, error = EOPNOTSUPP;
    +	int ret, error;
     	u_quad_t size;
     	
    -	ret = NFSVOPLOCK(vp, LK_SHARED);
    -	if (ret != 0)
    +	error = NFSVOPLOCK(vp, LK_SHARED);
    +	if (error != 0)
     		return (EBADF);
     	if (NFS_ISV4(vp) && (ap->a_flags & (F_POSIX | F_FLOCK)) != 0) {
     		if (vp->v_type != VREG) {
    -			NFSVOPUNLOCK(vp, 0);
    -			return (EINVAL);
    +			error = EINVAL;
    +			goto out;
     		}
     		if ((ap->a_flags & F_POSIX) != 0)
     			cred = p->p_ucred;
    @@ -3047,8 +3047,8 @@ nfs_advlock(struct vop_advlock_args *ap)
     			cred = td->td_ucred;
     		NFSVOPLOCK(vp, LK_UPGRADE | LK_RETRY);
     		if (vp->v_iflag & VI_DOOMED) {
    -			NFSVOPUNLOCK(vp, 0);
    -			return (EBADF);
    +			error = EBADF;
    +			goto out;
     		}
     
     		/*
    @@ -3077,21 +3077,21 @@ nfs_advlock(struct vop_advlock_args *ap)
     					return (EINTR);
     				NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
     				if (vp->v_iflag & VI_DOOMED) {
    -					NFSVOPUNLOCK(vp, 0);
    -					return (EBADF);
    +					error = EBADF;
    +					goto out;
     				}
     			}
     		} while (ret == NFSERR_DENIED && (ap->a_flags & F_WAIT) &&
     		     ap->a_op == F_SETLK);
     		if (ret == NFSERR_DENIED) {
    -			NFSVOPUNLOCK(vp, 0);
    -			return (EAGAIN);
    +			error = EAGAIN;
    +			goto out;
     		} else if (ret == EINVAL || ret == EBADF || ret == EINTR) {
    -			NFSVOPUNLOCK(vp, 0);
    -			return (ret);
    +			error = ret;
    +			goto out;
     		} else if (ret != 0) {
    -			NFSVOPUNLOCK(vp, 0);
    -			return (EACCES);
    +			error = EACCES;
    +			goto out;
     		}
     
     		/*
    @@ -3121,8 +3121,6 @@ nfs_advlock(struct vop_advlock_args *ap)
     			np->n_flag |= NHASBEENLOCKED;
     			mtx_unlock(&np->n_mtx);
     		}
    -		NFSVOPUNLOCK(vp, 0);
    -		return (0);
     	} else if (!NFS_ISV4(vp)) {
     		if ((VFSTONFS(vp->v_mount)->nm_flag & NFSMNT_NOLOCKD) != 0) {
     			size = VTONFS(vp)->n_size;
    @@ -3146,8 +3144,11 @@ nfs_advlock(struct vop_advlock_args *ap)
     				NFSVOPUNLOCK(vp, 0);
     			}
     		}
    +		return (error);
     	} else
    -		NFSVOPUNLOCK(vp, 0);
    +		error = EOPNOTSUPP;
    +out:
    +	NFSVOPUNLOCK(vp, 0);
     	return (error);
     }
     
    diff --git a/sys/geom/geom_io.c b/sys/geom/geom_io.c
    index 9797884252ef..8a35b1e57d00 100644
    --- a/sys/geom/geom_io.c
    +++ b/sys/geom/geom_io.c
    @@ -420,6 +420,8 @@ g_io_check(struct bio *bp)
     			return (EIO);
     		if (bp->bio_offset > pp->mediasize)
     			return (EIO);
    +		if (bp->bio_offset == pp->mediasize && bp->bio_length > 0)
    +			return (EIO);
     
     		/* Truncate requests to the end of providers media. */
     		excess = bp->bio_offset + bp->bio_length;
    diff --git a/sys/i386/include/cpu.h b/sys/i386/include/cpu.h
    index 8cd94fa7e1ff..8ba5e455f714 100644
    --- a/sys/i386/include/cpu.h
    +++ b/sys/i386/include/cpu.h
    @@ -72,6 +72,7 @@ extern char	btext[];
     extern char	etext[];
     
     void	cpu_halt(void);
    +void	cpu_lock_delay(void);
     void	cpu_reset(void);
     void	fork_trampoline(void);
     void	swi_vm(void *);
    diff --git a/sys/kern/capabilities.conf b/sys/kern/capabilities.conf
    index 7857d0862295..b5198b7a341c 100644
    --- a/sys/kern/capabilities.conf
    +++ b/sys/kern/capabilities.conf
    @@ -486,9 +486,9 @@ pipe2
     
     ##
     ## Allow poll(2), which will be scoped by capability rights.
    -## XXXRW: We don't yet do that scoping.
     ##
     poll
    +ppoll
     
     ##
     ## Allow I/O-related file descriptors, subject to capability rights.
    diff --git a/sys/kern/init_sysent.c b/sys/kern/init_sysent.c
    index 885b5dc6f030..a567d0d83d95 100644
    --- a/sys/kern/init_sysent.c
    +++ b/sys/kern/init_sysent.c
    @@ -594,7 +594,7 @@ struct sysent sysent[] = {
     	{ AS(pipe2_args), (sy_call_t *)sys_pipe2, AUE_PIPE, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 542 = pipe2 */
     	{ AS(aio_mlock_args), (sy_call_t *)sys_aio_mlock, AUE_AIO_MLOCK, NULL, 0, 0, 0, SY_THR_STATIC },	/* 543 = aio_mlock */
     	{ AS(procctl_args), (sy_call_t *)sys_procctl, AUE_PROCCTL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 544 = procctl */
    -	{ AS(ppoll_args), (sy_call_t *)sys_ppoll, AUE_POLL, NULL, 0, 0, 0, SY_THR_STATIC },	/* 545 = ppoll */
    +	{ AS(ppoll_args), (sy_call_t *)sys_ppoll, AUE_POLL, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 545 = ppoll */
     	{ AS(futimens_args), (sy_call_t *)sys_futimens, AUE_FUTIMES, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 546 = futimens */
     	{ AS(utimensat_args), (sy_call_t *)sys_utimensat, AUE_FUTIMESAT, NULL, 0, 0, SYF_CAPENABLED, SY_THR_STATIC },	/* 547 = utimensat */
     	{ 0, (sy_call_t *)nosys, AUE_NULL, NULL, 0, 0, 0, SY_THR_ABSENT },			/* 548 = obsolete numa_getaffinity */
    diff --git a/sys/kern/kern_mutex.c b/sys/kern/kern_mutex.c
    index c3f566dd0279..65c2e299bbc7 100644
    --- a/sys/kern/kern_mutex.c
    +++ b/sys/kern/kern_mutex.c
    @@ -1206,7 +1206,7 @@ _mtx_lock_indefinite_check(struct mtx *m, struct lock_delay_arg *ldap)
     
     	ldap->spin_cnt++;
     	if (ldap->spin_cnt < 60000000 || kdb_active || panicstr != NULL)
    -		DELAY(1);
    +		cpu_lock_delay();
     	else {
     		td = mtx_owner(m);
     
    diff --git a/sys/kern/kern_ubsan.c b/sys/kern/kern_ubsan.c
    new file mode 100644
    index 000000000000..d6d60c5fa89e
    --- /dev/null
    +++ b/sys/kern/kern_ubsan.c
    @@ -0,0 +1,1650 @@
    +/*	$NetBSD: ubsan.c,v 1.3 2018/08/03 16:31:04 kamil Exp $	*/
    +
    +/*-
    + * Copyright (c) 2018 The NetBSD Foundation, Inc.
    + * All rights reserved.
    + *
    + * Redistribution and use in source and binary forms, with or without
    + * modification, are permitted provided that the following conditions
    + * are met:
    + * 1. Redistributions of source code must retain the above copyright
    + *    notice, this list of conditions and the following disclaimer.
    + * 2. Redistributions in binary form must reproduce the above copyright
    + *    notice, this list of conditions and the following disclaimer in the
    + *    documentation and/or other materials provided with the distribution.
    + *
    + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
    + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
    + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
    + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    + * POSSIBILITY OF SUCH DAMAGE.
    + */
    +
    +
    +/*
    + * The micro UBSan implementation for the userland (uUBSan) and kernel (kUBSan).
    + * The uBSSan versions is suitable for inclusion into libc or used standalone
    + * with ATF tests.
    + *
    + * This file due to long symbol names generated by a compiler during the
    + * instrumentation process does not follow the KNF style with 80-column limit.
    + */
    +
    +#include 
    +#ifdef __FreeBSD__
    +__FBSDID("$FreeBSD$");
    +#else
    +#if defined(_KERNEL)
    +__KERNEL_RCSID(0, "$NetBSD: ubsan.c,v 1.3 2018/08/03 16:31:04 kamil Exp $");
    +#else
    +__RCSID("$NetBSD: ubsan.c,v 1.3 2018/08/03 16:31:04 kamil Exp $");
    +#endif
    +#endif
    +
    +#if defined(_KERNEL)
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#define	ASSERT(x) KASSERT(x, ("%s: " __STRING(x) " failed", __func__))
    +#define	__arraycount(x) nitems(x)
    +#define	ISSET(x, y)	((x) & (y))
    +#define	__BIT(x)	((uintmax_t)1 << (uintmax_t)(x))
    +#define	__LOWEST_SET_BIT(__mask) ((((__mask) - 1) & (__mask)) ^ (__mask))
    +#define	__SHIFTOUT(__x, __mask) (((__x) & (__mask)) / __LOWEST_SET_BIT(__mask))
    +#else
    +#if defined(_LIBC)
    +#include "namespace.h"
    +#endif
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#include 
    +#if defined(_LIBC)
    +#include "extern.h"
    +#define ubsan_vsyslog vsyslog_ss
    +#define ASSERT(x) _DIAGASSERT(x)
    +#else
    +#define ubsan_vsyslog vsyslog_r
    +#define ASSERT(x) assert(x)
    +#endif
    +/* These macros are available in _KERNEL only */
    +#define SET(t, f)	((t) |= (f))
    +#define ISSET(t, f)	((t) & (f))
    +#define CLR(t, f)	((t) &= ~(f))
    +#endif
    +
    +#define REINTERPRET_CAST(__dt, __st)	((__dt)(__st))
    +#define STATIC_CAST(__dt, __st)		((__dt)(__st))
    +
    +#define ACK_REPORTED	__BIT(31)
    +
    +#define MUL_STRING	"*"
    +#define PLUS_STRING	"+"
    +#define MINUS_STRING	"-"
    +#define DIVREM_STRING	"divrem"
    +
    +#define CFI_VCALL		0
    +#define CFI_NVCALL		1
    +#define CFI_DERIVEDCAST		2
    +#define CFI_UNRELATEDCAST	3
    +#define CFI_ICALL		4
    +#define CFI_NVMFCALL		5
    +#define CFI_VMFCALL		6
    +
    +#define NUMBER_MAXLEN	128
    +#define LOCATION_MAXLEN	(PATH_MAX + 32 /* ':LINE:COLUMN' */)
    +
    +#define WIDTH_8		8
    +#define WIDTH_16	16
    +#define WIDTH_32	32
    +#define WIDTH_64	64
    +#define WIDTH_80	80
    +#define WIDTH_96	96
    +#define WIDTH_128	128
    +
    +#define NUMBER_SIGNED_BIT	1U
    +
    +#if __SIZEOF_INT128__
    +typedef __int128 longest;
    +typedef unsigned __int128 ulongest;
    +#else
    +typedef int64_t longest;
    +typedef uint64_t ulongest;
    +#endif
    +
    +#ifndef _KERNEL
    +static int ubsan_flags = -1;
    +#define UBSAN_ABORT	__BIT(0)
    +#define UBSAN_STDOUT	__BIT(1)
    +#define UBSAN_STDERR	__BIT(2)
    +#define UBSAN_SYSLOG	__BIT(3)
    +#endif
    +
    +/* Undefined Behavior specific defines and structures */
    +
    +#define KIND_INTEGER	0
    +#define KIND_FLOAT	1
    +#define KIND_UNKNOWN	UINT16_MAX
    +
    +struct CSourceLocation {
    +	char *mFilename;
    +	uint32_t mLine;
    +	uint32_t mColumn;
    +};
    +
    +struct CTypeDescriptor {
    +	uint16_t mTypeKind;
    +	uint16_t mTypeInfo;
    +	uint8_t mTypeName[1];
    +};
    +
    +struct COverflowData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +};
    +
    +struct CUnreachableData {
    +	struct CSourceLocation mLocation;
    +};
    +
    +struct CCFICheckFailData {
    +	uint8_t mCheckKind;
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +};
    +
    +struct CDynamicTypeCacheMissData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +	void *mTypeInfo;
    +	uint8_t mTypeCheckKind;
    +};
    +
    +struct CFunctionTypeMismatchData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +};
    +
    +struct CInvalidBuiltinData {
    +	struct CSourceLocation mLocation;
    +	uint8_t mKind;
    +};
    +
    +struct CInvalidValueData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +};
    +
    +struct CNonNullArgData {
    +	struct CSourceLocation mLocation;
    +	struct CSourceLocation mAttributeLocation;
    +	int mArgIndex;
    +};
    +
    +struct CNonNullReturnData {
    +	struct CSourceLocation mAttributeLocation;
    +};
    +
    +struct COutOfBoundsData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mArrayType;
    +	struct CTypeDescriptor *mIndexType;
    +};
    +
    +struct CPointerOverflowData {
    +	struct CSourceLocation mLocation;
    +};
    +
    +struct CShiftOutOfBoundsData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mLHSType;
    +	struct CTypeDescriptor *mRHSType;
    +};
    +
    +struct CTypeMismatchData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +	unsigned long mLogAlignment;
    +	uint8_t mTypeCheckKind;
    +};
    +
    +struct CTypeMismatchData_v1 {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +	uint8_t mLogAlignment;
    +	uint8_t mTypeCheckKind;
    +};
    +
    +struct CVLABoundData {
    +	struct CSourceLocation mLocation;
    +	struct CTypeDescriptor *mType;
    +};
    +
    +struct CFloatCastOverflowData {
    +	struct CSourceLocation mLocation;	/* This field exists in this struct since 2015 August 11th */
    +	struct CTypeDescriptor *mFromType;
    +	struct CTypeDescriptor *mToType;
    +};
    +
    +/* Local utility functions */
    +static void Report(bool isFatal, const char *pFormat, ...) __printflike(2, 3);
    +static bool isAlreadyReported(struct CSourceLocation *pLocation);
    +static size_t zDeserializeTypeWidth(struct CTypeDescriptor *pType);
    +static void DeserializeLocation(char *pBuffer, size_t zBUfferLength, struct CSourceLocation *pLocation);
    +#ifdef __SIZEOF_INT128__
    +static void DeserializeUINT128(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, __uint128_t U128);
    +#endif
    +static void DeserializeNumberSigned(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, longest L);
    +static void DeserializeNumberUnsigned(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, ulongest L);
    +#ifndef _KERNEL
    +static void DeserializeFloatOverPointer(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long *pNumber);
    +static void DeserializeFloatInlined(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long ulNumber);
    +#endif
    +static longest llliGetNumber(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber);
    +static ulongest llluGetNumber(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber);
    +#ifndef _KERNEL
    +static void DeserializeNumberFloat(char *szLocation, char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long ulNumber);
    +#endif
    +static void DeserializeNumber(char *szLocation, char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long ulNumber);
    +static const char *DeserializeTypeCheckKind(uint8_t hhuTypeCheckKind);
    +static const char *DeserializeBuiltinCheckKind(uint8_t hhuBuiltinCheckKind);
    +static const char *DeserializeCFICheckKind(uint8_t hhuCFICheckKind);
    +static bool isNegativeNumber(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber);
    +static bool isShiftExponentTooLarge(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber, size_t zWidth);
    +
    +/* Unused in this implementation, emitted by the C++ check dynamic type cast. */
    +intptr_t __ubsan_vptr_type_cache[128];
    +
    +/* Public symbols used in the instrumentation of the code generation part */
    +void __ubsan_handle_add_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_add_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_builtin_unreachable(struct CUnreachableData *pData);
    +void __ubsan_handle_cfi_bad_type(struct CCFICheckFailData *pData, unsigned long ulVtable, bool bValidVtable, bool FromUnrecoverableHandler, unsigned long ProgramCounter, unsigned long FramePointer);
    +void __ubsan_handle_cfi_check_fail(struct CCFICheckFailData *pData, unsigned long ulValue, unsigned long ulValidVtable);
    +void __ubsan_handle_cfi_check_fail_abort(struct CCFICheckFailData *pData, unsigned long ulValue, unsigned long ulValidVtable);
    +void __ubsan_handle_divrem_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_divrem_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_dynamic_type_cache_miss(struct CDynamicTypeCacheMissData *pData, unsigned long ulPointer, unsigned long ulHash);
    +void __ubsan_handle_dynamic_type_cache_miss_abort(struct CDynamicTypeCacheMissData *pData, unsigned long ulPointer, unsigned long ulHash);
    +void __ubsan_handle_float_cast_overflow(struct CFloatCastOverflowData *pData, unsigned long ulFrom);
    +void __ubsan_handle_float_cast_overflow_abort(struct CFloatCastOverflowData *pData, unsigned long ulFrom);
    +void __ubsan_handle_function_type_mismatch(struct CFunctionTypeMismatchData *pData, unsigned long ulFunction);
    +void __ubsan_handle_function_type_mismatch_abort(struct CFunctionTypeMismatchData *pData, unsigned long ulFunction);
    +void __ubsan_handle_invalid_builtin(struct CInvalidBuiltinData *pData);
    +void __ubsan_handle_invalid_builtin_abort(struct CInvalidBuiltinData *pData);
    +void __ubsan_handle_load_invalid_value(struct CInvalidValueData *pData, unsigned long ulVal);
    +void __ubsan_handle_load_invalid_value_abort(struct CInvalidValueData *pData, unsigned long ulVal);
    +void __ubsan_handle_missing_return(struct CUnreachableData *pData);
    +void __ubsan_handle_mul_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_mul_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_negate_overflow(struct COverflowData *pData, unsigned long ulOldVal);
    +void __ubsan_handle_negate_overflow_abort(struct COverflowData *pData, unsigned long ulOldVal);
    +void __ubsan_handle_nonnull_arg(struct CNonNullArgData *pData);
    +void __ubsan_handle_nonnull_arg_abort(struct CNonNullArgData *pData);
    +void __ubsan_handle_nonnull_return_v1(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer);
    +void __ubsan_handle_nonnull_return_v1_abort(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer);
    +void __ubsan_handle_nullability_arg(struct CNonNullArgData *pData);
    +void __ubsan_handle_nullability_arg_abort(struct CNonNullArgData *pData);
    +void __ubsan_handle_nullability_return_v1(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer);
    +void __ubsan_handle_nullability_return_v1_abort(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer);
    +void __ubsan_handle_out_of_bounds(struct COutOfBoundsData *pData, unsigned long ulIndex);
    +void __ubsan_handle_out_of_bounds_abort(struct COutOfBoundsData *pData, unsigned long ulIndex);
    +void __ubsan_handle_pointer_overflow(struct CPointerOverflowData *pData, unsigned long ulBase, unsigned long ulResult);
    +void __ubsan_handle_pointer_overflow_abort(struct CPointerOverflowData *pData, unsigned long ulBase, unsigned long ulResult);
    +void __ubsan_handle_shift_out_of_bounds(struct CShiftOutOfBoundsData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_shift_out_of_bounds_abort(struct CShiftOutOfBoundsData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_sub_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_sub_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +void __ubsan_handle_type_mismatch(struct CTypeMismatchData *pData, unsigned long ulPointer);
    +void __ubsan_handle_type_mismatch_abort(struct CTypeMismatchData *pData, unsigned long ulPointer);
    +void __ubsan_handle_type_mismatch_v1(struct CTypeMismatchData_v1 *pData, unsigned long ulPointer);
    +void __ubsan_handle_type_mismatch_v1_abort(struct CTypeMismatchData_v1 *pData, unsigned long ulPointer);
    +void __ubsan_handle_vla_bound_not_positive(struct CVLABoundData *pData, unsigned long ulBound);
    +void __ubsan_handle_vla_bound_not_positive_abort(struct CVLABoundData *pData, unsigned long ulBound);
    +void __ubsan_get_current_report_data(const char **ppOutIssueKind, const char **ppOutMessage, const char **ppOutFilename, uint32_t *pOutLine, uint32_t *pOutCol, char **ppOutMemoryAddr);
    +
    +static void HandleOverflow(bool isFatal, struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS, const char *szOperation);
    +static void HandleNegateOverflow(bool isFatal, struct COverflowData *pData, unsigned long ulOldValue);
    +static void HandleBuiltinUnreachable(bool isFatal, struct CUnreachableData *pData);
    +static void HandleTypeMismatch(bool isFatal, struct CSourceLocation *mLocation, struct CTypeDescriptor *mType, unsigned long mLogAlignment, uint8_t mTypeCheckKind, unsigned long ulPointer);
    +static void HandleVlaBoundNotPositive(bool isFatal, struct CVLABoundData *pData, unsigned long ulBound);
    +static void HandleOutOfBounds(bool isFatal, struct COutOfBoundsData *pData, unsigned long ulIndex);
    +static void HandleShiftOutOfBounds(bool isFatal, struct CShiftOutOfBoundsData *pData, unsigned long ulLHS, unsigned long ulRHS);
    +static void HandleLoadInvalidValue(bool isFatal, struct CInvalidValueData *pData, unsigned long ulValue);
    +static void HandleInvalidBuiltin(bool isFatal, struct CInvalidBuiltinData *pData);
    +static void HandleFunctionTypeMismatch(bool isFatal, struct CFunctionTypeMismatchData *pData, unsigned long ulFunction);
    +static void HandleCFIBadType(bool isFatal, struct CCFICheckFailData *pData, unsigned long ulVtable, bool *bValidVtable, bool *FromUnrecoverableHandler, unsigned long *ProgramCounter, unsigned long *FramePointer);
    +static void HandleDynamicTypeCacheMiss(bool isFatal, struct CDynamicTypeCacheMissData *pData, unsigned long ulPointer, unsigned long ulHash);
    +static void HandleFloatCastOverflow(bool isFatal, struct CFloatCastOverflowData *pData, unsigned long ulFrom);
    +static void HandleMissingReturn(bool isFatal, struct CUnreachableData *pData);
    +static void HandleNonnullArg(bool isFatal, struct CNonNullArgData *pData);
    +static void HandleNonnullReturn(bool isFatal, struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer);
    +static void HandlePointerOverflow(bool isFatal, struct CPointerOverflowData *pData, unsigned long ulBase, unsigned long ulResult);
    +
    +static void
    +HandleOverflow(bool isFatal, struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS, const char *szOperation)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szLHS[NUMBER_MAXLEN];
    +	char szRHS[NUMBER_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	DeserializeNumber(szLocation, szLHS, NUMBER_MAXLEN, pData->mType, ulLHS);
    +	DeserializeNumber(szLocation, szRHS, NUMBER_MAXLEN, pData->mType, ulRHS);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, %s integer overflow: %s %s %s cannot be represented in type %s\n",
    +	       szLocation, ISSET(pData->mType->mTypeInfo, NUMBER_SIGNED_BIT) ? "signed" : "unsigned", szLHS, szOperation, szRHS, pData->mType->mTypeName);
    +}
    +
    +static void
    +HandleNegateOverflow(bool isFatal, struct COverflowData *pData, unsigned long ulOldValue)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szOldValue[NUMBER_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	DeserializeNumber(szLocation, szOldValue, NUMBER_MAXLEN, pData->mType, ulOldValue);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, negation of %s cannot be represented in type %s\n",
    +	       szLocation, szOldValue, pData->mType->mTypeName);
    +}
    +
    +static void
    +HandleBuiltinUnreachable(bool isFatal, struct CUnreachableData *pData)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, calling __builtin_unreachable()\n",
    +	       szLocation);
    +}
    +
    +static void
    +HandleTypeMismatch(bool isFatal, struct CSourceLocation *mLocation, struct CTypeDescriptor *mType, unsigned long mLogAlignment, uint8_t mTypeCheckKind, unsigned long ulPointer)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	ASSERT(mLocation);
    +	ASSERT(mType);
    +
    +	if (isAlreadyReported(mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, mLocation);
    +
    +	if (ulPointer == 0) {
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, %s null pointer of type %s\n",
    +		       szLocation, DeserializeTypeCheckKind(mTypeCheckKind), mType->mTypeName);
    +	} else if ((mLogAlignment - 1) & ulPointer) {
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, %s misaligned address %p for type %s which requires %ld byte alignment\n",
    +		       szLocation, DeserializeTypeCheckKind(mTypeCheckKind), REINTERPRET_CAST(void *, ulPointer), mType->mTypeName, mLogAlignment);
    +	} else {
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, %s address %p with insufficient space for an object of type %s\n",
    +		       szLocation, DeserializeTypeCheckKind(mTypeCheckKind), REINTERPRET_CAST(void *, ulPointer), mType->mTypeName);
    +	}
    +}
    +
    +static void
    +HandleVlaBoundNotPositive(bool isFatal, struct CVLABoundData *pData, unsigned long ulBound)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szBound[NUMBER_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	DeserializeNumber(szLocation, szBound, NUMBER_MAXLEN, pData->mType, ulBound);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, variable length array bound value %s <= 0\n",
    +	       szLocation, szBound);
    +}
    +
    +static void
    +HandleOutOfBounds(bool isFatal, struct COutOfBoundsData *pData, unsigned long ulIndex)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szIndex[NUMBER_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	DeserializeNumber(szLocation, szIndex, NUMBER_MAXLEN, pData->mIndexType, ulIndex);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, index %s is out of range for type %s\n",
    +	       szLocation, szIndex, pData->mArrayType->mTypeName);
    +}
    +
    +static void
    +HandleShiftOutOfBounds(bool isFatal, struct CShiftOutOfBoundsData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szLHS[NUMBER_MAXLEN];
    +	char szRHS[NUMBER_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	DeserializeNumber(szLocation, szLHS, NUMBER_MAXLEN, pData->mLHSType, ulLHS);
    +	DeserializeNumber(szLocation, szRHS, NUMBER_MAXLEN, pData->mRHSType, ulRHS);
    +
    +	if (isNegativeNumber(szLocation, pData->mRHSType, ulRHS))
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, shift exponent %s is negative\n",
    +		       szLocation, szRHS);
    +	else if (isShiftExponentTooLarge(szLocation, pData->mRHSType, ulRHS, zDeserializeTypeWidth(pData->mLHSType)))
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, shift exponent %s is too large for %zu-bit type %s\n",
    +		       szLocation, szRHS, zDeserializeTypeWidth(pData->mLHSType), pData->mLHSType->mTypeName);
    +	else if (isNegativeNumber(szLocation, pData->mLHSType, ulLHS))
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, left shift of negative value %s\n",
    +		       szLocation, szLHS);
    +	else
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, left shift of %s by %s places cannot be represented in type %s\n",
    +		       szLocation, szLHS, szRHS, pData->mLHSType->mTypeName);
    +}
    +
    +static void
    +HandleLoadInvalidValue(bool isFatal, struct CInvalidValueData *pData, unsigned long ulValue)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szValue[NUMBER_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	DeserializeNumber(szLocation, szValue, NUMBER_MAXLEN, pData->mType, ulValue);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, load of value %s is not a valid value for type %s\n",
    +	       szLocation, szValue, pData->mType->mTypeName);
    +}
    +
    +static void
    +HandleInvalidBuiltin(bool isFatal, struct CInvalidBuiltinData *pData)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, passing zero to %s, which is not a valid argument\n",
    +	       szLocation, DeserializeBuiltinCheckKind(pData->mKind));
    +}
    +
    +static void
    +HandleFunctionTypeMismatch(bool isFatal, struct CFunctionTypeMismatchData *pData, unsigned long ulFunction)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	/*
    +	 * There is no a portable C solution to translate an address of a
    +	 * function to its name. On the cost of getting this routine simple
    +	 * and portable without ifdefs between the userland and the kernel
    +	 * just print the address of the function as-is.
    +	 *
    +	 * For better diagnostic messages in the userland, users shall use
    +	 * the full upstream version shipped along with the compiler toolchain.
    +	 */
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, call to function %#lx through pointer to incorrect function type %s\n",
    +	      szLocation, ulFunction, pData->mType->mTypeName);
    +}
    +
    +static void
    +HandleCFIBadType(bool isFatal, struct CCFICheckFailData *pData, unsigned long ulVtable, bool *bValidVtable, bool *FromUnrecoverableHandler, unsigned long *ProgramCounter, unsigned long *FramePointer)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	/*
    +	 * This is a minimal implementation without diving into C++
    +	 * specifics and (Itanium) ABI deserialization.
    +	 */
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +
    +	if (pData->mCheckKind == CFI_ICALL || pData->mCheckKind == CFI_VMFCALL) {
    +		Report(isFatal, "UBSan: Undefined Behavior in %s, control flow integrity check for type %s failed during %s (vtable address %#lx)\n",
    +		      szLocation, pData->mType->mTypeName, DeserializeCFICheckKind(pData->mCheckKind), ulVtable);
    +	} else {
    +		Report(isFatal || FromUnrecoverableHandler, "UBSan: Undefined Behavior in %s, control flow integrity check for type %s failed during %s (vtable address %#lx; %s vtable; from %s handler; Program Counter %#lx; Frame Pointer %#lx)\n",
    +		      szLocation, pData->mType->mTypeName, DeserializeCFICheckKind(pData->mCheckKind), ulVtable, *bValidVtable ? "valid" : "invalid", *FromUnrecoverableHandler ? "unrecoverable" : "recoverable", *ProgramCounter, *FramePointer);
    +	}
    +}
    +
    +static void
    +HandleDynamicTypeCacheMiss(bool isFatal, struct CDynamicTypeCacheMissData *pData, unsigned long ulPointer, unsigned long ulHash)
    +{
    +#if 0
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	/*
    +	 * Unimplemented.
    +	 *
    +	 * This UBSan handler is special as the check has to be impelemented
    +	 * in an implementation. In order to handle it there is need to
    +	 * introspect into C++ ABI internals (RTTI) and use low-level
    +	 * C++ runtime interfaces.
    +	 */
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, %s address %#lx which might not point to an object of type %s\n"
    +	      szLocation, DeserializeTypeCheckKind(pData->mTypeCheckKind), ulPointer, pData->mType);
    +#endif
    +}
    +
    +static void
    +HandleFloatCastOverflow(bool isFatal, struct CFloatCastOverflowData *pData, unsigned long ulFrom)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szFrom[NUMBER_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	DeserializeNumber(szLocation, szFrom, NUMBER_MAXLEN, pData->mFromType, ulFrom);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, %s (of type %s) is outside the range of representable values of type %s\n",
    +	       szLocation, szFrom, pData->mFromType->mTypeName, pData->mToType->mTypeName);
    +}
    +
    +static void
    +HandleMissingReturn(bool isFatal, struct CUnreachableData *pData)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, execution reached the end of a value-returning function without returning a value\n",
    +	       szLocation);
    +}
    +
    +static void
    +HandleNonnullArg(bool isFatal, struct CNonNullArgData *pData)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szAttributeLocation[LOCATION_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +	if (pData->mAttributeLocation.mFilename)
    +		DeserializeLocation(szAttributeLocation, LOCATION_MAXLEN, &pData->mAttributeLocation);
    +	else
    +		szAttributeLocation[0] = '\0';
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, null pointer passed as argument %d, which is declared to never be null%s%s\n",
    +	       szLocation, pData->mArgIndex, pData->mAttributeLocation.mFilename ? ", nonnull/_Nonnull specified in " : "", szAttributeLocation);
    +}
    +
    +static void
    +HandleNonnullReturn(bool isFatal, struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +	char szAttributeLocation[LOCATION_MAXLEN];
    +
    +	ASSERT(pData);
    +	ASSERT(pLocationPointer);
    +
    +	if (isAlreadyReported(pLocationPointer))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, pLocationPointer);
    +	if (pData->mAttributeLocation.mFilename)
    +		DeserializeLocation(szAttributeLocation, LOCATION_MAXLEN, &pData->mAttributeLocation);
    +	else
    +		szAttributeLocation[0] = '\0';
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, null pointer returned from function declared to never return null%s%s\n",
    +	       szLocation, pData->mAttributeLocation.mFilename ? ", nonnull/_Nonnull specified in " : "", szAttributeLocation);
    +}
    +
    +static void
    +HandlePointerOverflow(bool isFatal, struct CPointerOverflowData *pData, unsigned long ulBase, unsigned long ulResult)
    +{
    +	char szLocation[LOCATION_MAXLEN];
    +
    +	ASSERT(pData);
    +
    +	if (isAlreadyReported(&pData->mLocation))
    +		return;
    +
    +	DeserializeLocation(szLocation, LOCATION_MAXLEN, &pData->mLocation);
    +
    +	Report(isFatal, "UBSan: Undefined Behavior in %s, pointer expression with base %#lx overflowed to %#lx\n",
    +	       szLocation, ulBase, ulResult);
    +}
    +
    +/* Definions of public symbols emitted by the instrumentation code */
    +void
    +__ubsan_handle_add_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(false, pData, ulLHS, ulRHS, PLUS_STRING);
    +}
    +
    +void
    +__ubsan_handle_add_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(true, pData, ulLHS, ulRHS, PLUS_STRING);
    +}
    +
    +void
    +__ubsan_handle_builtin_unreachable(struct CUnreachableData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleBuiltinUnreachable(true, pData);
    +}
    +
    +void
    +__ubsan_handle_cfi_bad_type(struct CCFICheckFailData *pData, unsigned long ulVtable, bool bValidVtable, bool FromUnrecoverableHandler, unsigned long ProgramCounter, unsigned long FramePointer)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleCFIBadType(false, pData, ulVtable, &bValidVtable, &FromUnrecoverableHandler, &ProgramCounter, &FramePointer);
    +}
    +
    +void
    +__ubsan_handle_cfi_check_fail(struct CCFICheckFailData *pData, unsigned long ulValue, unsigned long ulValidVtable)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleCFIBadType(false, pData, ulValue, 0, 0, 0, 0);
    +}
    +
    +void
    +__ubsan_handle_cfi_check_fail_abort(struct CCFICheckFailData *pData, unsigned long ulValue, unsigned long ulValidVtable)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleCFIBadType(true, pData, ulValue, 0, 0, 0, 0);
    +}
    +
    +void
    +__ubsan_handle_divrem_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(false, pData, ulLHS, ulRHS, DIVREM_STRING);
    +}
    +
    +void
    +__ubsan_handle_divrem_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(true, pData, ulLHS, ulRHS, DIVREM_STRING);
    +}
    +
    +void
    +__ubsan_handle_dynamic_type_cache_miss(struct CDynamicTypeCacheMissData *pData, unsigned long ulPointer, unsigned long ulHash)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleDynamicTypeCacheMiss(false, pData, ulPointer, ulHash);
    +}
    +
    +void
    +__ubsan_handle_dynamic_type_cache_miss_abort(struct CDynamicTypeCacheMissData *pData, unsigned long ulPointer, unsigned long ulHash)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleDynamicTypeCacheMiss(false, pData, ulPointer, ulHash);
    +}
    +
    +void
    +__ubsan_handle_float_cast_overflow(struct CFloatCastOverflowData *pData, unsigned long ulFrom)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleFloatCastOverflow(false, pData, ulFrom);
    +}
    +
    +void
    +__ubsan_handle_float_cast_overflow_abort(struct CFloatCastOverflowData *pData, unsigned long ulFrom)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleFloatCastOverflow(true, pData, ulFrom);
    +}
    +
    +void
    +__ubsan_handle_function_type_mismatch(struct CFunctionTypeMismatchData *pData, unsigned long ulFunction)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleFunctionTypeMismatch(false, pData, ulFunction);
    +}
    +
    +void
    +__ubsan_handle_function_type_mismatch_abort(struct CFunctionTypeMismatchData *pData, unsigned long ulFunction)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleFunctionTypeMismatch(false, pData, ulFunction);
    +}
    +
    +void
    +__ubsan_handle_invalid_builtin(struct CInvalidBuiltinData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleInvalidBuiltin(true, pData);
    +}
    +
    +void
    +__ubsan_handle_invalid_builtin_abort(struct CInvalidBuiltinData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleInvalidBuiltin(true, pData);
    +}
    +
    +void
    +__ubsan_handle_load_invalid_value(struct CInvalidValueData *pData, unsigned long ulValue)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleLoadInvalidValue(false, pData, ulValue);
    +}
    +
    +void
    +__ubsan_handle_load_invalid_value_abort(struct CInvalidValueData *pData, unsigned long ulValue)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleLoadInvalidValue(true, pData, ulValue);
    +}
    +
    +void
    +__ubsan_handle_missing_return(struct CUnreachableData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleMissingReturn(true, pData);
    +}
    +
    +void
    +__ubsan_handle_mul_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(false, pData, ulLHS, ulRHS, MUL_STRING);
    +}
    +
    +void
    +__ubsan_handle_mul_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(true, pData, ulLHS, ulRHS, MUL_STRING);
    +}
    +
    +void
    +__ubsan_handle_negate_overflow(struct COverflowData *pData, unsigned long ulOldValue)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleNegateOverflow(false, pData, ulOldValue);
    +}
    +
    +void
    +__ubsan_handle_negate_overflow_abort(struct COverflowData *pData, unsigned long ulOldValue)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleNegateOverflow(true, pData, ulOldValue);
    +}
    +
    +void
    +__ubsan_handle_nonnull_arg(struct CNonNullArgData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleNonnullArg(false, pData);
    +}
    +
    +void
    +__ubsan_handle_nonnull_arg_abort(struct CNonNullArgData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleNonnullArg(true, pData);
    +}
    +
    +void
    +__ubsan_handle_nonnull_return_v1(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer)
    +{
    +
    +	ASSERT(pData);
    +	ASSERT(pLocationPointer);
    +
    +	HandleNonnullReturn(false, pData, pLocationPointer);
    +}
    +
    +void
    +__ubsan_handle_nonnull_return_v1_abort(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer)
    +{
    +
    +	ASSERT(pData);
    +	ASSERT(pLocationPointer);
    +
    +	HandleNonnullReturn(true, pData, pLocationPointer);
    +}
    +
    +void
    +__ubsan_handle_nullability_arg(struct CNonNullArgData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleNonnullArg(false, pData);
    +}
    +
    +void
    +__ubsan_handle_nullability_arg_abort(struct CNonNullArgData *pData)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleNonnullArg(true, pData);
    +}
    +
    +void
    +__ubsan_handle_nullability_return_v1(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer)
    +{
    +
    +	ASSERT(pData);
    +	ASSERT(pLocationPointer);
    +
    +	HandleNonnullReturn(false, pData, pLocationPointer);
    +}
    +
    +void
    +__ubsan_handle_nullability_return_v1_abort(struct CNonNullReturnData *pData, struct CSourceLocation *pLocationPointer)
    +{
    +
    +	ASSERT(pData);
    +	ASSERT(pLocationPointer);
    +
    +	HandleNonnullReturn(true, pData, pLocationPointer);
    +}
    +
    +void
    +__ubsan_handle_out_of_bounds(struct COutOfBoundsData *pData, unsigned long ulIndex)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOutOfBounds(false, pData, ulIndex);
    +}
    +
    +void
    +__ubsan_handle_out_of_bounds_abort(struct COutOfBoundsData *pData, unsigned long ulIndex)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOutOfBounds(true, pData, ulIndex);
    +}
    +
    +void
    +__ubsan_handle_pointer_overflow(struct CPointerOverflowData *pData, unsigned long ulBase, unsigned long ulResult)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandlePointerOverflow(false, pData, ulBase, ulResult);
    +}
    +
    +void
    +__ubsan_handle_pointer_overflow_abort(struct CPointerOverflowData *pData, unsigned long ulBase, unsigned long ulResult)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandlePointerOverflow(true, pData, ulBase, ulResult);
    +}
    +
    +void
    +__ubsan_handle_shift_out_of_bounds(struct CShiftOutOfBoundsData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleShiftOutOfBounds(false, pData, ulLHS, ulRHS);
    +}
    +
    +void
    +__ubsan_handle_shift_out_of_bounds_abort(struct CShiftOutOfBoundsData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleShiftOutOfBounds(true, pData, ulLHS, ulRHS);
    +}
    +
    +void
    +__ubsan_handle_sub_overflow(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(false, pData, ulLHS, ulRHS, MINUS_STRING);
    +}
    +
    +void
    +__ubsan_handle_sub_overflow_abort(struct COverflowData *pData, unsigned long ulLHS, unsigned long ulRHS)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleOverflow(true, pData, ulLHS, ulRHS, MINUS_STRING);
    +}
    +
    +void
    +__ubsan_handle_type_mismatch(struct CTypeMismatchData *pData, unsigned long ulPointer)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleTypeMismatch(false, &pData->mLocation, pData->mType, pData->mLogAlignment, pData->mTypeCheckKind, ulPointer);
    +}
    +
    +void
    +__ubsan_handle_type_mismatch_abort(struct CTypeMismatchData *pData, unsigned long ulPointer)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleTypeMismatch(true, &pData->mLocation, pData->mType, pData->mLogAlignment, pData->mTypeCheckKind, ulPointer);
    +}
    +
    +void
    +__ubsan_handle_type_mismatch_v1(struct CTypeMismatchData_v1 *pData, unsigned long ulPointer)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleTypeMismatch(false, &pData->mLocation, pData->mType, __BIT(pData->mLogAlignment), pData->mTypeCheckKind, ulPointer);
    +}
    +
    +void
    +__ubsan_handle_type_mismatch_v1_abort(struct CTypeMismatchData_v1 *pData, unsigned long ulPointer)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleTypeMismatch(true, &pData->mLocation, pData->mType, __BIT(pData->mLogAlignment), pData->mTypeCheckKind, ulPointer);
    +}
    +
    +void
    +__ubsan_handle_vla_bound_not_positive(struct CVLABoundData *pData, unsigned long ulBound)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleVlaBoundNotPositive(false, pData, ulBound);
    +}
    +
    +void
    +__ubsan_handle_vla_bound_not_positive_abort(struct CVLABoundData *pData, unsigned long ulBound)
    +{
    +
    +	ASSERT(pData);
    +
    +	HandleVlaBoundNotPositive(true, pData, ulBound);
    +}
    +
    +void
    +__ubsan_get_current_report_data(const char **ppOutIssueKind, const char **ppOutMessage, const char **ppOutFilename, uint32_t *pOutLine, uint32_t *pOutCol, char **ppOutMemoryAddr)
    +{
    +	/*
    +	 * Unimplemented.
    +	 *
    +	 * The __ubsan_on_report() feature is non trivial to implement in a
    +	 * shared code between the kernel and userland. It's also opening
    +	 * new sets of potential problems as we are not expected to slow down
    +	 * execution of certain kernel subsystems (synchronization issues,
    +	 * interrupt handling etc).
    +	 *
    +	 * A proper solution would need probably a lock-free bounded queue built
    +	 * with atomic operations with the property of miltiple consumers and
    +	 * multiple producers. Maintaining and validating such code is not
    +	 * worth the effort.
    +	 *
    +	 * A legitimate user - besides testing framework - is a debugger plugin
    +	 * intercepting reports from the UBSan instrumentation. For such
    +	 * scenarios it is better to run the Clang/GCC version.
    +	 */
    +}
    +
    +/* Local utility functions */
    +
    +static void
    +Report(bool isFatal, const char *pFormat, ...)
    +{
    +	va_list ap;
    +
    +	ASSERT(pFormat);
    +
    +	va_start(ap, pFormat);
    +#if defined(_KERNEL)
    +	if (isFatal)
    +		vpanic(pFormat, ap);
    +	else
    +		vprintf(pFormat, ap);
    +#else
    +	if (ubsan_flags == -1) {
    +		char buf[1024];
    +		char *p;
    +
    +		ubsan_flags = UBSAN_STDERR;
    +
    +		if (getenv_r("LIBC_UBSAN", buf, sizeof(buf)) != -1) {
    +			for (p = buf; *p; p++) {
    +				switch (*p) {
    +				case 'a':
    +					SET(ubsan_flags, UBSAN_ABORT);
    +					break;
    +				case 'A':
    +					CLR(ubsan_flags, UBSAN_ABORT);
    +					break;
    +				case 'e':
    +					SET(ubsan_flags, UBSAN_STDERR);
    +					break;
    +				case 'E':
    +					CLR(ubsan_flags, UBSAN_STDERR);
    +					break;
    +				case 'l':
    +					SET(ubsan_flags, UBSAN_SYSLOG);
    +					break;
    +				case 'L':
    +					CLR(ubsan_flags, UBSAN_SYSLOG);
    +					break;
    +				case 'o':
    +					SET(ubsan_flags, UBSAN_STDOUT);
    +					break;
    +				case 'O':
    +					CLR(ubsan_flags, UBSAN_STDOUT);
    +					break;
    +				default:
    +					break;
    +				}
    +			}
    +		}
    +	}
    +
    +	// The *v*print* functions can flush the va_list argument.
    +	// Create a local copy for each call to prevent invalid read.
    +	if (ISSET(ubsan_flags, UBSAN_STDOUT)) {
    +		va_list tmp;
    +		va_copy(tmp, ap);
    +		vprintf(pFormat, tmp);
    +		va_end(tmp);
    +		fflush(stdout);
    +	}
    +	if (ISSET(ubsan_flags, UBSAN_STDERR)) {
    +		va_list tmp;
    +		va_copy(tmp, ap);
    +		vfprintf(stderr, pFormat, tmp);
    +		va_end(tmp);
    +		fflush(stderr);
    +	}
    +	if (ISSET(ubsan_flags, UBSAN_SYSLOG)) {
    +		va_list tmp;
    +		va_copy(tmp, ap);
    +		struct syslog_data SyslogData = SYSLOG_DATA_INIT;
    +		ubsan_vsyslog(LOG_DEBUG | LOG_USER, &SyslogData, pFormat, tmp);
    +		va_end(tmp);
    +	}
    +	if (isFatal || ISSET(ubsan_flags, UBSAN_ABORT)) {
    +		abort();
    +		/* NOTREACHED */
    +	}
    +#endif
    +	va_end(ap);
    +}
    +
    +static bool
    +isAlreadyReported(struct CSourceLocation *pLocation)
    +{
    +	/*
    +	 * This code is shared between libc, kernel and standalone usage.
    +	 * It shall work in early bootstrap phase of both of them.
    +	 */
    +
    +	uint32_t siOldValue;
    +	volatile uint32_t *pLine;
    +
    +	ASSERT(pLocation);
    +
    +	pLine = &pLocation->mLine;
    +
    +	do {
    +		siOldValue = *pLine;
    +	} while (__sync_val_compare_and_swap(pLine, siOldValue, siOldValue | ACK_REPORTED) != siOldValue);
    +
    +	return ISSET(siOldValue, ACK_REPORTED);
    +}
    +
    +static size_t
    +zDeserializeTypeWidth(struct CTypeDescriptor *pType)
    +{
    +	size_t zWidth = 0;
    +
    +	ASSERT(pType);
    +
    +	switch (pType->mTypeKind) {
    +	case KIND_INTEGER:
    +		zWidth = __BIT(__SHIFTOUT(pType->mTypeInfo, ~NUMBER_SIGNED_BIT));
    +		break;
    +	case KIND_FLOAT:
    +		zWidth = pType->mTypeInfo;
    +		break;
    +	default:
    +		Report(true, "UBSan: Unknown variable type %#04" PRIx16 "\n", pType->mTypeKind);
    +		/* NOTREACHED */
    +	}
    +
    +	/* Invalid width will be transformed to 0 */
    +	ASSERT(zWidth > 0);
    +
    +	return zWidth;
    +}
    +
    +static void
    +DeserializeLocation(char *pBuffer, size_t zBUfferLength, struct CSourceLocation *pLocation)
    +{
    +
    +	ASSERT(pLocation);
    +	ASSERT(pLocation->mFilename);
    +
    +	snprintf(pBuffer, zBUfferLength, "%s:%" PRIu32 ":%" PRIu32, pLocation->mFilename, pLocation->mLine & (uint32_t)~ACK_REPORTED, pLocation->mColumn);
    +}
    +
    +#ifdef __SIZEOF_INT128__
    +static void
    +DeserializeUINT128(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, __uint128_t U128)
    +{
    +	char szBuf[3]; /* 'XX\0' */
    +	char rgNumber[sizeof(ulongest)];
    +	ssize_t zI;
    +
    +	memcpy(rgNumber, &U128, sizeof(U128));
    +
    +	strlcpy(pBuffer, "Undecoded-128-bit-Integer-Type (0x", zBUfferLength);
    +#if BYTE_ORDER == LITTLE_ENDIAN
    +	for (zI = sizeof(ulongest) - 1; zI >= 0; zI--) {
    +#else
    +	for (zI = 0; zI < (ssize_t)sizeof(ulongest); zI++) {
    +#endif
    +		snprintf(szBuf, sizeof(szBuf), "%02" PRIx8, rgNumber[zI]);
    +		strlcat(pBuffer, szBuf, zBUfferLength);
    +	}
    +	strlcat(pBuffer, ")", zBUfferLength);
    +}
    +#endif
    +
    +static void
    +DeserializeNumberSigned(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, longest L)
    +{
    +
    +	ASSERT(pBuffer);
    +	ASSERT(zBUfferLength > 0);
    +	ASSERT(pType);
    +	ASSERT(ISSET(pType->mTypeInfo, NUMBER_SIGNED_BIT));
    +
    +	switch (zDeserializeTypeWidth(pType)) {
    +	default:
    +		ASSERT(0 && "Invalid codepath");
    +		/* NOTREACHED */
    +#ifdef __SIZEOF_INT128__
    +	case WIDTH_128:
    +		DeserializeUINT128(pBuffer, zBUfferLength, pType, STATIC_CAST(__uint128_t, L));
    +		break;
    +#endif
    +	case WIDTH_64:
    +	case WIDTH_32:
    +	case WIDTH_16:
    +	case WIDTH_8:
    +		snprintf(pBuffer, zBUfferLength, "%" PRId64, STATIC_CAST(int64_t, L));
    +		break;
    +	}
    +}
    +
    +static void
    +DeserializeNumberUnsigned(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, ulongest L)
    +{
    +
    +	ASSERT(pBuffer);
    +	ASSERT(zBUfferLength > 0);
    +	ASSERT(pType);
    +	ASSERT(!ISSET(pType->mTypeInfo, NUMBER_SIGNED_BIT));
    +
    +	switch (zDeserializeTypeWidth(pType)) {
    +	default:
    +		ASSERT(0 && "Invalid codepath");
    +		/* NOTREACHED */
    +#ifdef __SIZEOF_INT128__
    +	case WIDTH_128:
    +		DeserializeUINT128(pBuffer, zBUfferLength, pType, STATIC_CAST(__uint128_t, L));
    +		break;
    +#endif
    +	case WIDTH_64:
    +	case WIDTH_32:
    +	case WIDTH_16:
    +	case WIDTH_8:
    +		snprintf(pBuffer, zBUfferLength, "%" PRIu64, STATIC_CAST(uint64_t, L));
    +		break;
    +	}
    +}
    +
    +#ifndef _KERNEL
    +static void
    +DeserializeFloatOverPointer(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long *pNumber)
    +{
    +	double D;
    +#ifdef __HAVE_LONG_DOUBLE
    +	long double LD;
    +#endif
    +
    +	ASSERT(pBuffer);
    +	ASSERT(zBUfferLength > 0);
    +	ASSERT(pType);
    +	ASSERT(pNumber);
    +	/*
    +	 * This function handles 64-bit number over a pointer on 32-bit CPUs.
    +	 */
    +	ASSERT((sizeof(*pNumber) * CHAR_BIT < WIDTH_64) || (zDeserializeTypeWidth(pType) >= WIDTH_64));
    +	ASSERT(sizeof(D) == sizeof(uint64_t));
    +#ifdef __HAVE_LONG_DOUBLE
    +	ASSERT(sizeof(LD) > sizeof(uint64_t));
    +#endif
    +
    +	switch (zDeserializeTypeWidth(pType)) {
    +#ifdef __HAVE_LONG_DOUBLE
    +	case WIDTH_128:
    +	case WIDTH_96:
    +	case WIDTH_80:
    +		memcpy(&LD, pNumber, sizeof(long double));
    +		snprintf(pBuffer, zBUfferLength, "%Lg", LD);
    +		break;
    +#endif
    +	case WIDTH_64:
    +		memcpy(&D, pNumber, sizeof(double));
    +		snprintf(pBuffer, zBUfferLength, "%g", D);
    +		break;
    +	}
    +}
    +
    +static void
    +DeserializeFloatInlined(char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long ulNumber)
    +{
    +	float F;
    +	double D;
    +	uint32_t U32;
    +
    +	ASSERT(pBuffer);
    +	ASSERT(zBUfferLength > 0);
    +	ASSERT(pType);
    +	ASSERT(sizeof(F) == sizeof(uint32_t));
    +	ASSERT(sizeof(D) == sizeof(uint64_t));
    +
    +	switch (zDeserializeTypeWidth(pType)) {
    +	case WIDTH_64:
    +		memcpy(&D, &ulNumber, sizeof(double));
    +		snprintf(pBuffer, zBUfferLength, "%g", D);
    +		break;
    +	case WIDTH_32:
    +		/*
    +		 * On supported platforms sizeof(float)==sizeof(uint32_t)
    +		 * unsigned long is either 32 or 64-bit, cast it to 32-bit
    +		 * value in order to call memcpy(3) in an Endian-aware way.
    +		 */
    +		U32 = STATIC_CAST(uint32_t, ulNumber);
    +		memcpy(&F, &U32, sizeof(float));
    +		snprintf(pBuffer, zBUfferLength, "%g", F);
    +		break;
    +	case WIDTH_16:
    +		snprintf(pBuffer, zBUfferLength, "Undecoded-16-bit-Floating-Type (%#04" PRIx16 ")", STATIC_CAST(uint16_t, ulNumber));
    +		break;
    +	}
    +}
    +#endif
    +
    +static longest
    +llliGetNumber(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber)
    +{
    +	size_t zNumberWidth;
    +	longest L = 0;
    +
    +	ASSERT(szLocation);
    +	ASSERT(pType);
    +
    +	zNumberWidth = zDeserializeTypeWidth(pType);
    +	switch (zNumberWidth) {
    +	default:
    +		Report(true, "UBSan: Unexpected %zu-Bit Type in %s\n", zNumberWidth, szLocation);
    +		/* NOTREACHED */
    +	case WIDTH_128:
    +#ifdef __SIZEOF_INT128__
    +		memcpy(&L, REINTERPRET_CAST(longest *, ulNumber), sizeof(longest));
    +#else
    +		Report(true, "UBSan: Unexpected 128-Bit Type in %s\n", szLocation);
    +		/* NOTREACHED */
    +#endif
    +		break;
    +	case WIDTH_64:
    +		if (sizeof(ulNumber) * CHAR_BIT < WIDTH_64) {
    +			L = *REINTERPRET_CAST(int64_t *, ulNumber);
    +		} else {
    +			L = STATIC_CAST(int64_t, STATIC_CAST(uint64_t, ulNumber));
    +		}
    +		break;
    +	case WIDTH_32:
    +		L = STATIC_CAST(int32_t, STATIC_CAST(uint32_t, ulNumber));
    +		break;
    +	case WIDTH_16:
    +		L = STATIC_CAST(int16_t, STATIC_CAST(uint16_t, ulNumber));
    +		break;
    +	case WIDTH_8:
    +		L = STATIC_CAST(int8_t, STATIC_CAST(uint8_t, ulNumber));
    +		break;
    +	}
    +
    +	return L;
    +}
    +
    +static ulongest
    +llluGetNumber(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber)
    +{
    +	size_t zNumberWidth;
    +	ulongest UL = 0;
    +
    +	ASSERT(pType);
    +
    +	zNumberWidth = zDeserializeTypeWidth(pType);
    +	switch (zNumberWidth) {
    +	default:
    +		Report(true, "UBSan: Unexpected %zu-Bit Type in %s\n", zNumberWidth, szLocation);
    +		/* NOTREACHED */
    +	case WIDTH_128:
    +#ifdef __SIZEOF_INT128__
    +		memcpy(&UL, REINTERPRET_CAST(ulongest *, ulNumber), sizeof(ulongest));
    +		break;
    +#else
    +		Report(true, "UBSan: Unexpected 128-Bit Type in %s\n", szLocation);
    +		/* NOTREACHED */
    +#endif
    +	case WIDTH_64:
    +		if (sizeof(ulNumber) * CHAR_BIT < WIDTH_64) {
    +			UL = *REINTERPRET_CAST(uint64_t *, ulNumber);
    +			break;
    +		}
    +		/* FALLTHROUGH */
    +	case WIDTH_32:
    +		/* FALLTHROUGH */
    +	case WIDTH_16:
    +		/* FALLTHROUGH */
    +	case WIDTH_8:
    +		UL = ulNumber;
    +		break;
    +	}
    +
    +	return UL;
    +}
    +
    +#ifndef _KERNEL
    +static void
    +DeserializeNumberFloat(char *szLocation, char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long ulNumber)
    +{
    +	size_t zNumberWidth;
    +
    +	ASSERT(szLocation);
    +	ASSERT(pBuffer);
    +	ASSERT(zBUfferLength > 0);
    +	ASSERT(pType);
    +	ASSERT(pType->mTypeKind == KIND_FLOAT);
    +
    +	zNumberWidth = zDeserializeTypeWidth(pType);
    +	switch (zNumberWidth) {
    +	default:
    +		Report(true, "UBSan: Unexpected %zu-Bit Type in %s\n", zNumberWidth, szLocation);
    +		/* NOTREACHED */
    +#ifdef __HAVE_LONG_DOUBLE
    +	case WIDTH_128:
    +	case WIDTH_96:
    +	case WIDTH_80:
    +		DeserializeFloatOverPointer(pBuffer, zBUfferLength, pType, REINTERPRET_CAST(unsigned long *, ulNumber));
    +		break;
    +#endif
    +	case WIDTH_64:
    +		if (sizeof(ulNumber) * CHAR_BIT < WIDTH_64) {
    +			DeserializeFloatOverPointer(pBuffer, zBUfferLength, pType, REINTERPRET_CAST(unsigned long *, ulNumber));
    +			break;
    +		}
    +	case WIDTH_32:
    +	case WIDTH_16:
    +		DeserializeFloatInlined(pBuffer, zBUfferLength, pType, ulNumber);
    +		break;
    +	}
    +}
    +#endif
    +
    +static void
    +DeserializeNumber(char *szLocation, char *pBuffer, size_t zBUfferLength, struct CTypeDescriptor *pType, unsigned long ulNumber)
    +{
    +
    +	ASSERT(szLocation);
    +	ASSERT(pBuffer);
    +	ASSERT(zBUfferLength > 0);
    +	ASSERT(pType);
    +
    +	switch(pType->mTypeKind) {
    +	case KIND_INTEGER:
    +		if (ISSET(pType->mTypeInfo, NUMBER_SIGNED_BIT)) {
    +			longest L = llliGetNumber(szLocation, pType, ulNumber);
    +			DeserializeNumberSigned(pBuffer, zBUfferLength, pType, L);
    +		} else {
    +			ulongest UL = llluGetNumber(szLocation, pType, ulNumber);
    +			DeserializeNumberUnsigned(pBuffer, zBUfferLength, pType, UL);
    +		}
    +		break;
    +	case KIND_FLOAT:
    +#ifdef _KERNEL
    +		Report(true, "UBSan: Unexpected Float Type in %s\n", szLocation);
    +		/* NOTREACHED */
    +#else
    +		DeserializeNumberFloat(szLocation, pBuffer, zBUfferLength, pType, ulNumber);
    +#endif
    +		break;
    +	case KIND_UNKNOWN:
    +		Report(true, "UBSan: Unknown Type in %s\n", szLocation);
    +		/* NOTREACHED */
    +		break;
    +	}
    +}
    +
    +static const char *
    +DeserializeTypeCheckKind(uint8_t hhuTypeCheckKind)
    +{
    +	const char *rgczTypeCheckKinds[] = {
    +		"load of",
    +		"store to",
    +		"reference binding to",
    +		"member access within",
    +		"member call on",
    +		"constructor call on",
    +		"downcast of",
    +		"downcast of",
    +		"upcast of",
    +		"cast to virtual base of",
    +		"_Nonnull binding to",
    +		"dynamic operation on"
    +	};
    +
    +	ASSERT(__arraycount(rgczTypeCheckKinds) > hhuTypeCheckKind);
    +
    +	return rgczTypeCheckKinds[hhuTypeCheckKind];
    +}
    +
    +static const char *
    +DeserializeBuiltinCheckKind(uint8_t hhuBuiltinCheckKind)
    +{
    +	const char *rgczBuiltinCheckKinds[] = {
    +		"ctz()",
    +		"clz()"
    +	};
    +
    +	ASSERT(__arraycount(rgczBuiltinCheckKinds) > hhuBuiltinCheckKind);
    +
    +	return rgczBuiltinCheckKinds[hhuBuiltinCheckKind];
    +}
    +
    +static const char *
    +DeserializeCFICheckKind(uint8_t hhuCFICheckKind)
    +{
    +	const char *rgczCFICheckKinds[] = {
    +		"virtual call",					// CFI_VCALL
    +		"non-virtual call",				// CFI_NVCALL
    +		"base-to-derived cast",				// CFI_DERIVEDCAST
    +		"cast to unrelated type",			// CFI_UNRELATEDCAST
    +		"indirect function call",			// CFI_ICALL
    +		"non-virtual pointer to member function call",	// CFI_NVMFCALL
    +		"virtual pointer to member function call",	// CFI_VMFCALL
    +	};
    +
    +	ASSERT(__arraycount(rgczCFICheckKinds) > hhuCFICheckKind);
    +
    +	return rgczCFICheckKinds[hhuCFICheckKind];
    +}
    +
    +static bool
    +isNegativeNumber(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber)
    +{
    +
    +	ASSERT(szLocation);
    +	ASSERT(pType);
    +	ASSERT(pType->mTypeKind == KIND_INTEGER);
    +
    +	if (!ISSET(pType->mTypeInfo, NUMBER_SIGNED_BIT))
    +		return false;
    +
    +	return llliGetNumber(szLocation, pType, ulNumber) < 0;
    +}
    +
    +static bool
    +isShiftExponentTooLarge(char *szLocation, struct CTypeDescriptor *pType, unsigned long ulNumber, size_t zWidth)
    +{
    +
    +	ASSERT(szLocation);
    +	ASSERT(pType);
    +	ASSERT(pType->mTypeKind == KIND_INTEGER);
    +
    +	return llluGetNumber(szLocation, pType, ulNumber) >= zWidth;
    +}
    diff --git a/sys/kern/sys_pipe.c b/sys/kern/sys_pipe.c
    index 56eba3dd22db..8b0aaa9ab4cf 100644
    --- a/sys/kern/sys_pipe.c
    +++ b/sys/kern/sys_pipe.c
    @@ -509,9 +509,8 @@ pipespace_new(struct pipe *cpipe, int size)
     	size = round_page(size);
     	buffer = (caddr_t) vm_map_min(pipe_map);
     
    -	error = vm_map_find(pipe_map, NULL, 0,
    -		(vm_offset_t *) &buffer, size, 0, VMFS_ANY_SPACE,
    -		VM_PROT_ALL, VM_PROT_ALL, 0);
    +	error = vm_map_find(pipe_map, NULL, 0, (vm_offset_t *)&buffer, size, 0,
    +	    VMFS_ANY_SPACE, VM_PROT_RW, VM_PROT_RW, 0);
     	if (error != KERN_SUCCESS) {
     		if ((cpipe->pipe_buffer.buffer == NULL) &&
     			(size > SMALL_PIPE_SIZE)) {
    diff --git a/sys/kern/syscalls.master b/sys/kern/syscalls.master
    index dfe6677de120..55d81c059d5e 100644
    --- a/sys/kern/syscalls.master
    +++ b/sys/kern/syscalls.master
    @@ -117,8 +117,7 @@
     		);
     	}
     ; XXX should be		{ int open(const char *path, int flags, ...); }
    -; but we're not ready for `const' or varargs.
    -; XXX man page says `mode_t mode'.
    +; but we're not ready for varargs.
     6	AUE_CLOSE	STD {
     		int close(
     		    int fd
    @@ -207,10 +206,9 @@
     		    _In_z_ const char *type,
     		    _In_z_ const char *path,
     		    int flags,
    -		    _In_opt_ caddr_t data
    +		    _In_opt_ void *data
     		);
     	}
    -; XXX `path' should have type `const char *' but we're not ready for that.
     22	AUE_UMOUNT	STD {
     		int unmount(
     		    _In_z_ const char *path,
    @@ -253,7 +251,7 @@
     29	AUE_RECVFROM	STD {
     		int recvfrom(
     		    int s,
    -		    _Out_writes_bytes_(len) caddr_t buf,
    +		    _Out_writes_bytes_(len) void *buf,
     		    size_t len,
     		    int flags,
     		    _Out_writes_bytes_opt_(*fromlenaddr) struct sockaddr *from,
    @@ -336,7 +334,7 @@
     	}
     44	AUE_PROFILE	STD {
     		int profil(
    -		    _Out_writes_bytes_(size) caddr_t samples,
    +		    _Out_writes_bytes_(size) char *samples,
     		    size_t size,
     		    size_t offset,
     		    u_int scale
    @@ -398,7 +396,7 @@
     		int ioctl(
     		    int fd,
     		    u_long com,
    -		    _Inout_opt_ caddr_t data
    +		    _Inout_opt_ char *data
     		);
     	}
     55	AUE_REBOOT	STD {
    @@ -630,14 +628,14 @@
     98	AUE_CONNECT	STD {
     		int connect(
     		    int s,
    -		    _In_reads_bytes_(namelen) caddr_t name,
    +		    _In_reads_bytes_(namelen) const struct sockaddr *name,
     		    int namelen
     		);
     	}
     99	AUE_ACCEPT	COMPAT|NOARGS {
     		int accept(
     		    int s,
    -		    _Out_writes_bytes_opt_(*anamelen) caddr_t name,
    +		    _Out_writes_bytes_opt_(*anamelen) struct sockaddr *name,
     		    int *anamelen
     		);
     	} accept accept_args int
    @@ -650,7 +648,7 @@
     101	AUE_SEND	COMPAT {
     		int send(
     		    int s,
    -		    _In_reads_bytes_(len) caddr_t buf,
    +		    _In_reads_bytes_(len) const void *buf,
     		    int len,
     		    int flags
     		);
    @@ -658,7 +656,7 @@
     102	AUE_RECV	COMPAT {
     		int recv(
     		    int s,
    -		    _Out_writes_bytes_(len) caddr_t buf,
    +		    _Out_writes_bytes_(len) void *buf,
     		    int len,
     		    int flags
     		);
    @@ -671,7 +669,7 @@
     104	AUE_BIND	STD {
     		int bind(
     		    int s,
    -		    _In_reads_bytes_(namelen) caddr_t name,
    +		    _In_reads_bytes_(namelen) const struct sockaddr *name,
     		    int namelen
     		);
     	}
    @@ -680,7 +678,7 @@
     		    int s,
     		    int level,
     		    int name,
    -		    _In_reads_bytes_opt_(valsize) caddr_t val,
    +		    _In_reads_bytes_opt_(valsize) const void *val,
     		    int valsize
     		);
     	}
    @@ -731,7 +729,7 @@
     114	AUE_SENDMSG	COMPAT {
     		int sendmsg(
     		    int s,
    -		    _In_ caddr_t msg,
    +		    _In_ const void *msg,
     		    int flags
     		);
     	}
    @@ -753,7 +751,7 @@
     		    int s,
     		    int level,
     		    int name,
    -		    _Out_writes_bytes_opt_(*avalsize) caddr_t val,
    +		    _Out_writes_bytes_opt_(*avalsize) void *val,
     		    _Inout_  int *avalsize
     		);
     	}
    @@ -761,8 +759,8 @@
     120	AUE_READV	STD {
     		int readv(
     		    int fd,
    -		   _Inout_updates_(iovcnt) struct iovec *iovp,
    -		   u_int iovcnt
    +		    _Inout_updates_(iovcnt) struct iovec *iovp,
    +		    u_int iovcnt
     		);
     	}
     121	AUE_WRITEV	STD {
    @@ -794,10 +792,10 @@
     125	AUE_RECVFROM	COMPAT|NOARGS {
     		int recvfrom(
     		    int s,
    -		    _Out_writes_(len) caddr_t buf,
    +		    _Out_writes_(len) void *buf,
     		    size_t len,
     		    int flags,
    -		    _Out_writes_bytes_(*fromlenaddr) caddr_t from,
    +		    _Out_writes_bytes_(*fromlenaddr) struct sockaddr *from,
     		    _Inout_ int *fromlenaddr
     		);
     	} recvfrom recvfrom_args int
    @@ -846,10 +844,10 @@
     133	AUE_SENDTO	STD {
     		int sendto(
     		    int s,
    -		    _In_reads_bytes_(len) caddr_t buf,
    +		    _In_reads_bytes_(len) const void *buf,
     		    size_t len,
    -		     int flags,
    -		    _In_reads_bytes_opt_(tolen) caddr_t to,
    +		    int flags,
    +		    _In_reads_bytes_opt_(tolen) const struct sockaddr *to,
     		    int tolen
     		);
     	}
    @@ -894,7 +892,7 @@
     141	AUE_GETPEERNAME	COMPAT {
     		int getpeername(
     		    int fdes,
    -		    _Out_writes_bytes_(*alen) caddr_t asa,
    +		    _Out_writes_bytes_(*alen) struct sockaddr *asa,
     		    _Inout_opt_ int *alen
     		);
     	}
    @@ -932,7 +930,7 @@
     		    _In_z_ const char *path,
     		    int cmd,
     		    int uid,
    -		    _In_ caddr_t arg
    +		    _In_ void *arg
     		);
     	}
     149	AUE_O_QUOTA	COMPAT {
    @@ -941,7 +939,7 @@
     150	AUE_GETSOCKNAME	COMPAT|NOARGS {
     		int getsockname(
     		    int fdec,
    -		    _Out_writes_bytes_(*alen) caddr_t asa,
    +		    _Out_writes_bytes_(*alen) struct sockaddr *asa,
     		    _Inout_ int *alen
     		);
     	} getsockname getsockname_args int
    @@ -966,7 +964,7 @@
     155	AUE_NFS_SVC	NOSTD {
     		int nfssvc(
     		    int flag,
    -		    _In_ caddr_t argp
    +		    _In_ void *argp
     		);
     	}
     156	AUE_GETDIRENTRIES	COMPAT {
    @@ -1171,7 +1169,7 @@
     	}
     197	AUE_MMAP	COMPAT6 {
     		caddr_t mmap(
    -		    _In_ caddr_t addr,
    +		    _In_ void *addr,
     		    size_t len,
     		    int prot,
     		    int flags,
    @@ -2498,9 +2496,9 @@
     472	AUE_SCTP_GENERIC_SENDMSG	NOSTD {
     		int sctp_generic_sendmsg(
     		    int sd,
    -		    _In_reads_bytes_(mlen) caddr_t msg,
    +		    _In_reads_bytes_(mlen) void *msg,
     		    int mlen,
    -		    _In_reads_bytes_(tolen) caddr_t to,
    +		    _In_reads_bytes_(tolen) struct sockaddr *to,
     		    __socklen_t tolen,
     		    _In_opt_ struct sctp_sndrcvinfo *sinfo,
     		    int flags
    @@ -2511,7 +2509,7 @@
     		    int sd,
     		    _In_reads_(iovlen) struct iovec *iov,
     		    int iovlen,
    -		    _In_reads_bytes_(tolen) caddr_t to,
    +		    _In_reads_bytes_(tolen) struct sockaddr *to,
     		    __socklen_t tolen,
     		    _In_opt_ struct sctp_sndrcvinfo *sinfo,
     		    int flags
    @@ -2546,7 +2544,7 @@
     	}
     477	AUE_MMAP	STD {
     		caddr_t mmap(
    -		    _In_ caddr_t addr,
    +		    _In_ void *addr,
     		    size_t len,
     		    int prot,
     		    int flags,
    @@ -2967,7 +2965,7 @@
     		int bindat(
     		    int fd,
     		    int s,
    -		    _In_reads_bytes_(namelen) caddr_t name,
    +		    _In_reads_bytes_(namelen) const struct sockaddr *name,
     		    int namelen
     		);
     	}
    @@ -2975,7 +2973,7 @@
     		int connectat(
     		    int fd,
     		    int s,
    -		    _In_reads_bytes_(namelen) caddr_t name,
    +		    _In_reads_bytes_(namelen) const struct sockaddr *name,
     		    int namelen
     		);
     	}
    diff --git a/sys/kern/systrace_args.c b/sys/kern/systrace_args.c
    index 31283b9df1f0..9061b6eb6a89 100644
    --- a/sys/kern/systrace_args.c
    +++ b/sys/kern/systrace_args.c
    @@ -136,7 +136,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		uarg[0] = (intptr_t) p->type; /* const char * */
     		uarg[1] = (intptr_t) p->path; /* const char * */
     		iarg[2] = p->flags; /* int */
    -		uarg[3] = (intptr_t) p->data; /* caddr_t */
    +		uarg[3] = (intptr_t) p->data; /* void * */
     		*n_args = 4;
     		break;
     	}
    @@ -197,7 +197,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 29: {
     		struct recvfrom_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->buf; /* caddr_t */
    +		uarg[1] = (intptr_t) p->buf; /* void * */
     		uarg[2] = p->len; /* size_t */
     		iarg[3] = p->flags; /* int */
     		uarg[4] = (intptr_t) p->from; /* struct sockaddr * */
    @@ -289,7 +289,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	/* profil */
     	case 44: {
     		struct profil_args *p = params;
    -		uarg[0] = (intptr_t) p->samples; /* caddr_t */
    +		uarg[0] = (intptr_t) p->samples; /* char * */
     		uarg[1] = p->size; /* size_t */
     		uarg[2] = p->offset; /* size_t */
     		uarg[3] = p->scale; /* u_int */
    @@ -346,7 +346,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		struct ioctl_args *p = params;
     		iarg[0] = p->fd; /* int */
     		uarg[1] = p->com; /* u_long */
    -		uarg[2] = (intptr_t) p->data; /* caddr_t */
    +		uarg[2] = (intptr_t) p->data; /* char * */
     		*n_args = 3;
     		break;
     	}
    @@ -582,7 +582,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 98: {
     		struct connect_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->name; /* caddr_t */
    +		uarg[1] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[2] = p->namelen; /* int */
     		*n_args = 3;
     		break;
    @@ -599,7 +599,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 104: {
     		struct bind_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->name; /* caddr_t */
    +		uarg[1] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[2] = p->namelen; /* int */
     		*n_args = 3;
     		break;
    @@ -610,7 +610,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		iarg[0] = p->s; /* int */
     		iarg[1] = p->level; /* int */
     		iarg[2] = p->name; /* int */
    -		uarg[3] = (intptr_t) p->val; /* caddr_t */
    +		uarg[3] = (intptr_t) p->val; /* const void * */
     		iarg[4] = p->valsize; /* int */
     		*n_args = 5;
     		break;
    @@ -645,7 +645,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		iarg[0] = p->s; /* int */
     		iarg[1] = p->level; /* int */
     		iarg[2] = p->name; /* int */
    -		uarg[3] = (intptr_t) p->val; /* caddr_t */
    +		uarg[3] = (intptr_t) p->val; /* void * */
     		uarg[4] = (intptr_t) p->avalsize; /* int * */
     		*n_args = 5;
     		break;
    @@ -737,10 +737,10 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 133: {
     		struct sendto_args *p = params;
     		iarg[0] = p->s; /* int */
    -		uarg[1] = (intptr_t) p->buf; /* caddr_t */
    +		uarg[1] = (intptr_t) p->buf; /* const void * */
     		uarg[2] = p->len; /* size_t */
     		iarg[3] = p->flags; /* int */
    -		uarg[4] = (intptr_t) p->to; /* caddr_t */
    +		uarg[4] = (intptr_t) p->to; /* const struct sockaddr * */
     		iarg[5] = p->tolen; /* int */
     		*n_args = 6;
     		break;
    @@ -805,7 +805,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		uarg[0] = (intptr_t) p->path; /* const char * */
     		iarg[1] = p->cmd; /* int */
     		iarg[2] = p->uid; /* int */
    -		uarg[3] = (intptr_t) p->arg; /* caddr_t */
    +		uarg[3] = (intptr_t) p->arg; /* void * */
     		*n_args = 4;
     		break;
     	}
    @@ -823,7 +823,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 155: {
     		struct nfssvc_args *p = params;
     		iarg[0] = p->flag; /* int */
    -		uarg[1] = (intptr_t) p->argp; /* caddr_t */
    +		uarg[1] = (intptr_t) p->argp; /* void * */
     		*n_args = 2;
     		break;
     	}
    @@ -2474,9 +2474,9 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	case 472: {
     		struct sctp_generic_sendmsg_args *p = params;
     		iarg[0] = p->sd; /* int */
    -		uarg[1] = (intptr_t) p->msg; /* caddr_t */
    +		uarg[1] = (intptr_t) p->msg; /* void * */
     		iarg[2] = p->mlen; /* int */
    -		uarg[3] = (intptr_t) p->to; /* caddr_t */
    +		uarg[3] = (intptr_t) p->to; /* struct sockaddr * */
     		iarg[4] = p->tolen; /* __socklen_t */
     		uarg[5] = (intptr_t) p->sinfo; /* struct sctp_sndrcvinfo * */
     		iarg[6] = p->flags; /* int */
    @@ -2489,7 +2489,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		iarg[0] = p->sd; /* int */
     		uarg[1] = (intptr_t) p->iov; /* struct iovec * */
     		iarg[2] = p->iovlen; /* int */
    -		uarg[3] = (intptr_t) p->to; /* caddr_t */
    +		uarg[3] = (intptr_t) p->to; /* struct sockaddr * */
     		iarg[4] = p->tolen; /* __socklen_t */
     		uarg[5] = (intptr_t) p->sinfo; /* struct sctp_sndrcvinfo * */
     		iarg[6] = p->flags; /* int */
    @@ -2532,7 +2532,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     	/* mmap */
     	case 477: {
     		struct mmap_args *p = params;
    -		uarg[0] = (intptr_t) p->addr; /* caddr_t */
    +		uarg[0] = (intptr_t) p->addr; /* void * */
     		uarg[1] = p->len; /* size_t */
     		iarg[2] = p->prot; /* int */
     		iarg[3] = p->flags; /* int */
    @@ -3047,7 +3047,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		struct bindat_args *p = params;
     		iarg[0] = p->fd; /* int */
     		iarg[1] = p->s; /* int */
    -		uarg[2] = (intptr_t) p->name; /* caddr_t */
    +		uarg[2] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[3] = p->namelen; /* int */
     		*n_args = 4;
     		break;
    @@ -3057,7 +3057,7 @@ systrace_args(int sysnum, void *params, uint64_t *uarg, int *n_args)
     		struct connectat_args *p = params;
     		iarg[0] = p->fd; /* int */
     		iarg[1] = p->s; /* int */
    -		uarg[2] = (intptr_t) p->name; /* caddr_t */
    +		uarg[2] = (intptr_t) p->name; /* const struct sockaddr * */
     		iarg[3] = p->namelen; /* int */
     		*n_args = 4;
     		break;
    @@ -3467,7 +3467,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		default:
     			break;
    @@ -3560,7 +3560,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 2:
     			p = "size_t";
    @@ -3701,7 +3701,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     	case 44:
     		switch(ndx) {
     		case 0:
    -			p = "caddr_t";
    +			p = "userland char *";
     			break;
     		case 1:
     			p = "size_t";
    @@ -3794,7 +3794,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "u_long";
     			break;
     		case 2:
    -			p = "caddr_t";
    +			p = "userland char *";
     			break;
     		default:
     			break;
    @@ -4169,7 +4169,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 2:
     			p = "int";
    @@ -4198,7 +4198,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 2:
     			p = "int";
    @@ -4220,7 +4220,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland const void *";
     			break;
     		case 4:
     			p = "int";
    @@ -4281,7 +4281,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 4:
     			p = "userland int *";
    @@ -4436,7 +4436,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland const void *";
     			break;
     		case 2:
     			p = "size_t";
    @@ -4445,7 +4445,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 4:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 5:
     			p = "int";
    @@ -4551,7 +4551,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		default:
     			break;
    @@ -4583,7 +4583,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		default:
     			break;
    @@ -7276,13 +7276,13 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 1:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 2:
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 4:
     			p = "__socklen_t";
    @@ -7310,7 +7310,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 3:
    -			p = "caddr_t";
    +			p = "userland struct sockaddr *";
     			break;
     		case 4:
     			p = "__socklen_t";
    @@ -7395,7 +7395,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     	case 477:
     		switch(ndx) {
     		case 0:
    -			p = "caddr_t";
    +			p = "userland void *";
     			break;
     		case 1:
     			p = "size_t";
    @@ -8312,7 +8312,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 2:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 3:
     			p = "int";
    @@ -8331,7 +8331,7 @@ systrace_entry_setargdesc(int sysnum, int ndx, char *desc, size_t descsz)
     			p = "int";
     			break;
     		case 2:
    -			p = "caddr_t";
    +			p = "userland const struct sockaddr *";
     			break;
     		case 3:
     			p = "int";
    diff --git a/sys/kern/tty.c b/sys/kern/tty.c
    index 26ce6124bf86..022c392d5c17 100644
    --- a/sys/kern/tty.c
    +++ b/sys/kern/tty.c
    @@ -33,6 +33,7 @@
     __FBSDID("$FreeBSD$");
     
     #include "opt_capsicum.h"
    +#include "opt_printf.h"
     
     #include 
     #include 
    @@ -106,6 +107,12 @@ SYSCTL_INT(_kern, OID_AUTO, tty_drainwait, CTLFLAG_RWTUN,
     
     #define	TTYBUF_MAX	65536
     
    +#ifdef PRINTF_BUFR_SIZE
    +#define	TTY_PRBUF_SIZE	PRINTF_BUFR_SIZE
    +#else
    +#define	TTY_PRBUF_SIZE	256
    +#endif
    +
     /*
      * Allocate buffer space if necessary, and set low watermarks, based on speed.
      * Note that the ttyxxxq_setsize() functions may drop and then reacquire the tty
    @@ -1051,7 +1058,9 @@ tty_alloc_mutex(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
     	PATCH_FUNC(busy);
     #undef PATCH_FUNC
     
    -	tp = malloc(sizeof(struct tty), M_TTY, M_WAITOK|M_ZERO);
    +	tp = malloc(sizeof(struct tty) + TTY_PRBUF_SIZE, M_TTY,
    +	    M_WAITOK | M_ZERO);
    +	tp->t_prbufsz = TTY_PRBUF_SIZE;
     	tp->t_devsw = tsw;
     	tp->t_devswsoftc = sc;
     	tp->t_flags = tsw->tsw_flags;
    diff --git a/sys/kern/tty_info.c b/sys/kern/tty_info.c
    index 378e1bc64284..47e65565848d 100644
    --- a/sys/kern/tty_info.c
    +++ b/sys/kern/tty_info.c
    @@ -45,6 +45,8 @@
     #include 
     __FBSDID("$FreeBSD$");
     
    +#include "opt_stack.h"
    +
     #include 
     #include 
     #include 
    @@ -269,7 +271,7 @@ tty_info(struct tty *tp)
     	if (tty_checkoutq(tp) == 0)
     		return;
     
    -	(void)sbuf_new(&sb, tp->t_prbuf, sizeof(tp->t_prbuf), SBUF_FIXEDLEN);
    +	(void)sbuf_new(&sb, tp->t_prbuf, tp->t_prbufsz, SBUF_FIXEDLEN);
     	sbuf_set_drain(&sb, sbuf_tty_drain, tp);
     
     	/* Print load average. */
    diff --git a/sys/kern/uipc_mqueue.c b/sys/kern/uipc_mqueue.c
    index 4751635e2aee..2f5cad6466d8 100644
    --- a/sys/kern/uipc_mqueue.c
    +++ b/sys/kern/uipc_mqueue.c
    @@ -393,7 +393,7 @@ mqnode_free(struct mqfs_node *node)
     static __inline void
     mqnode_addref(struct mqfs_node *node)
     {
    -	atomic_fetchadd_int(&node->mn_refcount, 1);
    +	atomic_add_int(&node->mn_refcount, 1);
     }
     
     static __inline void
    diff --git a/sys/kern/uipc_syscalls.c b/sys/kern/uipc_syscalls.c
    index 57cddd153972..202d5c868de4 100644
    --- a/sys/kern/uipc_syscalls.c
    +++ b/sys/kern/uipc_syscalls.c
    @@ -825,7 +825,7 @@ sys_sendto(struct thread *td, struct sendto_args *uap)
     	struct msghdr msg;
     	struct iovec aiov;
     
    -	msg.msg_name = uap->to;
    +	msg.msg_name = __DECONST(void *, uap->to);
     	msg.msg_namelen = uap->tolen;
     	msg.msg_iov = &aiov;
     	msg.msg_iovlen = 1;
    @@ -833,7 +833,7 @@ sys_sendto(struct thread *td, struct sendto_args *uap)
     #ifdef COMPAT_OLDSOCK
     	msg.msg_flags = 0;
     #endif
    -	aiov.iov_base = uap->buf;
    +	aiov.iov_base = __DECONST(void *, uap->buf);
     	aiov.iov_len = uap->len;
     	return (sendit(td, uap->s, &msg, uap->flags));
     }
    @@ -849,7 +849,7 @@ osend(struct thread *td, struct osend_args *uap)
     	msg.msg_namelen = 0;
     	msg.msg_iov = &aiov;
     	msg.msg_iovlen = 1;
    -	aiov.iov_base = uap->buf;
    +	aiov.iov_base = __DECONST(void *, uap->buf);
     	aiov.iov_len = uap->len;
     	msg.msg_control = 0;
     	msg.msg_flags = 0;
    @@ -1225,7 +1225,7 @@ sys_setsockopt(struct thread *td, struct setsockopt_args *uap)
     }
     
     int
    -kern_setsockopt(struct thread *td, int s, int level, int name, void *val,
    +kern_setsockopt(struct thread *td, int s, int level, int name, const void *val,
         enum uio_seg valseg, socklen_t valsize)
     {
     	struct socket *so;
    @@ -1241,7 +1241,7 @@ kern_setsockopt(struct thread *td, int s, int level, int name, void *val,
     	sopt.sopt_dir = SOPT_SET;
     	sopt.sopt_level = level;
     	sopt.sopt_name = name;
    -	sopt.sopt_val = val;
    +	sopt.sopt_val = __DECONST(void *, val);
     	sopt.sopt_valsize = valsize;
     	switch (valseg) {
     	case UIO_USERSPACE:
    @@ -1546,7 +1546,7 @@ sockargs(struct mbuf **mp, char *buf, socklen_t buflen, int type)
     }
     
     int
    -getsockaddr(struct sockaddr **namp, caddr_t uaddr, size_t len)
    +getsockaddr(struct sockaddr **namp, const struct sockaddr *uaddr, size_t len)
     {
     	struct sockaddr *sa;
     	int error;
    diff --git a/sys/kern/vfs_bio.c b/sys/kern/vfs_bio.c
    index 83e67207dc9f..ea322343d89a 100644
    --- a/sys/kern/vfs_bio.c
    +++ b/sys/kern/vfs_bio.c
    @@ -1656,7 +1656,7 @@ buf_alloc(struct bufdomain *bd)
     	if (freebufs > 0)
     		bp = uma_zalloc(buf_zone, M_NOWAIT);
     	if (bp == NULL) {
    -		atomic_fetchadd_int(&bd->bd_freebuffers, 1);
    +		atomic_add_int(&bd->bd_freebuffers, 1);
     		bufspace_daemon_wakeup(bd);
     		counter_u64_add(numbufallocfails, 1);
     		return (NULL);
    diff --git a/sys/mips/include/cpu.h b/sys/mips/include/cpu.h
    index a54ea2a2d6bf..b4f5c59f72f5 100644
    --- a/sys/mips/include/cpu.h
    +++ b/sys/mips/include/cpu.h
    @@ -71,6 +71,7 @@
     #define	cpu_getstack(td)	((td)->td_frame->sp)
     #define	cpu_setstack(td, nsp)	((td)->td_frame->sp = (nsp))
     #define	cpu_spinwait()		/* nothing */
    +#define	cpu_lock_delay()	DELAY(1)
     
     /*
      * A machine-independent interface to the CPU's counter.
    diff --git a/sys/netgraph/ng_pptpgre.c b/sys/netgraph/ng_pptpgre.c
    index 0941d8eb7d18..6ad7516a5dbc 100644
    --- a/sys/netgraph/ng_pptpgre.c
    +++ b/sys/netgraph/ng_pptpgre.c
    @@ -64,6 +64,7 @@
     #include 
     #include 
     #include 
    +#include 
     
     #include 
     #include 
    @@ -124,6 +125,8 @@ typedef u_int64_t		pptptime_t;
     #define PPTP_MIN_TIMEOUT	(PPTP_TIME_SCALE / 83)	/* 12 milliseconds */
     #define PPTP_MAX_TIMEOUT	(3 * PPTP_TIME_SCALE)	/* 3 seconds */
     
    +#define PPTP_REORDER_TIMEOUT	1
    +
     /* When we receive a packet, we wait to see if there's an outgoing packet
        we can piggy-back the ACK off of. These parameters determine the mimimum
        and maxmimum length of time we're willing to wait in order to do that.
    @@ -142,6 +145,34 @@ typedef u_int64_t		pptptime_t;
     #define SESSHASHSIZE		0x0020
     #define SESSHASH(x)		(((x) ^ ((x) >> 8)) & (SESSHASHSIZE - 1))
     
    +SYSCTL_NODE(_net_graph, OID_AUTO, pptpgre, CTLFLAG_RW, 0, "PPTPGRE");
    +
    +/*
    + * Reorder queue maximum length. Zero disables reorder.
    + *
    + * The node may keep reorder_max queue entries per session
    + * if reorder is enabled, plus allocate one more for short time.
    + *
    + * Be conservative in memory consumption by default.
    + * Lots of sessions with large queues can overflow M_NETGRAPH zone.
    + */
    +static int reorder_max = 1; /* reorder up to two swapped packets in a row */
    +SYSCTL_UINT(_net_graph_pptpgre, OID_AUTO, reorder_max, CTLFLAG_RWTUN,
    +	&reorder_max, 0, "Reorder queue maximum length");
    +
    +static int reorder_timeout = PPTP_REORDER_TIMEOUT;
    +SYSCTL_UINT(_net_graph_pptpgre, OID_AUTO, reorder_timeout, CTLFLAG_RWTUN,
    +	&reorder_timeout, 0, "Reorder timeout is milliseconds");
    +
    +/* Packet reorder FIFO queue */
    +struct ng_pptpgre_roq {
    +	SLIST_ENTRY(ng_pptpgre_roq)  next;	/* next entry of the queue */
    +	item_p			item;		/* netgraph item */
    +	u_int32_t		seq;		/* packet sequence number */
    +};
    +SLIST_HEAD(ng_pptpgre_roq_head, ng_pptpgre_roq);
    +typedef struct ng_pptpgre_roq_head roqh;
    +
     /* We keep packet retransmit and acknowlegement state in this struct */
     struct ng_pptpgre_sess {
     	node_p			node;		/* this node pointer */
    @@ -161,6 +192,9 @@ struct ng_pptpgre_sess {
     	u_int32_t		winAck;		/* seq when xmitWin will grow */
     	pptptime_t		timeSent[PPTP_XMIT_WIN];
     	LIST_ENTRY(ng_pptpgre_sess) sessions;
    +	roqh			roq;		/* reorder queue head */
    +	u_int8_t		roq_len;	/* reorder queue length */
    +	struct callout		reorderTimer;	/* reorder timeout handler */
     };
     typedef struct ng_pptpgre_sess *hpriv_p;
     
    @@ -187,13 +221,19 @@ static ng_disconnect_t	ng_pptpgre_disconnect;
     static int	ng_pptpgre_xmit(hpriv_p hpriv, item_p item);
     static void	ng_pptpgre_start_send_ack_timer(hpriv_p hpriv);
     static void	ng_pptpgre_start_recv_ack_timer(hpriv_p hpriv);
    +static void	ng_pptpgre_start_reorder_timer(hpriv_p hpriv);
     static void	ng_pptpgre_recv_ack_timeout(node_p node, hook_p hook,
     		    void *arg1, int arg2);
     static void	ng_pptpgre_send_ack_timeout(node_p node, hook_p hook,
     		    void *arg1, int arg2);
    +static void	ng_pptpgre_reorder_timeout(node_p node, hook_p hook,
    +		    void *arg1, int arg2);
     static hpriv_p	ng_pptpgre_find_session(priv_p privp, u_int16_t cid);
     static void	ng_pptpgre_reset(hpriv_p hpriv);
     static pptptime_t ng_pptpgre_time(void);
    +static void	ng_pptpgre_ack(const hpriv_p hpriv);
    +static int	ng_pptpgre_sendq(const hpriv_p hpriv, roqh *q,
    +		    const struct ng_pptpgre_roq *st);
     
     /* Parse type for struct ng_pptpgre_conf */
     static const struct ng_parse_struct_field ng_pptpgre_conf_type_fields[]
    @@ -291,6 +331,10 @@ ng_pptpgre_constructor(node_p node)
     	ng_callout_init(&priv->uppersess.rackTimer);
     	priv->uppersess.node = node;
     
    +	SLIST_INIT(&priv->uppersess.roq);
    +	priv->uppersess.roq_len = 0;
    +	ng_callout_init(&priv->uppersess.reorderTimer);
    +
     	for (i = 0; i < SESSHASHSIZE; i++)
     	    LIST_INIT(&priv->sesshash[i]);
     
    @@ -348,6 +392,11 @@ ng_pptpgre_newhook(node_p node, hook_p hook, const char *name)
     		hpriv->conf.cid = cid;
     		hpriv->node = node;
     		hpriv->hook = hook;
    +
    +		SLIST_INIT(&hpriv->roq);
    +		hpriv->roq_len = 0;
    +		ng_callout_init(&hpriv->reorderTimer);
    +
     		NG_HOOK_SET_PRIVATE(hook, hpriv);
     
     		hash = SESSHASH(cid);
    @@ -646,6 +695,49 @@ ng_pptpgre_xmit(hpriv_p hpriv, item_p item)
     	return (error);
     }
     
    +static void
    +ng_pptpgre_ack(const hpriv_p hpriv)
    +{
    +	mtx_assert(&hpriv->mtx, MA_OWNED);
    +	if (!(callout_pending(&hpriv->sackTimer))) {
    +		/* If delayed ACK is disabled, send it now */
    +		if (!hpriv->conf.enableDelayedAck) {	/* ack now */
    +			ng_pptpgre_xmit(hpriv, NULL);
    +			/* ng_pptpgre_xmit() drops the mutex */
    +			return;
    +		}
    +		/* ack later */
    +		ng_pptpgre_start_send_ack_timer(hpriv);
    +		mtx_unlock(&hpriv->mtx);
    +		return;
    +	}
    +	mtx_unlock(&hpriv->mtx);
    +}
    +
    +/*
    + * Delivers packets from the queue "q" to upper layers. Frees delivered
    + * entries with the exception of one equal to "st" that is allocated
    + * on caller's stack and not on the heap.
    + */
    +static int
    +ng_pptpgre_sendq(const hpriv_p hpriv, roqh *q, const struct ng_pptpgre_roq *st)
    +{
    +	struct ng_pptpgre_roq *np;
    +	struct mbuf *m;
    +	int error = 0;
    +
    +	mtx_assert(&hpriv->mtx, MA_NOTOWNED);
    +	while (!SLIST_EMPTY(q)) {
    +		np = SLIST_FIRST(q);
    +		SLIST_REMOVE_HEAD(q, next);
    +		NGI_GET_M(np->item, m);
    +		NG_FWD_NEW_DATA(error, np->item, hpriv->hook, m);
    +		if (np != st)
    +			free(np, M_NETGRAPH);
    +	}
    +	return (error);
    +}
    +
     /*
      * Handle an incoming packet.  The packet includes the IP header.
      */
    @@ -661,7 +753,14 @@ ng_pptpgre_rcvdata_lower(hook_p hook, item_p item)
     	int error = 0;
     	struct mbuf *m;
     
    -	NGI_GET_M(item, m);
    +	roqh sendq = SLIST_HEAD_INITIALIZER(sendq);  /* send queue on stack */
    +	struct ng_pptpgre_roq *last = NULL;	/* last packet in the sendq */
    +	struct ng_pptpgre_roq *np, *prev;
    +	struct ng_pptpgre_roq temp = { { NULL }, NULL, 0 };
    +	long diff;
    +	u_int32_t seq;
    +
    +	m = NGI_M(item);
     	/* Update stats */
     	priv->stats.recvPackets++;
     	priv->stats.recvOctets += m->m_pkthdr.len;
    @@ -673,18 +772,23 @@ ng_pptpgre_rcvdata_lower(hook_p hook, item_p item)
     	}
     
     	/* Safely pull up the complete IP+GRE headers */
    -	if (m->m_len < sizeof(*ip) + sizeof(*gre)
    -	    && (m = m_pullup(m, sizeof(*ip) + sizeof(*gre))) == NULL) {
    -		priv->stats.memoryFailures++;
    -		ERROUT(ENOBUFS);
    +	if (m->m_len < sizeof(*ip) + sizeof(*gre)) {
    +		if ((m = m_pullup(m, sizeof(*ip) + sizeof(*gre))) == NULL) {
    +			priv->stats.memoryFailures++;
    +			_NGI_M(item) = NULL;
    +			ERROUT(ENOBUFS);
    +		}
    +		_NGI_M(item) = m;
     	}
     	ip = mtod(m, const struct ip *);
     	iphlen = ip->ip_hl << 2;
     	if (m->m_len < iphlen + sizeof(*gre)) {
     		if ((m = m_pullup(m, iphlen + sizeof(*gre))) == NULL) {
     			priv->stats.memoryFailures++;
    +			_NGI_M(item) = NULL;
     			ERROUT(ENOBUFS);
     		}
    +		_NGI_M(item) = m;
     		ip = mtod(m, const struct ip *);
     	}
     	gre = (const struct greheader *)((const u_char *)ip + iphlen);
    @@ -696,8 +800,10 @@ ng_pptpgre_rcvdata_lower(hook_p hook, item_p item)
     	if (m->m_len < iphlen + grelen) {
     		if ((m = m_pullup(m, iphlen + grelen)) == NULL) {
     			priv->stats.memoryFailures++;
    +			_NGI_M(item) = NULL;
     			ERROUT(ENOBUFS);
     		}
    +		_NGI_M(item) = m;
     		ip = mtod(m, const struct ip *);
     		gre = (const struct greheader *)((const u_char *)ip + iphlen);
     	}
    @@ -726,7 +832,6 @@ ng_pptpgre_rcvdata_lower(hook_p hook, item_p item)
     		const u_int32_t	ack = be32dec(&gre->data[gre->hasSeq]);
     		const int index = ack - hpriv->recvAck - 1;
     		long sample;
    -		long diff;
     
     		/* Sanity check ack value */
     		if (PPTP_SEQ_DIFF(ack, hpriv->xmitSeq) > 0) {
    @@ -773,54 +878,178 @@ ng_pptpgre_rcvdata_lower(hook_p hook, item_p item)
     badAck:
     
     	/* See if frame contains any data */
    -	if (gre->hasSeq) {
    -		const u_int32_t seq = be32dec(&gre->data[0]);
    +	if (!gre->hasSeq) {		/* no data to deliver */
    +		priv->stats.recvLoneAcks++;
    +		mtx_unlock(&hpriv->mtx);
    +		ERROUT(0);
    +	}
     
    -		/* Sanity check sequence number */
    -		if (PPTP_SEQ_DIFF(seq, hpriv->recvSeq) <= 0) {
    -			if (seq == hpriv->recvSeq)
    -				priv->stats.recvDuplicates++;
    -			else
    -				priv->stats.recvOutOfOrder++;
    +	seq = be32dec(&gre->data[0]);
    +
    +	diff = PPTP_SEQ_DIFF(seq, hpriv->recvSeq);
    +	if (diff <= 0) {			/* late or duplicate packet */
    +		if (diff < 0 && reorder_max == 0)	/* reorder disabled */
    +			priv->stats.recvOutOfOrder++;	/* late */
    +		else
    +			priv->stats.recvDuplicates++;	/* duplicate */
    +		mtx_unlock(&hpriv->mtx);
    +		ERROUT(EINVAL);
    +	}
    +
    +	/* Trim mbuf down to internal payload */
    +	m_adj(m, iphlen + grelen);
    +	if (extralen > 0)
    +		m_adj(m, -extralen);
    +
    +#define INIT_SENDQ(t) do {				\
    +		t.item = item;				\
    +		t.seq = seq;				\
    +		SLIST_INSERT_HEAD(&sendq, &t, next);	\
    +		last = &t;				\
    +		hpriv->recvSeq = seq;			\
    +		goto deliver;				\
    +	} while(0)
    +
    +	if (diff == 1)
    +		/* the packet came in order, place it at the start of sendq */
    +		INIT_SENDQ(temp);
    +
    +	/* The packet came too early, try to enqueue it.
    +	 *
    +	 * Check for duplicate in the queue. After this loop, "prev" will be
    +	 * NULL if the packet should become new head of the queue,
    +	 * or else it should be inserted after the "prev".
    +	 */
    +	prev = SLIST_FIRST(&hpriv->roq);
    +	SLIST_FOREACH(np, &hpriv->roq, next) {
    +		diff = PPTP_SEQ_DIFF(np->seq, seq);
    +		if (diff == 0) { /* do not add duplicate, drop it */
    +			priv->stats.recvDuplicates++;
     			mtx_unlock(&hpriv->mtx);
     			ERROUT(EINVAL);
     		}
    -		hpriv->recvSeq = seq;
    -
    -		/* We need to acknowledge this packet; do it soon... */
    -		if (!(callout_pending(&hpriv->sackTimer))) {
    -			/* If delayed ACK is disabled, send it now */
    -			if (!hpriv->conf.enableDelayedAck) {	/* ack now */
    -				ng_pptpgre_xmit(hpriv, NULL);
    -				/* ng_pptpgre_xmit() drops the mutex */
    -			} else {				/* ack later */
    -				ng_pptpgre_start_send_ack_timer(hpriv);
    -				mtx_unlock(&hpriv->mtx);
    -			}
    -		} else
    -			mtx_unlock(&hpriv->mtx);
    -
    -		/* Trim mbuf down to internal payload */
    -		m_adj(m, iphlen + grelen);
    -		if (extralen > 0)
    -			m_adj(m, -extralen);
    -
    -		mtx_assert(&hpriv->mtx, MA_NOTOWNED);
    -
    -		/* Deliver frame to upper layers */
    -		NG_FWD_NEW_DATA(error, item, hpriv->hook, m);
    -	} else {
    -		priv->stats.recvLoneAcks++;
    -		mtx_unlock(&hpriv->mtx);
    -		NG_FREE_ITEM(item);
    -		NG_FREE_M(m);		/* no data to deliver */
    +		if (diff > 0) {		/* we found newer packet */
    +			if (np == prev)	/* that is the head of the queue */
    +			    prev = NULL; /* put current packet to the head */
    +			break;
    +		}
    +		prev = np;
     	}
     
    +	priv->stats.recvOutOfOrder++;	/* duplicate not found */
    +	if (hpriv->roq_len < reorder_max)
    +		goto enqueue;	/* reorder enabled and there is a room */
    +
    +	/*
    +	 * There is no room in the queue or reorder disabled.
    +	 *
    +	 * It the latter case, we may still have non-empty reorder queue
    +	 * if reorder was disabled in process of reordering.
    +	 * Then we correctly deliver the queue without growing it.
    +	 *
    +	 * In both cases, no malloc()'s until the queue is shortened.
    +	 */
    +	priv->stats.recvReorderOverflow++;
    +	if (prev == NULL) {	  /* new packet goes before the head      */
    +		INIT_SENDQ(temp); /* of reorder queue, so put it to sendq */
    +	}
    +#undef INIT_SENDQ
    +
    +	/*
    +	 * Current packet goes after the head of reorder queue.
    +	 * Move the head to sendq to make room for current packet.
    +	 */
    +	np = SLIST_FIRST(&hpriv->roq);
    +	if (prev == np)
    +		prev = NULL;
    +	SLIST_REMOVE_HEAD(&hpriv->roq, next);
    +	hpriv->roq_len--;	/* we are allowed to use malloc() now */
    +	SLIST_INSERT_HEAD(&sendq, np, next);
    +	last = np;
    +	hpriv->recvSeq = np->seq;
    +
    +enqueue:
    +	np = malloc(sizeof(*np), M_NETGRAPH, M_NOWAIT | M_ZERO);
    +	if (np == NULL) {
    +		priv->stats.memoryFailures++;
    +		/*
    +		 * Emergency: we cannot save new data.
    +		 * Flush the queue delivering all queued packets preceeding
    +		 * current one despite of gaps.
    +		 */
    +		while (!SLIST_EMPTY(&hpriv->roq)) {
    +			np = SLIST_FIRST(&hpriv->roq);
    +			if (np->seq > seq)
    +				break;
    +			SLIST_REMOVE_HEAD(&hpriv->roq, next);
    +			hpriv->roq_len--;
    +			if (last == NULL)
    +				SLIST_INSERT_HEAD(&sendq, np, next);
    +			else
    +				SLIST_INSERT_AFTER(last, np, next);
    +			last = np;
    +		}
    +
    +		/*
    +		 * Pretend we got all packets till the current one
    +		 * and acknowledge it.
    +		 */
    +		hpriv->recvSeq = seq;
    +		ng_pptpgre_ack(hpriv);	/* drops lock */
    +		ng_pptpgre_sendq(hpriv, &sendq, &temp);
    +		NG_FWD_NEW_DATA(error, item, hpriv->hook, m);
    +		ERROUT(ENOMEM);
    +	}
    +
    +	/* Add current (early) packet to the reorder queue. */
    +	np->item = item;
    +	np->seq = seq;
    +	if (prev == NULL)
    +		SLIST_INSERT_HEAD(&hpriv->roq, np, next);
    +	else
    +		SLIST_INSERT_AFTER(prev, np, next);
    +	hpriv->roq_len++;
    +
    +deliver:
    +	/* Look if we have some packets in sequence after sendq. */
    +	while (!SLIST_EMPTY(&hpriv->roq)) {
    +		np = SLIST_FIRST(&hpriv->roq);
    +		if (PPTP_SEQ_DIFF(np->seq, hpriv->recvSeq) > 1)
    +			break; /* the gap in the sequence */
    +
    +		/* "np" is in sequence, move it to the sendq. */
    +		SLIST_REMOVE_HEAD(&hpriv->roq, next);
    +		hpriv->roq_len--;
    +		hpriv->recvSeq = np->seq;
    +
    +		if (last == NULL)
    +			SLIST_INSERT_HEAD(&sendq, np, next);
    +		else
    +			SLIST_INSERT_AFTER(last, np, next);
    +		last = np;
    +	}
    +
    +	if (SLIST_EMPTY(&hpriv->roq)) {
    +		if (callout_pending(&hpriv->reorderTimer))
    +			ng_uncallout(&hpriv->reorderTimer, hpriv->node);
    +	} else {
    +		if (!callout_pending(&hpriv->reorderTimer))
    +			ng_pptpgre_start_reorder_timer(hpriv);
    +	}
    +
    +	if (SLIST_EMPTY(&sendq)) {
    +		/* Current packet has been queued, nothing to free/deliver. */
    +		mtx_unlock(&hpriv->mtx);
    +		return (error);
    +	}
    +
    +	/* We need to acknowledge last packet; do it soon... */
    +	ng_pptpgre_ack(hpriv);		/* drops lock */
    +	ng_pptpgre_sendq(hpriv, &sendq, &temp);
     	return (error);
     
     done:
     	NG_FREE_ITEM(item);
    -	NG_FREE_M(m);
     	return (error);
     }
     
    @@ -916,6 +1145,68 @@ ng_pptpgre_send_ack_timeout(node_p node, hook_p hook, void *arg1, int arg2)
     	mtx_assert(&hpriv->mtx, MA_NOTOWNED);
     }
     
    +/*
    + * Start a timer for the reorder queue. This assumes the timer is not
    + * already running.
    + */
    +static void
    +ng_pptpgre_start_reorder_timer(hpriv_p hpriv)
    +{
    +	int ticks;
    +
    +	/* Be conservative: timeout can happen up to 1 tick early */
    +	ticks = (((reorder_timeout * hz) + 1000 - 1) / 1000) + 1;
    +	ng_callout(&hpriv->reorderTimer, hpriv->node, hpriv->hook,
    +		ticks, ng_pptpgre_reorder_timeout, hpriv, 0);
    +}
    +
    +/*
    + * The oldest packet spent too much time in the reorder queue.
    + * Deliver it and next packets in sequence, if any.
    + */
    +static void
    +ng_pptpgre_reorder_timeout(node_p node, hook_p hook, void *arg1, int arg2)
    +{
    +	const priv_p priv = NG_NODE_PRIVATE(node);
    +	const hpriv_p hpriv = arg1;
    +	roqh sendq = SLIST_HEAD_INITIALIZER(sendq);
    +	struct ng_pptpgre_roq *np, *last = NULL;
    +
    +	priv->stats.recvReorderTimeouts++;
    +	mtx_lock(&hpriv->mtx);
    +	if (SLIST_EMPTY(&hpriv->roq)) { /* should not happen */
    +		mtx_unlock(&hpriv->mtx);
    +		return;
    +	}
    +
    +	last = np = SLIST_FIRST(&hpriv->roq);
    +	hpriv->roq_len--;
    +	SLIST_REMOVE_HEAD(&hpriv->roq, next);
    +	SLIST_INSERT_HEAD(&sendq, np, next);
    +
    +	/* Look if we have more packets in sequence */
    +	while (!SLIST_EMPTY(&hpriv->roq)) {
    +		np = SLIST_FIRST(&hpriv->roq);
    +		if (PPTP_SEQ_DIFF(np->seq, last->seq) > 1)
    +			break; /* the gap in the sequence */
    +
    +		/* Next packet is in sequence, move it to the sendq. */
    +		hpriv->roq_len--;
    +		SLIST_REMOVE_HEAD(&hpriv->roq, next);
    +		SLIST_INSERT_AFTER(last, np, next);
    +		last = np;
    +	}
    +
    +	hpriv->recvSeq = last->seq;
    +	if (!SLIST_EMPTY(&hpriv->roq))
    +		ng_pptpgre_start_reorder_timer(hpriv);
    +
    +	/* We need to acknowledge last packet; do it soon... */
    +	ng_pptpgre_ack(hpriv);		/* drops lock */
    +	ng_pptpgre_sendq(hpriv, &sendq, NULL);
    +	mtx_assert(&hpriv->mtx, MA_NOTOWNED);
    +}
    +
     /*************************************************************************
     		    MISC FUNCTIONS
     *************************************************************************/
    @@ -943,6 +1234,8 @@ ng_pptpgre_find_session(priv_p privp, u_int16_t cid)
     static void
     ng_pptpgre_reset(hpriv_p hpriv)
     {
    +	struct ng_pptpgre_roq *np;
    +
     	/* Reset adaptive timeout state */
     	hpriv->ato = PPTP_MAX_TIMEOUT;
     	hpriv->rtt = PPTP_TIME_SCALE / 10;
    @@ -965,6 +1258,16 @@ ng_pptpgre_reset(hpriv_p hpriv)
     	/* Stop timers */
     	ng_uncallout(&hpriv->sackTimer, hpriv->node);
     	ng_uncallout(&hpriv->rackTimer, hpriv->node);
    +	ng_uncallout(&hpriv->reorderTimer, hpriv->node);
    +
    +	/* Clear reorder queue */
    +	while (!SLIST_EMPTY(&hpriv->roq)) {
    +		np = SLIST_FIRST(&hpriv->roq);
    +		SLIST_REMOVE_HEAD(&hpriv->roq, next);
    +		NG_FREE_ITEM(np->item);
    +		free(np, M_NETGRAPH);
    +	}
    +	hpriv->roq_len = 0;
     }
     
     /*
    diff --git a/sys/netgraph/ng_pptpgre.h b/sys/netgraph/ng_pptpgre.h
    index ecba3ce1f37d..08084917dcca 100644
    --- a/sys/netgraph/ng_pptpgre.h
    +++ b/sys/netgraph/ng_pptpgre.h
    @@ -100,6 +100,10 @@ struct ng_pptpgre_stats {
     	u_int32_t recvLoneAcks;		/* ack-only packets rec'd */
     	u_int32_t recvAckTimeouts;	/* times peer failed to ack in time */
     	u_int32_t memoryFailures;	/* times we couldn't allocate memory */
    +	u_int32_t recvReorderOverflow;	/* times we dropped GRE packet
    +					   due to overflow of reorder queue */
    +	u_int32_t recvReorderTimeouts;	/* times we flushed reorder queue
    +					   due to timeout */
     };
     
     /* Keep this in sync with the above structure definition */
    @@ -120,6 +124,8 @@ struct ng_pptpgre_stats {
     	  { "recvLoneAcks",	&ng_parse_uint32_type	},	\
     	  { "recvAckTimeouts",	&ng_parse_uint32_type	},	\
     	  { "memoryFailures",	&ng_parse_uint32_type	},	\
    +	  { "recvReorderOverflow", &ng_parse_uint32_type},	\
    +	  { "recvReorderTimeouts", &ng_parse_uint32_type},	\
     	  { NULL }						\
     }
     
    diff --git a/sys/netinet/sctp_output.c b/sys/netinet/sctp_output.c
    index ddf5a4ddfd27..08f40974b07a 100644
    --- a/sys/netinet/sctp_output.c
    +++ b/sys/netinet/sctp_output.c
    @@ -3733,6 +3733,7 @@ sctp_process_cmsgs_for_init(struct sctp_tcb *stcb, struct mbuf *control, int *er
     	return (0);
     }
     
    +#if defined(INET) || defined(INET6)
     static struct sctp_tcb *
     sctp_findassociation_cmsgs(struct sctp_inpcb **inp_p,
         uint16_t port,
    @@ -3822,6 +3823,7 @@ sctp_findassociation_cmsgs(struct sctp_inpcb **inp_p,
     	}
     	return (NULL);
     }
    +#endif
     
     static struct mbuf *
     sctp_add_cookie(struct mbuf *init, int init_offset,
    @@ -12699,9 +12701,11 @@ sctp_lower_sosend(struct socket *so,
     		SCTP_INP_WUNLOCK(inp);
     		/* With the lock applied look again */
     		stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
    +#if defined(INET) || defined(INET6)
     		if ((stcb == NULL) && (control != NULL) && (port > 0)) {
     			stcb = sctp_findassociation_cmsgs(&t_inp, port, control, &net, &error);
     		}
    +#endif
     		if (stcb == NULL) {
     			SCTP_INP_WLOCK(inp);
     			SCTP_INP_DECR_REF(inp);
    diff --git a/sys/powerpc/include/atomic.h b/sys/powerpc/include/atomic.h
    index 1b3c084db196..c8e1e8447cc7 100644
    --- a/sys/powerpc/include/atomic.h
    +++ b/sys/powerpc/include/atomic.h
    @@ -510,7 +510,7 @@ atomic_load_acq_##TYPE(volatile u_##TYPE *p)			\
     	u_##TYPE v;						\
     								\
     	v = *p;							\
    -	mb();							\
    +	powerpc_lwsync();					\
     	return (v);						\
     }								\
     								\
    diff --git a/sys/powerpc/include/cpu.h b/sys/powerpc/include/cpu.h
    index 3573a0a85d20..00f8437c8c49 100644
    --- a/sys/powerpc/include/cpu.h
    +++ b/sys/powerpc/include/cpu.h
    @@ -128,6 +128,7 @@ get_cyclecount(void)
     
     #define	cpu_getstack(td)	((td)->td_frame->fixreg[1])
     #define	cpu_spinwait()		__asm __volatile("or 27,27,27") /* yield */
    +#define	cpu_lock_delay()	DELAY(1)
     
     extern char btext[];
     extern char etext[];
    diff --git a/sys/powerpc/powerpc/mp_machdep.c b/sys/powerpc/powerpc/mp_machdep.c
    index a0a97d4af3f2..49e259ad50b9 100644
    --- a/sys/powerpc/powerpc/mp_machdep.c
    +++ b/sys/powerpc/powerpc/mp_machdep.c
    @@ -100,7 +100,11 @@ machdep_ap_bootstrap(void)
     	/* Serialize console output and AP count increment */
     	mtx_lock_spin(&ap_boot_mtx);
     	ap_awake++;
    -	printf("SMP: AP CPU #%d launched\n", PCPU_GET(cpuid));
    +	if (bootverbose)
    +		printf("SMP: AP CPU #%d launched\n", PCPU_GET(cpuid));
    +	else
    +		printf("%s%d%s", ap_awake == 2 ? "Launching APs: " : "",
    +		    PCPU_GET(cpuid), ap_awake == mp_ncpus ? "\n" : " ");
     	mtx_unlock_spin(&ap_boot_mtx);
     
     	while(smp_started == 0)
    diff --git a/sys/riscv/include/cpu.h b/sys/riscv/include/cpu.h
    index 92c5c67ef597..989f8946333d 100644
    --- a/sys/riscv/include/cpu.h
    +++ b/sys/riscv/include/cpu.h
    @@ -46,6 +46,7 @@
     #define	cpu_getstack(td)	((td)->td_frame->tf_sp)
     #define	cpu_setstack(td, sp)	((td)->td_frame->tf_sp = (sp))
     #define	cpu_spinwait()		/* nothing */
    +#define	cpu_lock_delay()	DELAY(1)
     
     #ifdef _KERNEL
     
    diff --git a/sys/riscv/riscv/pmap.c b/sys/riscv/riscv/pmap.c
    index 22bec6355684..0e1299d6509b 100644
    --- a/sys/riscv/riscv/pmap.c
    +++ b/sys/riscv/riscv/pmap.c
    @@ -2098,13 +2098,20 @@ pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
     		new_l3 |= PTE_W;
     	if ((va >> 63) == 0)
     		new_l3 |= PTE_U;
    -	else if (prot & VM_PROT_WRITE)
    -		new_l3 |= PTE_D;
     
     	new_l3 |= (pn << PTE_PPN0_S);
     	if ((flags & PMAP_ENTER_WIRED) != 0)
     		new_l3 |= PTE_SW_WIRED;
    -	if ((m->oflags & VPO_UNMANAGED) == 0)
    +
    +	/*
    +	 * Set modified bit gratuitously for writeable mappings if
    +	 * the page is unmanaged. We do not want to take a fault
    +	 * to do the dirty bit accounting for these mappings.
    +	 */
    +	if ((m->oflags & VPO_UNMANAGED) != 0) {
    +		if (prot & VM_PROT_WRITE)
    +			new_l3 |= PTE_D;
    +	} else
     		new_l3 |= PTE_SW_MANAGED;
     
     	CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
    diff --git a/sys/sparc64/include/cpu.h b/sys/sparc64/include/cpu.h
    index 54deaf415167..a91159f6a7a2 100644
    --- a/sys/sparc64/include/cpu.h
    +++ b/sys/sparc64/include/cpu.h
    @@ -48,6 +48,7 @@
     #define	cpu_getstack(td)	((td)->td_frame->tf_sp)
     #define	cpu_setstack(td, sp)	((td)->td_frame->tf_sp = (sp))
     #define	cpu_spinwait()		/* nothing */
    +#define	cpu_lock_delay()	DELAY(1)
     
     #ifdef _KERNEL
     
    diff --git a/sys/sys/capability.h b/sys/sys/capability.h
    index 4b07c090e405..39195e034c56 100644
    --- a/sys/sys/capability.h
    +++ b/sys/sys/capability.h
    @@ -35,7 +35,8 @@
      * Historically, the key userspace and kernel Capsicum definitions were found
      * in this file.  However, it conflicted with POSIX.1e's capability.h, so has
      * been renamed capsicum.h.  The file remains for backwards compatibility
    - * reasons as a nested include.
    + * reasons as a nested include.  It is expected to be removed before
    + * FreeBSD 13.
      */
     #ifndef _SYS_CAPABILITY_H_
     #define	_SYS_CAPABILITY_H_
    diff --git a/sys/sys/socketvar.h b/sys/sys/socketvar.h
    index 93dc23641c7b..94bb6b490b67 100644
    --- a/sys/sys/socketvar.h
    +++ b/sys/sys/socketvar.h
    @@ -379,7 +379,8 @@ struct uio;
     /*
      * From uipc_socket and friends
      */
    -int	getsockaddr(struct sockaddr **namp, caddr_t uaddr, size_t len);
    +int	getsockaddr(struct sockaddr **namp, const struct sockaddr *uaddr,
    +	    size_t len);
     int	getsock_cap(struct thread *td, int fd, cap_rights_t *rightsp,
     	    struct file **fpp, u_int *fflagp, struct filecaps *havecaps);
     void	soabort(struct socket *so);
    diff --git a/sys/sys/syscallsubr.h b/sys/sys/syscallsubr.h
    index 2c5652c7b552..3545745f5a7f 100644
    --- a/sys/sys/syscallsubr.h
    +++ b/sys/sys/syscallsubr.h
    @@ -243,7 +243,7 @@ int	kern_setitimer(struct thread *, u_int, struct itimerval *,
     	    struct itimerval *);
     int	kern_setrlimit(struct thread *, u_int, struct rlimit *);
     int	kern_setsockopt(struct thread *td, int s, int level, int name,
    -	    void *optval, enum uio_seg valseg, socklen_t valsize);
    +	    const void *optval, enum uio_seg valseg, socklen_t valsize);
     int	kern_settimeofday(struct thread *td, struct timeval *tv,
     	    struct timezone *tzp);
     int	kern_shm_open(struct thread *td, const char *userpath, int flags,
    diff --git a/sys/sys/sysproto.h b/sys/sys/sysproto.h
    index fa54d1234201..a4e12429ebe3 100644
    --- a/sys/sys/sysproto.h
    +++ b/sys/sys/sysproto.h
    @@ -99,7 +99,7 @@ struct mount_args {
     	char type_l_[PADL_(const char *)]; const char * type; char type_r_[PADR_(const char *)];
     	char path_l_[PADL_(const char *)]; const char * path; char path_r_[PADR_(const char *)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    -	char data_l_[PADL_(caddr_t)]; caddr_t data; char data_r_[PADR_(caddr_t)];
    +	char data_l_[PADL_(void *)]; void * data; char data_r_[PADR_(void *)];
     };
     struct unmount_args {
     	char path_l_[PADL_(const char *)]; const char * path; char path_r_[PADR_(const char *)];
    @@ -132,7 +132,7 @@ struct sendmsg_args {
     };
     struct recvfrom_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char buf_l_[PADL_(caddr_t)]; caddr_t buf; char buf_r_[PADR_(caddr_t)];
    +	char buf_l_[PADL_(void *)]; void * buf; char buf_r_[PADR_(void *)];
     	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
     	char from_l_[PADL_(struct sockaddr *)]; struct sockaddr * from; char from_r_[PADR_(struct sockaddr *)];
    @@ -185,7 +185,7 @@ struct getegid_args {
     	register_t dummy;
     };
     struct profil_args {
    -	char samples_l_[PADL_(caddr_t)]; caddr_t samples; char samples_r_[PADR_(caddr_t)];
    +	char samples_l_[PADL_(char *)]; char * samples; char samples_r_[PADR_(char *)];
     	char size_l_[PADL_(size_t)]; size_t size; char size_r_[PADR_(size_t)];
     	char offset_l_[PADL_(size_t)]; size_t offset; char offset_r_[PADR_(size_t)];
     	char scale_l_[PADL_(u_int)]; u_int scale; char scale_r_[PADR_(u_int)];
    @@ -219,7 +219,7 @@ struct sigaltstack_args {
     struct ioctl_args {
     	char fd_l_[PADL_(int)]; int fd; char fd_r_[PADR_(int)];
     	char com_l_[PADL_(u_long)]; u_long com; char com_r_[PADR_(u_long)];
    -	char data_l_[PADL_(caddr_t)]; caddr_t data; char data_r_[PADR_(caddr_t)];
    +	char data_l_[PADL_(char *)]; char * data; char data_r_[PADR_(char *)];
     };
     struct reboot_args {
     	char opt_l_[PADL_(int)]; int opt; char opt_r_[PADR_(int)];
    @@ -347,7 +347,7 @@ struct socket_args {
     };
     struct connect_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char name_l_[PADL_(caddr_t)]; caddr_t name; char name_r_[PADR_(caddr_t)];
    +	char name_l_[PADL_(const struct sockaddr *)]; const struct sockaddr * name; char name_r_[PADR_(const struct sockaddr *)];
     	char namelen_l_[PADL_(int)]; int namelen; char namelen_r_[PADR_(int)];
     };
     struct getpriority_args {
    @@ -356,14 +356,14 @@ struct getpriority_args {
     };
     struct bind_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char name_l_[PADL_(caddr_t)]; caddr_t name; char name_r_[PADR_(caddr_t)];
    +	char name_l_[PADL_(const struct sockaddr *)]; const struct sockaddr * name; char name_r_[PADR_(const struct sockaddr *)];
     	char namelen_l_[PADL_(int)]; int namelen; char namelen_r_[PADR_(int)];
     };
     struct setsockopt_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
     	char level_l_[PADL_(int)]; int level; char level_r_[PADR_(int)];
     	char name_l_[PADL_(int)]; int name; char name_r_[PADR_(int)];
    -	char val_l_[PADL_(caddr_t)]; caddr_t val; char val_r_[PADR_(caddr_t)];
    +	char val_l_[PADL_(const void *)]; const void * val; char val_r_[PADR_(const void *)];
     	char valsize_l_[PADL_(int)]; int valsize; char valsize_r_[PADR_(int)];
     };
     struct listen_args {
    @@ -382,7 +382,7 @@ struct getsockopt_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
     	char level_l_[PADL_(int)]; int level; char level_r_[PADR_(int)];
     	char name_l_[PADL_(int)]; int name; char name_r_[PADR_(int)];
    -	char val_l_[PADL_(caddr_t)]; caddr_t val; char val_r_[PADR_(caddr_t)];
    +	char val_l_[PADL_(void *)]; void * val; char val_r_[PADR_(void *)];
     	char avalsize_l_[PADL_(int *)]; int * avalsize; char avalsize_r_[PADR_(int *)];
     };
     struct readv_args {
    @@ -430,10 +430,10 @@ struct mkfifo_args {
     };
     struct sendto_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char buf_l_[PADL_(caddr_t)]; caddr_t buf; char buf_r_[PADR_(caddr_t)];
    +	char buf_l_[PADL_(const void *)]; const void * buf; char buf_r_[PADR_(const void *)];
     	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    -	char to_l_[PADL_(caddr_t)]; caddr_t to; char to_r_[PADR_(caddr_t)];
    +	char to_l_[PADL_(const struct sockaddr *)]; const struct sockaddr * to; char to_r_[PADR_(const struct sockaddr *)];
     	char tolen_l_[PADL_(int)]; int tolen; char tolen_r_[PADR_(int)];
     };
     struct shutdown_args {
    @@ -471,7 +471,7 @@ struct quotactl_args {
     	char path_l_[PADL_(const char *)]; const char * path; char path_r_[PADR_(const char *)];
     	char cmd_l_[PADL_(int)]; int cmd; char cmd_r_[PADR_(int)];
     	char uid_l_[PADL_(int)]; int uid; char uid_r_[PADR_(int)];
    -	char arg_l_[PADL_(caddr_t)]; caddr_t arg; char arg_r_[PADR_(caddr_t)];
    +	char arg_l_[PADL_(void *)]; void * arg; char arg_r_[PADR_(void *)];
     };
     struct oquota_args {
     	register_t dummy;
    @@ -484,7 +484,7 @@ struct nlm_syscall_args {
     };
     struct nfssvc_args {
     	char flag_l_[PADL_(int)]; int flag; char flag_r_[PADR_(int)];
    -	char argp_l_[PADL_(caddr_t)]; caddr_t argp; char argp_r_[PADR_(caddr_t)];
    +	char argp_l_[PADL_(void *)]; void * argp; char argp_r_[PADR_(void *)];
     };
     struct lgetfh_args {
     	char fname_l_[PADL_(const char *)]; const char * fname; char fname_r_[PADR_(const char *)];
    @@ -1318,9 +1318,9 @@ struct sctp_peeloff_args {
     };
     struct sctp_generic_sendmsg_args {
     	char sd_l_[PADL_(int)]; int sd; char sd_r_[PADR_(int)];
    -	char msg_l_[PADL_(caddr_t)]; caddr_t msg; char msg_r_[PADR_(caddr_t)];
    +	char msg_l_[PADL_(void *)]; void * msg; char msg_r_[PADR_(void *)];
     	char mlen_l_[PADL_(int)]; int mlen; char mlen_r_[PADR_(int)];
    -	char to_l_[PADL_(caddr_t)]; caddr_t to; char to_r_[PADR_(caddr_t)];
    +	char to_l_[PADL_(struct sockaddr *)]; struct sockaddr * to; char to_r_[PADR_(struct sockaddr *)];
     	char tolen_l_[PADL_(__socklen_t)]; __socklen_t tolen; char tolen_r_[PADR_(__socklen_t)];
     	char sinfo_l_[PADL_(struct sctp_sndrcvinfo *)]; struct sctp_sndrcvinfo * sinfo; char sinfo_r_[PADR_(struct sctp_sndrcvinfo *)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    @@ -1329,7 +1329,7 @@ struct sctp_generic_sendmsg_iov_args {
     	char sd_l_[PADL_(int)]; int sd; char sd_r_[PADR_(int)];
     	char iov_l_[PADL_(struct iovec *)]; struct iovec * iov; char iov_r_[PADR_(struct iovec *)];
     	char iovlen_l_[PADL_(int)]; int iovlen; char iovlen_r_[PADR_(int)];
    -	char to_l_[PADL_(caddr_t)]; caddr_t to; char to_r_[PADR_(caddr_t)];
    +	char to_l_[PADL_(struct sockaddr *)]; struct sockaddr * to; char to_r_[PADR_(struct sockaddr *)];
     	char tolen_l_[PADL_(__socklen_t)]; __socklen_t tolen; char tolen_r_[PADR_(__socklen_t)];
     	char sinfo_l_[PADL_(struct sctp_sndrcvinfo *)]; struct sctp_sndrcvinfo * sinfo; char sinfo_r_[PADR_(struct sctp_sndrcvinfo *)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    @@ -1356,7 +1356,7 @@ struct pwrite_args {
     	char offset_l_[PADL_(off_t)]; off_t offset; char offset_r_[PADR_(off_t)];
     };
     struct mmap_args {
    -	char addr_l_[PADL_(caddr_t)]; caddr_t addr; char addr_r_[PADR_(caddr_t)];
    +	char addr_l_[PADL_(void *)]; void * addr; char addr_r_[PADR_(void *)];
     	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
     	char prot_l_[PADL_(int)]; int prot; char prot_r_[PADR_(int)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    @@ -1645,13 +1645,13 @@ struct cap_fcntls_get_args {
     struct bindat_args {
     	char fd_l_[PADL_(int)]; int fd; char fd_r_[PADR_(int)];
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char name_l_[PADL_(caddr_t)]; caddr_t name; char name_r_[PADR_(caddr_t)];
    +	char name_l_[PADL_(const struct sockaddr *)]; const struct sockaddr * name; char name_r_[PADR_(const struct sockaddr *)];
     	char namelen_l_[PADL_(int)]; int namelen; char namelen_r_[PADR_(int)];
     };
     struct connectat_args {
     	char fd_l_[PADL_(int)]; int fd; char fd_r_[PADR_(int)];
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char name_l_[PADL_(caddr_t)]; caddr_t name; char name_r_[PADR_(caddr_t)];
    +	char name_l_[PADL_(const struct sockaddr *)]; const struct sockaddr * name; char name_r_[PADR_(const struct sockaddr *)];
     	char namelen_l_[PADL_(int)]; int namelen; char namelen_r_[PADR_(int)];
     };
     struct chflagsat_args {
    @@ -2207,13 +2207,13 @@ struct sethostname_args {
     };
     struct osend_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char buf_l_[PADL_(caddr_t)]; caddr_t buf; char buf_r_[PADR_(caddr_t)];
    +	char buf_l_[PADL_(const void *)]; const void * buf; char buf_r_[PADR_(const void *)];
     	char len_l_[PADL_(int)]; int len; char len_r_[PADR_(int)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
     };
     struct orecv_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char buf_l_[PADL_(caddr_t)]; caddr_t buf; char buf_r_[PADR_(caddr_t)];
    +	char buf_l_[PADL_(void *)]; void * buf; char buf_r_[PADR_(void *)];
     	char len_l_[PADL_(int)]; int len; char len_r_[PADR_(int)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
     };
    @@ -2245,7 +2245,7 @@ struct orecvmsg_args {
     };
     struct osendmsg_args {
     	char s_l_[PADL_(int)]; int s; char s_r_[PADR_(int)];
    -	char msg_l_[PADL_(caddr_t)]; caddr_t msg; char msg_r_[PADR_(caddr_t)];
    +	char msg_l_[PADL_(const void *)]; const void * msg; char msg_r_[PADR_(const void *)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
     };
     struct otruncate_args {
    @@ -2258,7 +2258,7 @@ struct oftruncate_args {
     };
     struct ogetpeername_args {
     	char fdes_l_[PADL_(int)]; int fdes; char fdes_r_[PADR_(int)];
    -	char asa_l_[PADL_(caddr_t)]; caddr_t asa; char asa_r_[PADR_(caddr_t)];
    +	char asa_l_[PADL_(struct sockaddr *)]; struct sockaddr * asa; char asa_r_[PADR_(struct sockaddr *)];
     	char alen_l_[PADL_(int *)]; int * alen; char alen_r_[PADR_(int *)];
     };
     struct osethostid_args {
    @@ -2401,7 +2401,7 @@ struct freebsd6_pwrite_args {
     	char offset_l_[PADL_(off_t)]; off_t offset; char offset_r_[PADR_(off_t)];
     };
     struct freebsd6_mmap_args {
    -	char addr_l_[PADL_(caddr_t)]; caddr_t addr; char addr_r_[PADR_(caddr_t)];
    +	char addr_l_[PADL_(void *)]; void * addr; char addr_r_[PADR_(void *)];
     	char len_l_[PADL_(size_t)]; size_t len; char len_r_[PADR_(size_t)];
     	char prot_l_[PADL_(int)]; int prot; char prot_r_[PADR_(int)];
     	char flags_l_[PADL_(int)]; int flags; char flags_r_[PADR_(int)];
    diff --git a/sys/sys/tty.h b/sys/sys/tty.h
    index c85ca559361a..8b458cf115dc 100644
    --- a/sys/sys/tty.h
    +++ b/sys/sys/tty.h
    @@ -133,12 +133,8 @@ struct tty {
     	void		*t_hooksoftc;	/* (t) Soft config, for hooks. */
     	struct cdev	*t_dev;		/* (c) Primary character device. */
     
    -#ifndef PRINTF_BUFR_SIZE
    -#define TTY_PRINTF_SIZE 256
    -#else
    -#define TTY_PRINTF_SIZE PRINTF_BUFR_SIZE
    -#endif
    -	char		t_prbuf[TTY_PRINTF_SIZE]; /* (t) */
    +	size_t		t_prbufsz;	/* (t) SIGINFO buffer size. */
    +	char		t_prbuf[];	/* (t) SIGINFO buffer. */
     };
     
     /*
    diff --git a/sys/vm/vm_kern.c b/sys/vm/vm_kern.c
    index 79108ce1ef64..3720ffbee161 100644
    --- a/sys/vm/vm_kern.c
    +++ b/sys/vm/vm_kern.c
    @@ -650,8 +650,8 @@ kmap_alloc_wait(vm_map_t map, vm_size_t size)
     		map->needs_wakeup = TRUE;
     		vm_map_unlock_and_wait(map, 0);
     	}
    -	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_ALL,
    -	    VM_PROT_ALL, MAP_ACC_CHARGED);
    +	vm_map_insert(map, NULL, 0, addr, addr + size, VM_PROT_RW, VM_PROT_RW,
    +	    MAP_ACC_CHARGED);
     	vm_map_unlock(map);
     	return (addr);
     }
    diff --git a/sys/vm/vm_pageout.c b/sys/vm/vm_pageout.c
    index 9f592c38410a..c69e5e8bd9d7 100644
    --- a/sys/vm/vm_pageout.c
    +++ b/sys/vm/vm_pageout.c
    @@ -973,7 +973,7 @@ vm_pageout_laundry_worker(void *arg)
     	shortfall = 0;
     	in_shortfall = false;
     	shortfall_cycle = 0;
    -	target = 0;
    +	last_target = target = 0;
     	nfreed = 0;
     
     	/*
    diff --git a/sys/x86/x86/delay.c b/sys/x86/x86/delay.c
    index d0900c4330b8..c767250954da 100644
    --- a/sys/x86/x86/delay.c
    +++ b/sys/x86/x86/delay.c
    @@ -51,11 +51,23 @@ __FBSDID("$FreeBSD$");
     #include 
     #include 
     
    -static u_int
    -get_tsc(__unused struct timecounter *tc)
    +static void
    +delay_tsc(int n)
     {
    +	uint64_t end, now;
     
    -	return (rdtsc32());
    +	/*
    +	 * Pin the current thread ensure correct behavior if the TSCs
    +	 * on different CPUs are not in sync.
    +	 */
    +	sched_pin();
    +	now = rdtsc();
    +	end = now + tsc_freq * n / 1000000;
    +	do {
    +		cpu_spinwait();
    +		now = rdtsc();
    +	} while (now < end);
    +	sched_unpin();
     }
     
     static int
    @@ -66,22 +78,24 @@ delay_tc(int n)
     	uint64_t end, freq, now;
     	u_int last, mask, u;
     
    -	tc = timecounter;
    -	freq = atomic_load_acq_64(&tsc_freq);
    -	if (tsc_is_invariant && freq != 0) {
    -		func = get_tsc;
    -		mask = ~0u;
    -	} else {
    -		if (tc->tc_quality <= 0)
    -			return (0);
    -		func = tc->tc_get_timecount;
    -		mask = tc->tc_counter_mask;
    -		freq = tc->tc_frequency;
    +	/*
    +	 * Only use the TSC if it is P-state invariant.  If the TSC is
    +	 * not P-state invariant and the CPU is not running at the
    +	 * "full" P-state, then the TSC will increment at some rate
    +	 * less than tsc_freq and delay_tsc() will wait too long.
    +	 */
    +	if (tsc_is_invariant && tsc_freq != 0) {
    +		delay_tsc(n);
    +		return (1);
     	}
    +	tc = timecounter;
    +	if (tc->tc_quality <= 0)
    +		return (0);
    +	func = tc->tc_get_timecount;
    +	mask = tc->tc_counter_mask;
    +	freq = tc->tc_frequency;
     	now = 0;
     	end = freq * n / 1000000;
    -	if (func == get_tsc)
    -		sched_pin();
     	last = func(tc) & mask;
     	do {
     		cpu_spinwait();
    @@ -92,8 +106,6 @@ delay_tc(int n)
     			now += u - last;
     		last = u;
     	} while (now < end);
    -	if (func == get_tsc)
    -		sched_unpin();
     	return (1);
     }
     
    @@ -110,3 +122,22 @@ DELAY(int n)
     	init_ops.early_delay(n);
     	TSEXIT();
     }
    +
    +void
    +cpu_lock_delay(void)
    +{
    +
    +	/*
    +	 * Use TSC to wait for a usec if present, otherwise fall back
    +	 * to reading from port 0x84.  We can't call into timecounters
    +	 * for this delay since timecounters might use spin locks.
    +	 *
    +	 * Note that unlike delay_tc(), this uses the TSC even if it
    +	 * is not P-state invariant.  For this function it is ok to
    +	 * wait even a few usecs.
    +	 */
    +	if (tsc_freq != 0)
    +		delay_tsc(1);
    +	else
    +		inb(0x84);
    +}
    diff --git a/tools/build/Makefile b/tools/build/Makefile
    index 0e6d77716852..40915c66a498 100644
    --- a/tools/build/Makefile
    +++ b/tools/build/Makefile
    @@ -59,15 +59,72 @@ SUBDIR=		cross-build
     # Needed to build config (since it uses libnv)
     SYSINCS+=	${SRCTOP}/sys/sys/nv.h ${SRCTOP}/sys/sys/cnv.h
     
    +# We want to run the build with only ${WORLDTMP} in $PATH to ensure we don't
    +# accidentally run tools that are incompatible but happen to be in $PATH.
    +# This is especially important when building on Linux/MacOS where many of the
    +# programs used during the build accept different flags or generate different
    +# output. On those platforms we only symlink the tools known to be compatible
    +# (e.g. basic utilities such as mkdir) into ${WORLDTMP} and build all others
    +# from the FreeBSD sources during the bootstrap-tools stage.
    +
    +# basic commands: It is fine to use the host version for all of these even on
    +# Linux/MacOS since we only use flags that are supported by all of them.
    +_host_tools_to_symlink=	basename bzip2 bunzip2 chmod chown cmp comm cp date \
    +	dirname echo env false find fmt gzip gunzip head hostname id ln ls \
    +	mkdir mv nice patch rm realpath sh sleep stat tee touch tr true uname \
    +	uniq wc which
    +
    +# We also need a symlink to the absolute path to the make binary used for
    +# the toplevel makefile. This is not necessarily the same as `which make`
    +# since e.g. on Linux and MacOS that will be GNU make.
    +_make_abs!=	which "${MAKE}"
    +_host_abs_tools_to_symlink=	${_make_abs}:make ${_make_abs}:bmake
    +
    +host-symlinks:
    +	@echo "Linking host tools into ${DESTDIR}/bin"
    +.for _tool in ${_host_tools_to_symlink}
    +	@if [ ! -e "${DESTDIR}/bin/${_tool}" ]; then \
    +		source_path=`which ${_tool}`; \
    +		if [ ! -e "$${source_path}" ] ; then \
    +			echo "Cannot find host tool '${_tool}'"; false; \
    +		fi; \
    +		ln -sfnv "$${source_path}" "${DESTDIR}/bin/${_tool}"; \
    +	fi
    +.endfor
    +.for _tool in ${_host_abs_tools_to_symlink}
    +	@source_path="${_tool:S/:/ /:[1]}"; \
    +	target_path="${DESTDIR}/bin/${_tool:S/:/ /:[2]}"; \
    +	if [ ! -e "$${target_path}" ] ; then \
    +		if [ ! -e "$${source_path}" ] ; then \
    +			echo "Host tool '${src_path}' is missing"; false; \
    +		fi; \
    +		ln -sfnv "$${source_path}" "$${target_path}"; \
    +	fi
    +.endfor
     
     # Create all the directories that are needed during the legacy, bootstrap-tools
     # and cross-tools stages. We do this here using mkdir since mtree may not exist
     # yet (this happens if we are crossbuilding from Linux/Mac).
     installdirs:
    -.for _dir in bin sbin usr/bin usr/sbin usr/lib usr/include lib/geom lib/casper
    +.for _dir in bin usr/lib usr/include lib/geom lib/casper
     	mkdir -p "${DESTDIR}/${_dir}"
     .endfor
    +# Link usr/bin, sbin, and usr/sbin to bin so that it doesn't matter whether a
    +# bootstrap tool was added to WORLTMP with a symlink or by building it in the
    +# bootstrap-tools phase. We could also overrride BINDIR when building bootstrap
    +# tools but adding the symlinks is easier and means all tools are also
    +# in the directory that they are installed to normally.
     
    +.for _dir in sbin usr/sbin usr/bin
    +# delete existing directories from before r340157
    +	@if [ ! -L ${DESTDIR}/${_dir} ]; then \
    +	    echo "removing old non-symlink ${DESTDIR}/${_dir}"; \
    +	    rm -rf "${DESTDIR}/${_dir}"; \
    +	fi
    +.endfor
    +	ln -sfn bin ${DESTDIR}/sbin
    +	ln -sfn ../bin ${DESTDIR}/usr/bin
    +	ln -sfn ../bin ${DESTDIR}/usr/sbin
     .for _group in ${INCSGROUPS:NINCS}
     	mkdir -p "${DESTDIR}/${${_group}DIR}"
     .endfor
    diff --git a/tools/build/options/WITHOUT_BIND_NOW b/tools/build/options/WITHOUT_BIND_NOW
    new file mode 100644
    index 000000000000..f35a7653aa3b
    --- /dev/null
    +++ b/tools/build/options/WITHOUT_BIND_NOW
    @@ -0,0 +1,5 @@
    +.\" $FreeBSD$
    +Do not build all binaries with the
    +.Dv DF_BIND_NOW
    +flag set.
    +Run-time relocation processing will be performed on demand.
    diff --git a/tools/build/options/WITHOUT_ED_CRYPTO b/tools/build/options/WITHOUT_ED_CRYPTO
    deleted file mode 100644
    index d4572640d4c1..000000000000
    --- a/tools/build/options/WITHOUT_ED_CRYPTO
    +++ /dev/null
    @@ -1,4 +0,0 @@
    -.\" $FreeBSD$
    -Set to build
    -.Xr ed 1
    -without support for encryption/decryption.
    diff --git a/tools/build/options/WITH_BIND_NOW b/tools/build/options/WITH_BIND_NOW
    new file mode 100644
    index 000000000000..02e4c37352b4
    --- /dev/null
    +++ b/tools/build/options/WITH_BIND_NOW
    @@ -0,0 +1,5 @@
    +.\" $FreeBSD$
    +Build all binaries with the
    +.Dv DF_BIND_NOW
    +flag set to indicate that the run-time loader should perform all relocation
    +processing at process startup rather than on demand.
    diff --git a/tools/build/options/WITH_LLD_BOOTSTRAP b/tools/build/options/WITH_LLD_BOOTSTRAP
    index 4977b9767abf..b3b392eb4d13 100644
    --- a/tools/build/options/WITH_LLD_BOOTSTRAP
    +++ b/tools/build/options/WITH_LLD_BOOTSTRAP
    @@ -1,2 +1,3 @@
     .\" $FreeBSD$
    -Set to build the LLD linker during the bootstrap phase of the build.
    +Set to build the LLD linker during the bootstrap phase of the build,
    +and use it during buildworld and buildkernel.
    diff --git a/tools/tools/locale/Makefile b/tools/tools/locale/Makefile
    index 9e8483dc445c..250d6cd396b1 100644
    --- a/tools/tools/locale/Makefile
    +++ b/tools/tools/locale/Makefile
    @@ -10,13 +10,10 @@
     
     .OBJDIR:	.
     
    -.if !defined(CLDRDIR)
    -CLDRDIR!=	grep ^cldr etc/unicode.conf | cut -f 2 -d " "
    +.if !defined(UNIDIR)
    +.error UNIDIR is not set
     .endif
    -.if !defined(UNIDATADIR)
    -UNIDATADIR!=	grep ^unidata etc/unicode.conf | cut -f 2 -d " "
    -.endif
    -PASSON=		CLDRDIR="${CLDRDIR}" UNIDATADIR="${UNIDATADIR}"
    +PASSON=		UNIDIR="${UNIDIR}"
     
     ETCDIR=		${.CURDIR}/etc
     
    @@ -49,12 +46,8 @@ COLLATIONS_SPECIAL_ENV+=	${area}.${enc}
     .endfor
     PASSON+=	COLLATIONS_SPECIAL="${COLLATIONS_SPECIAL_ENV}"
     
    -.if defined(LC)
    -LC:=	--lc=${LC}
    -.endif
    -
     all:
    -	cp ${ETCDIR}/common.UTF-8.src ${CLDRDIR}/posix/xx_Comm_US.UTF-8.src
    +	cp ${ETCDIR}/common.UTF-8.src ${UNIDIR}/posix/xx_Comm_C.UTF-8.src
     .for t in ${TYPES}
     .  if ${KNOWN:M${t}}
     	test -d ${t} || mkdir ${t}
    @@ -69,8 +62,9 @@ install: install-${t}
     install-${t}:
     .  if ${KNOWN:M${t}}
     	rm -rf ${.CURDIR}/${t}.draft
    -	rm -rf ${.CURDIR}/../../../share/${t}
    -	mv ${.CURDIR}/${t} ${.CURDIR}/../../../share/${t}
    +	rm -f ${.CURDIR}/../../../share/${t}/Makefile
    +	rm -f ${.CURDIR}/../../../share/${t}/*.src
    +	mv ${.CURDIR}/${t}/* ${.CURDIR}/../../../share/${t}/
     .  endif
     .endfor
     
    @@ -86,10 +80,9 @@ post-install:
     gen-${t}:
     	mkdir -p ${t} ${t}.draft
     	perl -I tools tools/cldr2def.pl \
    -		--cldr=$$(realpath ${CLDRDIR}) \
    -		--unidata=$$(realpath ${UNIDATADIR}) \
    +		--unidir=$$(realpath ${UNIDIR}) \
     		--etc=$$(realpath ${ETCDIR}) \
    -		--type=${t} ${LC}
    +		--type=${t}
     
     build-${t}: gen-${t}
     	env ${PASSON} tools/finalize ${t}
    @@ -101,15 +94,16 @@ build-colldef:	static-colldef
     
     static-colldef:
     .for area enc in ${COLLATION_SPECIAL}
    -	awk -f tools/extract-colldef.awk ${CLDRDIR}/posix/${area}.${enc}.src > colldef.draft/${area}.${enc}.src
    +	awk -f tools/extract-colldef.awk ${UNIDIR}/posix/${area}.${enc}.src > \
    +	    colldef.draft/${area}.${enc}.src
     .endfor
     
     transfer-rollup:
    -	cp ${ETCDIR}/common.UTF-8.src ${CLDRDIR}/posix/xx_Comm_US.UTF-8.src
    +	cp ${ETCDIR}/common.UTF-8.src ${UNIDIR}/posix/xx_Comm_C.UTF-8.src
     
     rollup:
     	perl -I tools tools/utf8-rollup.pl \
    -		--cldr=$$(realpath ${CLDRDIR}) \
    +		--unidir=$$(realpath ${UNIDIR}) \
     		--etc=$$(realpath ${ETCDIR})
     
     clean:
    @@ -159,33 +153,33 @@ ENCODINGS=	Big5 \
     
     
     POSIX:
    -.if exists (${CLDRDIR}/tools/java/cldr.jar)
    -	mkdir -p ${CLDRDIR}/posix
    +.if exists (${UNIDIR}/tools/java/cldr.jar)
    +	mkdir -p ${UNIDIR}/posix
     .  for area in ${BASE_LOCALES_OF_INTEREST}
    -.    if !exists(${CLDRDIR}/posix/${area}.UTF-8.src)
    -	java -DCLDR_DIR=${CLDRDIR:Q} -jar ${CLDRDIR}/tools/java/cldr.jar \
    +.    if !exists(${UNIDIR}/posix/${area}.UTF-8.src)
    +	java -DCLDR_DIR=${UNIDIR:Q} -jar ${UNIDIR}/tools/java/cldr.jar \
     		org.unicode.cldr.posix.GeneratePOSIX \
    -		-d ${CLDRDIR}/posix -m ${area} -c UTF-8
    +		-d ${UNIDIR}/posix -m ${area} -c UTF-8
     .    endif
     .  endfor
     .  for area encoding in ${COLLATION_SPECIAL}
    -.    if !exists(${CLDRDIR}/posix/${area}.${encoding}.src)
    -	java -DCLDR_DIR=${CLDRDIR:Q} -jar ${CLDRDIR}/tools/java/cldr.jar \
    +.    if !exists(${UNIDIR}/posix/${area}.${encoding}.src)
    +	java -DCLDR_DIR=${UNIDIR:Q} -jar ${UNIDIR}/tools/java/cldr.jar \
     		org.unicode.cldr.posix.GeneratePOSIX \
    -		-d ${CLDRDIR}/posix -m ${area} -c ${encoding}
    +		-d ${UNIDIR}/posix -m ${area} -c ${encoding}
     .    endif
     .  endfor
     .  for enc in ${ENCODINGS}
    -.  if !exists(${CLDRDIR}/posix/${enc}.cm)
    -	java -DCLDR_DIR=${CLDRDIR:Q} -jar ${CLDRDIR}/tools/java/cldr.jar \
    +.  if !exists(${UNIDIR}/posix/${enc}.cm)
    +	java -DCLDR_DIR=${UNIDIR:Q} -jar ${UNIDIR}/tools/java/cldr.jar \
     		org.unicode.cldr.posix.GenerateCharmap \
    -		-d ${CLDRDIR}/posix -c ${enc}
    +		-d ${UNIDIR}/posix -c ${enc}
     .  endif
     .  endfor
     .else
     	@echo "Please install CLDR toolset for the desired release"
    -	@echo "It should go at ${CLDRDIR}/tools"
    +	@echo "It should go at ${UNIDIR}/tools"
     .endif
     
     clean-POSIX:
    -	rm -f ${CLDRDIR}/posix/*
    +	rm -f ${UNIDIR}/posix/*
    diff --git a/tools/tools/locale/README b/tools/tools/locale/README
    index 1874b750315c..4badae846927 100644
    --- a/tools/tools/locale/README
    +++ b/tools/tools/locale/README
    @@ -9,30 +9,23 @@ Tools needed:
     	devel/p5-Tie-IxHash
     	textproc/p5-XML-Parser
     
    -Fetch CLDR data from: http://unicode.org/Public/cldr/.  You need all of the
    +1. Fetch CLDR data from: http://unicode.org/Public/cldr/.  You need all of the
     core.zip, keyboards.zip, and tools.zip.
    -
    -Extract:
    -	mkdir -p ~/unicode/cldr/v33.0
    -	cd ~/unicode/cldr/v33.0
    -	unzip ~/core.zip ~/keyboards.zip ~/tools.zip
    -
    -Fetch unidata (UCD.zip) from http://www.unicode.org/Public/zipped/latest.
    -
    -Extract:
    -	mkdir -p ~/unicode/UNIDATA/11.0.0
    -	cd ~/unicode/UNIDATA/11.0.0
    +2. Fetch unidata (UCD.zip) from http://www.unicode.org/Public/zipped/latest.
    +3. Extract:
    +	mkdir -p ~/unicode
    +	cd ~/unicode
    +	unzip ~/core.zip
    +	unzip ~/keyboards.zip
    +	unzip ~/tools.zip
     	unzip ~/UCD.zip
    -
    -Either modify tools/tools/locales/etc/unicode.conf or export variables:
    -	CLDRDIR=~/unicode/cldr/v33.0; export CLDRDIR
    -	UNIDATADIR=~/unicode/UNIDATA/9.0.0; export UNIDATADIR
    -
    -Build the CLDR tools:
    -	cd $CLDRDIR/tools/java
    +4. Export variable:
    +	UNIDIR=~/unicode; export UNIDIR
    +5. Build the CLDR tools:
    +	cd $UNIDIR/tools/java
     	ant jar
    -
    -Run:
    +6. Build POSIX data files from CLDR data:
     	make POSIX
    +7. Build and install new locale data:
     	make
     	make install
    diff --git a/tools/tools/locale/etc/unicode.conf b/tools/tools/locale/etc/unicode.conf
    deleted file mode 100644
    index 8d5e4e104d01..000000000000
    --- a/tools/tools/locale/etc/unicode.conf
    +++ /dev/null
    @@ -1,4 +0,0 @@
    -# $FreeBSD$
    -
    -cldr ~/unicode/cldr/30.0.3
    -unidata ~/unicode/UNIDATA/9.0.0
    diff --git a/tools/tools/locale/tools/UTF82encoding.pl b/tools/tools/locale/tools/UTF82encoding.pl
    deleted file mode 100755
    index dc43c1cb8056..000000000000
    --- a/tools/tools/locale/tools/UTF82encoding.pl
    +++ /dev/null
    @@ -1,78 +0,0 @@
    -#!/usr/bin/perl -w
    -
    -use strict;
    -use Data::Dumper;
    -
    -if ($#ARGV != 1) {
    -	print "Usage: $0  \n";
    -	exit;
    -}
    -
    -open(FIN, "$ARGV[0]/posix/UTF-8.cm");
    -my @lines = ;
    -chomp(@lines);
    -close(FIN);
    -
    -my %cm = ();
    -foreach my $line (@lines) {
    -	next if ($line =~ /^#/);
    -	next if ($line eq "");
    -	next if ($line !~ /^;
    -chomp(@lines);
    -close(FIN);
    -
    -foreach my $line (@lines) {
    -	if ($line =~ /^#/) {
    -		print "$line\n";
    -		next;
    -	}
    -
    -	my @l = split(//, $line);
    -	for (my $i = 0; $i <= $#l; $i++) {
    -		my $hex = sprintf("%X", ord($l[$i]));
    -
    -		if ((		      $l[$i] gt "\x20")
    -		 && ($l[$i] lt "a" || $l[$i] gt "z")
    -		 && ($l[$i] lt "A" || $l[$i] gt "Z")
    -		 && ($l[$i] lt "0" || $l[$i] gt "9")
    -		 && ($l[$i] lt "\x80")) {
    -			print $l[$i];
    -			next;
    -		}
    -
    -		if (defined $cm{$hex}) {
    -			print $cm{$hex};
    -			next;
    -		}
    -
    -		$hex = sprintf("%X%X", ord($l[$i]), ord($l[$i + 1]));
    -		if (defined $cm{$hex}) {
    -			$i += 1;
    -			print $cm{$hex};
    -			next;
    -		}
    -
    -		$hex = sprintf("%X%X%X",
    -		    ord($l[$i]), ord($l[$i + 1]), ord($l[$i + 2 ]));
    -		if (defined $cm{$hex}) {
    -			$i += 2;
    -			print $cm{$hex};
    -			next;
    -		}
    -
    -		print "\n--$hex--\n";
    -	}
    -	print "\n";
    -
    -}
    diff --git a/tools/tools/locale/tools/changeoffset.pl b/tools/tools/locale/tools/changeoffset.pl
    deleted file mode 100755
    index 22671927beeb..000000000000
    --- a/tools/tools/locale/tools/changeoffset.pl
    +++ /dev/null
    @@ -1,30 +0,0 @@
    -#!/usr/bin/perl -w
    -
    -if ($#ARGV != 2) {
    -	print STDERR "Usage: $0   \n";
    -	print STDERR "offset should be in hex and can be prefixed with a -.\n";
    -	exit;
    -}
    -
    -$fin = $ARGV[0];
    -$fout = $ARGV[1];
    -$offset = hex($ARGV[2]);
    -
    -open(FIN, "$fin.TXT") or die "Cannot open $fin.TXT for reading";
    -open(FOUT, ">$fout.TXT");
    -
    -foreach my $l () {
    -	my @a = split(" ", $l);
    -
    -	if ($a[0] =~ /^0x[0-9a-fA-F]+$/) {
    -		my $c = length($a[0]);
    -		my $h = hex($a[0]) + $offset;
    -
    -		$l = sprintf("0x%*X%s", $c - 2, $h, substr($l, $c));
    -	}
    -
    -	print FOUT $l;
    -}
    -
    -close(FOUT);
    -close(FIN);
    diff --git a/tools/tools/locale/tools/cldr2def.pl b/tools/tools/locale/tools/cldr2def.pl
    index a34c5477670b..82a36793db36 100755
    --- a/tools/tools/locale/tools/cldr2def.pl
    +++ b/tools/tools/locale/tools/cldr2def.pl
    @@ -6,32 +6,27 @@ use File::Copy;
     use XML::Parser;
     use Tie::IxHash;
     use Text::Iconv;
    -use Data::Dumper;
    +#use Data::Dumper;
     use Getopt::Long;
     use Digest::SHA qw(sha1_hex);
     require "charmaps.pm";
     
     
     if ($#ARGV < 2) {
    -	print "Usage: $0 --cldr= --unidata= --etc= --type= [--lc=]\n";
    +	print "Usage: $0 --unidir= --etc= --type=\n";
     	exit(1);
     }
     
     my $DEFENCODING = "UTF-8";
    -my @filter = ();
     
    -my $CLDRDIR = undef;
    -my $UNIDATADIR = undef;
    +my $UNIDIR = undef;
     my $ETCDIR = undef;
     my $TYPE = undef;
    -my $doonly = undef;
     
     my $result = GetOptions (
    -		"cldr=s"	=> \$CLDRDIR,
    -		"unidata=s"	=> \$UNIDATADIR,
    +		"unidir=s"	=> \$UNIDIR,
     		"etc=s"		=> \$ETCDIR,
     		"type=s"	=> \$TYPE,
    -		"lc=s"		=> \$doonly
     	    );
     
     my %convertors = ();
    @@ -47,8 +42,8 @@ get_languages();
     
     my %utf8map = ();
     my %utf8aliases = ();
    -get_unidata($UNIDATADIR);
    -get_utf8map("$CLDRDIR/posix/$DEFENCODING.cm");
    +get_unidata($UNIDIR);
    +get_utf8map("$UNIDIR/posix/$DEFENCODING.cm");
     get_encodings("$ETCDIR/charmaps");
     
     my %keys = ();
    @@ -397,40 +392,24 @@ sub get_languages {
     	%translations = %{$data{T}}; 
     	%alternativemonths = %{$data{AM}}; 
     	%encodings = %{$data{E}}; 
    -
    -	return if (!defined $doonly);
    -
    -	my @a = split(/_/, $doonly);
    -	if ($#a == 1) {
    -		$filter[0] = $a[0];
    -		$filter[1] = "x";
    -		$filter[2] = $a[1];
    -	} elsif ($#a == 2) {
    -		$filter[0] = $a[0];
    -		$filter[1] = $a[1];
    -		$filter[2] = $a[2];
    -	}
    -
    -	print Dumper(@filter);
    -	return;
     }
     
     sub transform_ctypes {
    +	# Add the C.UTF-8
    +	$languages{"C"}{"x"}{data}{"x"}{$DEFENCODING} = undef;
    +
     	foreach my $l (sort keys(%languages)) {
     	foreach my $f (sort keys(%{$languages{$l}})) {
     	foreach my $c (sort keys(%{$languages{$l}{$f}{data}})) {
    -		next if ($#filter == 2 && ($filter[0] ne $l
    -		    || $filter[1] ne $f || $filter[2] ne $c));
     		next if (defined $languages{$l}{$f}{definitions}
     		    && $languages{$l}{$f}{definitions} !~ /$TYPE/);
     		$languages{$l}{$f}{data}{$c}{$DEFENCODING} = 0;	# unread
    -		my $file;
    -		$file = $l . "_";
    -		$file .= $f . "_" if ($f ne "x");
    -		$file .= $c;
    +		my $file = $l;
    +		$file .= "_" . $f if ($f ne "x");
    +		$file .= "_" . $c if ($c ne "x");
     		my $actfile = $file;
     
    -		my $filename = "$CLDRDIR/posix/xx_Comm_US.UTF-8.src";
    +		my $filename = "$UNIDIR/posix/xx_Comm_C.UTF-8.src";
     		if (! -f $filename) {
     			print STDERR "Cannot open $filename\n";
     			next;
    @@ -453,7 +432,7 @@ sub transform_ctypes {
     		close(FOUT);
     		foreach my $enc (sort keys(%{$languages{$l}{$f}{data}{$c}})) {
     			next if ($enc eq $DEFENCODING);
    -			$filename = "$CLDRDIR/posix/$file.$DEFENCODING.src";
    +			$filename = "$UNIDIR/posix/$file.$DEFENCODING.src";
     			if (! -f $filename) {
     				print STDERR "Cannot open $filename\n";
     				next;
    @@ -492,8 +471,6 @@ sub transform_collation {
     	foreach my $l (sort keys(%languages)) {
     	foreach my $f (sort keys(%{$languages{$l}})) {
     	foreach my $c (sort keys(%{$languages{$l}{$f}{data}})) {
    -		next if ($#filter == 2 && ($filter[0] ne $l
    -		    || $filter[1] ne $f || $filter[2] ne $c));
     		next if (defined $languages{$l}{$f}{definitions}
     		    && $languages{$l}{$f}{definitions} !~ /$TYPE/);
     		$languages{$l}{$f}{data}{$c}{$DEFENCODING} = 0;	# unread
    @@ -503,15 +480,15 @@ sub transform_collation {
     		$file .= $c;
     		my $actfile = $file;
     
    -		my $filename = "$CLDRDIR/posix/$file.$DEFENCODING.src";
    +		my $filename = "$UNIDIR/posix/$file.$DEFENCODING.src";
     		$filename = "$ETCDIR/$file.$DEFENCODING.src"
     		    if (! -f $filename);
     		if (! -f $filename
     		 && defined $languages{$l}{$f}{fallback}) {
     			$file = $languages{$l}{$f}{fallback};
    -			$filename = "$CLDRDIR/posix/$file.$DEFENCODING.src";
    +			$filename = "$UNIDIR/posix/$file.$DEFENCODING.src";
     		}
    -		$filename = "$CLDRDIR/posix/$file.$DEFENCODING.src"
    +		$filename = "$UNIDIR/posix/$file.$DEFENCODING.src"
     		    if (! -f $filename);
     		if (! -f $filename) {
     			print STDERR
    @@ -562,8 +539,6 @@ sub get_fields {
     	foreach my $l (sort keys(%languages)) {
     	foreach my $f (sort keys(%{$languages{$l}})) {
     	foreach my $c (sort keys(%{$languages{$l}{$f}{data}})) {
    -		next if ($#filter == 2 && ($filter[0] ne $l
    -		    || $filter[1] ne $f || $filter[2] ne $c));
     		next if (defined $languages{$l}{$f}{definitions}
     		    && $languages{$l}{$f}{definitions} !~ /$TYPE/);
     
    @@ -573,15 +548,15 @@ sub get_fields {
     		$file .= $f . "_" if ($f ne "x");
     		$file .= $c;
     
    -		my $filename = "$CLDRDIR/posix/$file.$DEFENCODING.src";
    +		my $filename = "$UNIDIR/posix/$file.$DEFENCODING.src";
     		$filename = "$ETCDIR/$file.$DEFENCODING.src"
     		    if (! -f $filename);
     		if (! -f $filename
     		 && defined $languages{$l}{$f}{fallback}) {
     			$file = $languages{$l}{$f}{fallback};
    -			$filename = "$CLDRDIR/posix/$file.$DEFENCODING.src";
    +			$filename = "$UNIDIR/posix/$file.$DEFENCODING.src";
     		}
    -		$filename = "$CLDRDIR/posix/$file.$DEFENCODING.src"
    +		$filename = "$UNIDIR/posix/$file.$DEFENCODING.src"
     		    if (! -f $filename);
     		if (! -f $filename) {
     			print STDERR
    @@ -701,8 +676,6 @@ sub print_fields {
     	foreach my $l (sort keys(%languages)) {
     	foreach my $f (sort keys(%{$languages{$l}})) {
     	foreach my $c (sort keys(%{$languages{$l}{$f}{data}})) {
    -		next if ($#filter == 2 && ($filter[0] ne $l
    -		    || $filter[1] ne $f || $filter[2] ne $c));
     		next if (defined $languages{$l}{$f}{definitions}
     		    && $languages{$l}{$f}{definitions} !~ /$TYPE/);
     		foreach my $enc (sort keys(%{$languages{$l}{$f}{data}{$c}})) {
    @@ -849,7 +822,6 @@ EOF
     }
     
     sub make_makefile {
    -	return if ($#filter > -1);
     	print "Creating Makefile for $TYPE\n";
     	my $SRCOUT;
     	my $SRCOUT2;
    @@ -911,8 +883,16 @@ LOCALEDIR=	\${SHAREDIR}/locale
     FILESNAME=	$FILESNAMES{$TYPE}
     .SUFFIXES:	.src .${SRCOUT2}
     ${MAPLOC}
    +EOF
    +
    +	if ($TYPE eq "colldef" || $TYPE eq "ctypedef") {
    +		print FOUT <
     
    +EOF
    +	}
    +
    +	print FOUT < 0) {
     			my $link = shift(@files);
    +			$link =~ s/_x_x//;	# special case for C
     			$link =~ s/_x_/_/;	# strip family if none there
     			foreach my $file (@files) {
     				my @a = split(/_/, $file);
    @@ -976,8 +957,6 @@ EOF
     	foreach my $l (sort keys(%languages)) {
     	foreach my $f (sort keys(%{$languages{$l}})) {
     	foreach my $c (sort keys(%{$languages{$l}{$f}{data}})) {
    -		next if ($#filter == 2 && ($filter[0] ne $l
    -		    || $filter[1] ne $f || $filter[2] ne $c));
     		next if (defined $languages{$l}{$f}{definitions}
     		    && $languages{$l}{$f}{definitions} !~ /$TYPE/);
     		if (defined $languages{$l}{$f}{data}{$c}{$DEFENCODING}
    @@ -987,9 +966,9 @@ EOF
     			next;
     		}
     		foreach my $e (sort keys(%{$languages{$l}{$f}{data}{$c}})) {
    -			my $file = $l . "_";
    -			$file .= $f . "_" if ($f ne "x");
    -			$file .= $c;
    +			my $file = $l;
    +			$file .= "_" . $f if ($f ne "x");
    +			$file .= "_" . $c if ($c ne "x");
     			next if (!defined $languages{$l}{$f}{data}{$c}{$e});
     			print FOUT "LOCALES+=\t$file.$e\n";
     		}
    diff --git a/tools/tools/locale/tools/finalize b/tools/tools/locale/tools/finalize
    index b5b550c67688..d13d802227e0 100755
    --- a/tools/tools/locale/tools/finalize
    +++ b/tools/tools/locale/tools/finalize
    @@ -116,13 +116,13 @@ then
     	else {last1 = $1; last2 = $2}}' ${TEMP2} > ${TEMP3}
     	rm -f ${TEMP2}
     	/usr/bin/sed -E -e 's/[ ]+/ /g' \
    -		${CLDRDIR}/posix/UTF-8.cm \
    +		${UNIDIR}/posix/UTF-8.cm \
     		> ${base}/../etc/final-maps/map.UTF-8
     	/usr/bin/sed -E -e 's/[ ]+/ /g' \
    -		${CLDRDIR}/posix/eucCN.cm \
    +		${UNIDIR}/posix/eucCN.cm \
     		> ${base}/../etc/final-maps/map.eucCN
     	/usr/bin/sed -E -e 's/[ ]+/ /g' \
    -		${CLDRDIR}/posix/eucCN.cm \
    +		${UNIDIR}/posix/eucCN.cm \
     		> ${base}/../etc/final-maps/map.GB2312
     	CHARMAPS="ARMSCII-8 Big5 CP1131 CP1251 \
     		CP866 GBK ISCII-DEV ISO8859-1 \
    diff --git a/tools/tools/locale/tools/unicode2src.pl b/tools/tools/locale/tools/unicode2src.pl
    deleted file mode 100755
    index 76628c175e3d..000000000000
    --- a/tools/tools/locale/tools/unicode2src.pl
    +++ /dev/null
    @@ -1,144 +0,0 @@
    -#!/usr/bin/perl -wC
    -
    -#
    -# $FreeBSD$
    -#
    -
    -use strict;
    -use XML::Parser;
    -use Tie::IxHash;
    -use Data::Dumper;
    -use Getopt::Long;
    -use Digest::SHA qw(sha1_hex);
    -
    -
    -if ($#ARGV < 2) {
    -	print "Usage: $0 --cldr= --unidata= --etc= --input= --output=\n";
    -	exit(1);
    -}
    -
    -my @filter = ();
    -
    -my $CLDRDIR = undef;
    -my $UNIDATADIR = undef;
    -my $ETCDIR = undef;
    -my $TYPE = undef;
    -my $INPUT = undef;
    -my $OUTPUT = undef;
    -
    -my $result = GetOptions (
    -		"cldr=s"	=> \$CLDRDIR,
    -		"unidata=s"	=> \$UNIDATADIR,
    -		"etc=s"		=> \$ETCDIR,
    -		"type=s"	=> \$TYPE,
    -		"input=s"	=> \$INPUT,
    -		"output=s"	=> \$OUTPUT,
    -	    );
    -
    -my %ucd = ();
    -my %utf8map = ();
    -my %utf8aliases = ();
    -get_unidata($UNIDATADIR);
    -get_utf8map("$CLDRDIR/posix/UTF-8.cm");
    -convert($INPUT, $OUTPUT);
    -
    -############################
    -
    -sub get_unidata {
    -	my $directory = shift;
    -
    -	open(FIN, "$directory/UnicodeData.txt")
    -	    or die("Cannot open $directory/UnicodeData.txt");;
    -	my @lines = ;
    -	chomp(@lines);
    -	close(FIN);
    -
    -	foreach my $l (@lines) {
    -		my @a = split(/;/, $l);
    -
    -		$ucd{code2name}{"$a[0]"} = $a[1];	# Unicode name
    -		$ucd{name2code}{"$a[1]"} = $a[0];	# Unicode code
    -	}
    -}
    -
    -sub get_utf8map {
    -	my $file = shift;
    -
    -	open(FIN, $file);
    -	my @lines = ;
    -	close(FIN);
    -	chomp(@lines);
    -
    -	my $prev_k = undef;
    -	my $prev_v = "";
    -	my $incharmap = 0;
    -	foreach my $l (@lines) {
    -		$l =~ s/\r//;
    -		next if ($l =~ /^\#/);
    -		next if ($l eq "");
    -
    -		if ($l eq "CHARMAP") {
    -			$incharmap = 1;
    -			next;
    -		}
    -
    -		next if (!$incharmap);
    -		last if ($l eq "END CHARMAP");
    -
    -		$l =~ /^<([^\s]+)>\s+(.*)/;
    -		my $k = $1;
    -		my $v = $2;
    -		$k =~ s/_/ /g;		# unicode char string
    -		$v =~ s/\\x//g;		# UTF-8 char code
    -		$utf8map{$k} = $v;
    -
    -		$utf8aliases{$k} = $prev_k if ($prev_v eq $v);
    -
    -		$prev_v = $v;
    -		$prev_k = $k;
    -	}
    -}
    -
    -sub decode_cldr {
    -	my $s = shift;
    -
    -	my $v = $utf8map{$s};
    -	$v = $utf8aliases{$s} if (!defined $v);
    -	die "Cannot convert $s" if (!defined $v);
    -
    -	return pack("C", hex($v)) if (length($v) == 2);
    -	return pack("CC", hex(substr($v, 0, 2)), hex(substr($v, 2, 2)))
    -		if (length($v) == 4);
    -	return pack("CCC", hex(substr($v, 0, 2)), hex(substr($v, 2, 2)),
    -	    hex(substr($v, 4, 2))) if (length($v) == 6);
    -	print STDERR "Cannot convert $s\n";
    -	return "length = " . length($v);
    -}
    -
    -sub convert {
    -	my $IN = shift;
    -	my $OUT = shift;
    -
    -	open(FIN, "$IN");
    -	open(FOUT, ">$OUT");
    -
    -#	print Dumper(%utf8map);
    -
    -	my $l;
    -	while (defined ($l = )) {
    -		chomp($l);
    -
    -		if ($l =~ /^#/) {
    -			print FOUT $l, "\n";
    -			next;
    -		}
    -
    -		while ($l =~ /^(.*?)<(.*?)>(.*)$/) {
    -			$l = $1 . decode_cldr($2) . $3;
    -		}
    -		print FOUT $l, "\n";
    -	}
    -
    -	close(FOUT);
    -	close(FIN);
    -}
    diff --git a/tools/tools/locale/tools/utf8-rollup.pl b/tools/tools/locale/tools/utf8-rollup.pl
    index a04e77eaa073..d7bdf213214a 100755
    --- a/tools/tools/locale/tools/utf8-rollup.pl
    +++ b/tools/tools/locale/tools/utf8-rollup.pl
    @@ -1,4 +1,5 @@
     #!/usr/local/bin/perl -wC
    +# $FreeBSD$
     
     use strict;
     #use File::Copy;
    @@ -11,15 +12,15 @@ use Getopt::Long;
     
     
     if ($#ARGV != 1) {
    -	print "Usage: $0 --cldr= --etc=\n";
    +	print "Usage: $0 --unidir= --etc=\n";
     	exit(1);
     }
     
    -my $CLDRDIR = undef;
    +my $UNIDIR = undef;
     my $ETCDIR = undef;
     
     my $result = GetOptions (
    -		"cldr=s"	=> \$CLDRDIR,
    +		"unidir=s"	=> \$UNIDIR,
     		"etc=s"		=> \$ETCDIR,
     	    );
     
    @@ -118,7 +119,7 @@ my $outfilename = "$ETCDIR/common.UTF-8.src";
     my $manual_file = "$ETCDIR/manual-input.UTF-8";
     my $stars = "**********************************************************************\n";
     
    -get_utf8map("$CLDRDIR/posix/UTF-8.cm");
    +get_utf8map("$UNIDIR/posix/UTF-8.cm");
     generate_header ();
     generate_sections ();
     generate_footer ();
    @@ -252,7 +253,7 @@ sub compress_ctype {
     
     	my @lines = initialize_lines ($territory);
     
    -	my $filename = "$CLDRDIR/posix/$territory.UTF-8.src";
    +	my $filename = "$UNIDIR/posix/$territory.UTF-8.src";
     	if (! -f $filename) {
     		print STDERR "Cannot open $filename\n";
     		return;
    diff --git a/tools/tools/locale/tools/whatis.pl b/tools/tools/locale/tools/whatis.pl
    deleted file mode 100755
    index 1167d4a3c293..000000000000
    --- a/tools/tools/locale/tools/whatis.pl
    +++ /dev/null
    @@ -1,29 +0,0 @@
    -#!/bin/sh
    -
    -UNIDATA=$(grep ^unidata etc/unicode.conf | cut -f 2 -d " ")
    -UTF8=$(grep ^cldr etc/unicode.conf | cut -f 2 -d " ")/UTF-8.cm
    -CHARMAPS=etc/charmaps
    -
    -if [ -z "$1" ]; then
    -	echo "Usage: $0 "
    -	exit
    -fi
    -
    -UCS=$*
    -UCS_=$(echo $* | sed -e 's/ /./g')
    -echo UCS: ${UCS}
    -
    -echo UTF-8.cm:
    -grep "${UCS_}" ${UTF8} | sed -e 's/   */	/g'
    -
    -echo UNIDATA:
    -grep "${UCS_}" ${UNIDATA}
    -L=$(grep "${UCS_}" ${UNIDATA})
    -
    -echo UCC:
    -grep "${UCS_}" ${UNIDATA} | awk -F\; '{ print $1 }'
    -
    -
    -echo CHARMAPS:
    -grep ${UCS_} ${CHARMAPS}/* | sed -e "s|${CHARMAPS}/||g"
    -grep ${UCC} ${CHARMAPS}/* | sed -e "s|${CHARMAPS}/||g"
    diff --git a/tools/tools/nanobsd/embedded/common b/tools/tools/nanobsd/embedded/common
    index 72461fff8062..e60a0bb234be 100644
    --- a/tools/tools/nanobsd/embedded/common
    +++ b/tools/tools/nanobsd/embedded/common
    @@ -671,4 +671,4 @@ create_diskimage ( ) (
     # Set the path to the same path we use for buldworld to use latest mkimg
     NANO_TARGET=$(cd ${NANO_SRC}; ${NANO_MAKE} TARGET_ARCH=${NANO_ARCH} -V _TARGET)
     NANO_TMPPATH=$(cd ${NANO_SRC}; ${NANO_MAKE} MK_AUTO_OBJ=no TARGET=${NANO_TARGET} TARGET_ARCH=${NANO_ARCH} -f Makefile.inc1 buildenv -V TMPPATH)
    -export PATH="${NANO_TMPPATH}"
    +export PATH="${NANO_TMPPATH}:${PATH}"
    diff --git a/usr.bin/cmp/cmp.c b/usr.bin/cmp/cmp.c
    index 0915bab63e51..b8d5dba14ec4 100644
    --- a/usr.bin/cmp/cmp.c
    +++ b/usr.bin/cmp/cmp.c
    @@ -163,22 +163,21 @@ main(int argc, char *argv[])
     	}
     
     	cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_MMAP_R);
    -	if (cap_rights_limit(fd1, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(fd1, &rights) < 0)
     		err(ERR_EXIT, "unable to limit rights for %s", file1);
    -	if (cap_rights_limit(fd2, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(fd2, &rights) < 0)
     		err(ERR_EXIT, "unable to limit rights for %s", file2);
     
     	/* Required for fdopen(3). */
     	fcntls = CAP_FCNTL_GETFL;
    -	if (cap_fcntls_limit(fd1, fcntls) < 0 && errno != ENOSYS)
    +	if (caph_fcntls_limit(fd1, fcntls) < 0)
     		err(ERR_EXIT, "unable to limit fcntls for %s", file1);
    -	if (cap_fcntls_limit(fd2, fcntls) < 0 && errno != ENOSYS)
    +	if (caph_fcntls_limit(fd2, fcntls) < 0)
     		err(ERR_EXIT, "unable to limit fcntls for %s", file2);
     
     	if (!special) {
     		cap_rights_init(&rights);
    -		if (cap_rights_limit(STDIN_FILENO, &rights) < 0 &&
    -		    errno != ENOSYS) {
    +		if (caph_rights_limit(STDIN_FILENO, &rights) < 0) {
     			err(ERR_EXIT, "unable to limit stdio");
     		}
     	}
    diff --git a/usr.bin/diff/diffreg.c b/usr.bin/diff/diffreg.c
    index 56e126a58414..c2fa9fb40621 100644
    --- a/usr.bin/diff/diffreg.c
    +++ b/usr.bin/diff/diffreg.c
    @@ -319,11 +319,9 @@ diffreg(char *file1, char *file2, int flags, int capsicum)
     
     	if (capsicum) {
     		cap_rights_init(&rights_ro, CAP_READ, CAP_FSTAT, CAP_SEEK);
    -		if (cap_rights_limit(fileno(f1), &rights_ro) < 0
    -		    && errno != ENOSYS)
    +		if (caph_rights_limit(fileno(f1), &rights_ro) < 0)
     			err(2, "unable to limit rights on: %s", file1);
    -		if (cap_rights_limit(fileno(f2), &rights_ro) < 0 &&
    -		    errno != ENOSYS)
    +		if (caph_rights_limit(fileno(f2), &rights_ro) < 0)
     			err(2, "unable to limit rights on: %s", file2);
     		if (fileno(f1) == STDIN_FILENO || fileno(f2) == STDIN_FILENO) {
     			/* stding has already been limited */
    diff --git a/usr.bin/diff3/diff3.c b/usr.bin/diff3/diff3.c
    index 4b1346f85097..4afe1767bb13 100644
    --- a/usr.bin/diff3/diff3.c
    +++ b/usr.bin/diff3/diff3.c
    @@ -717,19 +717,19 @@ main(int argc, char **argv)
     	fp[0] = fopen(file1, "r");
     	if (fp[0] == NULL)
     		err(2, "Can't open %s", file1);
    -	if (cap_rights_limit(fileno(fp[0]), &rights_ro) < 0)
    +	if (caph_rights_limit(fileno(fp[0]), &rights_ro) < 0)
     		err(2, "unable to limit rights on: %s", file1);
     
     	fp[1] = fopen(file2, "r");
     	if (fp[1] == NULL)
     		err(2, "Can't open %s", file2);
    -	if (cap_rights_limit(fileno(fp[1]), &rights_ro) < 0)
    +	if (caph_rights_limit(fileno(fp[1]), &rights_ro) < 0)
     		err(2, "unable to limit rights on: %s", file2);
     
     	fp[2] = fopen(file3, "r");
     	if (fp[2] == NULL)
     		err(2, "Can't open %s", file3);
    -	if (cap_rights_limit(fileno(fp[2]), &rights_ro) < 0)
    +	if (caph_rights_limit(fileno(fp[2]), &rights_ro) < 0)
     		err(2, "unable to limit rights on: %s", file3);
     
     	if (pipe(fd13))
    diff --git a/usr.bin/elfdump/elfdump.1 b/usr.bin/elfdump/elfdump.1
    index a549d5391934..f0bb7f2fc175 100644
    --- a/usr.bin/elfdump/elfdump.1
    +++ b/usr.bin/elfdump/elfdump.1
    @@ -24,7 +24,7 @@
     .\"
     .\" $FreeBSD$
     .\"
    -.Dd January 15, 2003
    +.Dd November 5, 2018
     .Dt ELFDUMP 1
     .Os
     .Sh NAME
    @@ -34,7 +34,7 @@
     files
     .Sh SYNOPSIS
     .Nm
    -.Fl a | cdeGhinprs
    +.Fl a | E | cdeGhinprs
     .Op Fl w Ar file
     .Ar file
     .Sh DESCRIPTION
    @@ -55,6 +55,11 @@ Dump section headers.
     Dump dynamic symbols.
     .It Fl e
     Dump ELF header.
    +.It Fl E
    +Return success if
    +.Ar file
    +is an ELF file and failure if it is not.
    +This option is exclusive with other options.
     .It Fl G
     Dump the GOT.
     .It Fl h
    diff --git a/usr.bin/elfdump/elfdump.c b/usr.bin/elfdump/elfdump.c
    index ed2a8e230ac7..aadf1e84088d 100644
    --- a/usr.bin/elfdump/elfdump.c
    +++ b/usr.bin/elfdump/elfdump.c
    @@ -60,6 +60,7 @@ __FBSDID("$FreeBSD$");
     #define	ED_SHDR		(1<<8)
     #define	ED_SYMTAB	(1<<9)
     #define	ED_ALL		((1<<10)-1)
    +#define	ED_IS_ELF	(1<<10)	/* Exclusive with other flags */
     
     #define	elf_get_addr	elf_get_quad
     #define	elf_get_off	elf_get_quad
    @@ -518,7 +519,7 @@ main(int ac, char **av)
     
     	out = stdout;
     	flags = 0;
    -	while ((ch = getopt(ac, av, "acdeiGhnprsw:")) != -1)
    +	while ((ch = getopt(ac, av, "acdEeiGhnprsw:")) != -1)
     		switch (ch) {
     		case 'a':
     			flags = ED_ALL;
    @@ -529,6 +530,9 @@ main(int ac, char **av)
     		case 'd':
     			flags |= ED_DYN;
     			break;
    +		case 'E':
    +			flags = ED_IS_ELF;
    +			break;
     		case 'e':
     			flags |= ED_EHDR;
     			break;
    @@ -557,7 +561,7 @@ main(int ac, char **av)
     			if ((out = fopen(optarg, "w")) == NULL)
     				err(1, "%s", optarg);
     			cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
    -			if (cap_rights_limit(fileno(out), &rights) < 0 && errno != ENOSYS)
    +			if (caph_rights_limit(fileno(out), &rights) < 0)
     				err(1, "unable to limit rights for %s", optarg);
     			break;
     		case '?':
    @@ -566,16 +570,17 @@ main(int ac, char **av)
     		}
     	ac -= optind;
     	av += optind;
    -	if (ac == 0 || flags == 0)
    +	if (ac == 0 || flags == 0 || ((flags & ED_IS_ELF) &&
    +	    (ac != 1 || (flags & ~ED_IS_ELF) || out != stdout)))
     		usage();
     	if ((fd = open(*av, O_RDONLY)) < 0 ||
     	    fstat(fd, &sb) < 0)
     		err(1, "%s", *av);
     	cap_rights_init(&rights, CAP_MMAP_R);
    -	if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(fd, &rights) < 0)
     		err(1, "unable to limit rights for %s", *av);
     	cap_rights_init(&rights);
    -	if ((cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS) ||
    +	if (caph_rights_limit(STDIN_FILENO, &rights) < 0 ||
     	    caph_limit_stdout() < 0 || caph_limit_stderr() < 0) {
                     err(1, "unable to limit rights for stdio");
     	}
    @@ -584,8 +589,12 @@ main(int ac, char **av)
     	e = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
     	if (e == MAP_FAILED)
     		err(1, NULL);
    -	if (!IS_ELF(*(Elf32_Ehdr *)e))
    +	if (!IS_ELF(*(Elf32_Ehdr *)e)) {
    +		if (flags & ED_IS_ELF)
    +			exit(1);
     		errx(1, "not an elf file");
    +	} else if (flags & ED_IS_ELF)
    +		exit (0);
     	phoff = elf_get_off(e, e, E_PHOFF);
     	shoff = elf_get_off(e, e, E_SHOFF);
     	phentsize = elf_get_quarter(e, e, E_PHENTSIZE);
    @@ -1254,6 +1263,7 @@ elf_get_quad(Elf32_Ehdr *e, void *base, elf_member_t member)
     static void
     usage(void)
     {
    -	fprintf(stderr, "usage: elfdump -a | -cdeGhinprs [-w file] file\n");
    +	fprintf(stderr,
    +	    "usage: elfdump -a | -E | -cdeGhinprs [-w file] file\n");
     	exit(1);
     }
    diff --git a/usr.bin/indent/indent.c b/usr.bin/indent/indent.c
    index 9b45daf63b0c..1dcce85e232b 100644
    --- a/usr.bin/indent/indent.c
    +++ b/usr.bin/indent/indent.c
    @@ -245,10 +245,10 @@ main(int argc, char **argv)
     
         /* Restrict input/output descriptors and enter Capsicum sandbox. */
         cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
    -    if (cap_rights_limit(fileno(output), &rights) < 0 && errno != ENOSYS)
    +    if (caph_rights_limit(fileno(output), &rights) < 0)
     	err(EXIT_FAILURE, "unable to limit rights for %s", out_name);
         cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
    -    if (cap_rights_limit(fileno(input), &rights) < 0 && errno != ENOSYS)
    +    if (caph_rights_limit(fileno(input), &rights) < 0)
     	err(EXIT_FAILURE, "unable to limit rights for %s", in_name);
         if (caph_enter() < 0)
     	err(EXIT_FAILURE, "unable to enter capability mode");
    diff --git a/usr.bin/jot/jot.c b/usr.bin/jot/jot.c
    index c7f7a31278c1..96d66de11173 100644
    --- a/usr.bin/jot/jot.c
    +++ b/usr.bin/jot/jot.c
    @@ -114,7 +114,7 @@ main(int argc, char **argv)
     	if (caph_limit_stdio() < 0)
     		err(1, "unable to limit rights for stdio");
     	cap_rights_init(&rights);
    -	if (cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(STDIN_FILENO, &rights) < 0)
     		err(1, "unable to limit rights for stdin");
     
     	/*
    diff --git a/usr.bin/ktrdump/ktrdump.c b/usr.bin/ktrdump/ktrdump.c
    index 0f39da01d640..750f138f5485 100644
    --- a/usr.bin/ktrdump/ktrdump.c
    +++ b/usr.bin/ktrdump/ktrdump.c
    @@ -132,8 +132,7 @@ main(int ac, char **av)
     			if ((in = open(optarg, O_RDONLY)) == -1)
     				err(1, "%s", optarg);
     			cap_rights_init(&rights, CAP_FSTAT, CAP_MMAP_R);
    -			if (cap_rights_limit(in, &rights) < 0 &&
    -			    errno != ENOSYS)
    +			if (caph_rights_limit(in, &rights) < 0)
     				err(1, "unable to limit rights for %s",
     				    optarg);
     			break;
    diff --git a/usr.bin/lam/lam.c b/usr.bin/lam/lam.c
    index 4f42921ad388..693e9903cd36 100644
    --- a/usr.bin/lam/lam.c
    +++ b/usr.bin/lam/lam.c
    @@ -136,8 +136,7 @@ getargs(char *av[])
     			else if ((ip->fp = fopen(p, "r")) == NULL) {
     				err(1, "%s", p);
     			}
    -			if (cap_rights_limit(fileno(ip->fp), &rights_ro) < 0
    -			    && errno != ENOSYS)
    +			if (caph_rights_limit(fileno(ip->fp), &rights_ro) < 0)
     				err(1, "unable to limit rights on: %s", p);
     			ip->pad = P;
     			if (!ip->sepstring)
    diff --git a/usr.bin/man/man.sh b/usr.bin/man/man.sh
    index a71ac3578d30..12a370cd8efb 100755
    --- a/usr.bin/man/man.sh
    +++ b/usr.bin/man/man.sh
    @@ -662,6 +662,7 @@ man_setup_width() {
     # Setup necessary locale variables.
     man_setup_locale() {
     	local lang_cc
    +	local locstr
     
     	locpaths='.'
     	man_charset='US-ASCII'
    @@ -670,18 +671,25 @@ man_setup_locale() {
     	if [ -n "$oflag" ]; then
     		decho 'Using non-localized manpages'
     	else
    -		# Use the locale tool to give us the proper LC_CTYPE
    +		# Use the locale tool to give us proper locale information
     		eval $( $LOCALE )
     
    -		case "$LC_CTYPE" in
    +		if [ -n "$LANG" ]; then
    +			locstr=$LANG
    +		else
    +			locstr=$LC_CTYPE
    +		fi
    +
    +		case "$locstr" in
     		C)		;;
    +		C.UTF-8)	;;
     		POSIX)		;;
     		[a-z][a-z]_[A-Z][A-Z]\.*)
    -				lang_cc="${LC_CTYPE%.*}"
    -				man_lang="${LC_CTYPE%_*}"
    +				lang_cc="${locstr%.*}"
    +				man_lang="${locstr%_*}"
     				man_country="${lang_cc#*_}"
    -				man_charset="${LC_CTYPE#*.}"
    -				locpaths="$LC_CTYPE"
    +				man_charset="${locstr#*.}"
    +				locpaths="$locstr"
     				locpaths="$locpaths:$man_lang.$man_charset"
     				if [ "$man_lang" != "en" ]; then
     					locpaths="$locpaths:en.$man_charset"
    diff --git a/usr.bin/rwho/rwho.c b/usr.bin/rwho/rwho.c
    index 6326b2ce251a..8e6384161f28 100644
    --- a/usr.bin/rwho/rwho.c
    +++ b/usr.bin/rwho/rwho.c
    @@ -129,7 +129,7 @@ main(int argc, char *argv[])
     	dfd = dirfd(dirp);
     	mp = myutmp;
     	cap_rights_init(&rights, CAP_READ, CAP_LOOKUP);
    -	if (cap_rights_limit(dfd, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(dfd, &rights) < 0)
     		err(1, "cap_rights_limit failed: %s", _PATH_RWHODIR);
     	/*
     	 * Cache files required for time(3) and localtime(3) before entering
    @@ -147,7 +147,7 @@ main(int argc, char *argv[])
     		f = openat(dfd, dp->d_name, O_RDONLY);
     		if (f < 0)
     			continue;
    -		if (cap_rights_limit(f, &rights) < 0 && errno != ENOSYS)
    +		if (caph_rights_limit(f, &rights) < 0)
     			err(1, "cap_rights_limit failed: %s", dp->d_name);
     		cc = read(f, (char *)&wd, sizeof(struct whod));
     		if (cc < WHDRSIZE) {
    diff --git a/usr.bin/tee/tee.c b/usr.bin/tee/tee.c
    index b6d438afd96d..b55aa84d2f63 100644
    --- a/usr.bin/tee/tee.c
    +++ b/usr.bin/tee/tee.c
    @@ -147,7 +147,7 @@ add(int fd, const char *name)
     			err(EXIT_FAILURE, "unable to limit stdout");
     	} else {
     		cap_rights_init(&rights, CAP_WRITE, CAP_FSTAT);
    -		if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS)
    +		if (caph_rights_limit(fd, &rights) < 0)
     			err(EXIT_FAILURE, "unable to limit rights");
     	}
     
    diff --git a/usr.bin/uniq/uniq.c b/usr.bin/uniq/uniq.c
    index 862b7525e82a..dce2bbd82ab8 100644
    --- a/usr.bin/uniq/uniq.c
    +++ b/usr.bin/uniq/uniq.c
    @@ -143,14 +143,14 @@ main (int argc, char *argv[])
     	if (argc > 0 && strcmp(argv[0], "-") != 0)
     		ifp = file(ifn = argv[0], "r");
     	cap_rights_init(&rights, CAP_FSTAT, CAP_READ);
    -	if (cap_rights_limit(fileno(ifp), &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(fileno(ifp), &rights) < 0)
     		err(1, "unable to limit rights for %s", ifn);
     	cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE);
     	if (argc > 1)
     		ofp = file(argv[1], "w");
     	else
     		cap_rights_set(&rights, CAP_IOCTL);
    -	if (cap_rights_limit(fileno(ofp), &rights) < 0 && errno != ENOSYS) {
    +	if (caph_rights_limit(fileno(ofp), &rights) < 0) {
     		err(1, "unable to limit rights for %s",
     		    argc > 1 ? argv[1] : "stdout");
     	}
    @@ -159,8 +159,7 @@ main (int argc, char *argv[])
     
     		cmd = TIOCGETA; /* required by isatty(3) in printf(3) */
     
    -		if (cap_ioctls_limit(fileno(ofp), &cmd, 1) < 0 &&
    -		    errno != ENOSYS) {
    +		if (caph_ioctls_limit(fileno(ofp), &cmd, 1) < 0) {
     			err(1, "unable to limit ioctls for %s",
     			    argc > 1 ? argv[1] : "stdout");
     		}
    diff --git a/usr.bin/units/units.c b/usr.bin/units/units.c
    index e0807c56077d..847e617588a6 100644
    --- a/usr.bin/units/units.c
    +++ b/usr.bin/units/units.c
    @@ -156,8 +156,7 @@ readunits(const char *userfile)
     		}
     	}
     	cap_rights_init(&unitfilerights, CAP_READ, CAP_FSTAT);
    -	if (cap_rights_limit(fileno(unitfile), &unitfilerights) < 0
    -		&& errno != ENOSYS)
    +	if (caph_rights_limit(fileno(unitfile), &unitfilerights) < 0)
     		err(1, "cap_rights_limit() failed");
     	while (!feof(unitfile)) {
     		if (!fgets(line, sizeof(line), unitfile))
    diff --git a/usr.bin/write/write.c b/usr.bin/write/write.c
    index 3f0f1a1aa9cd..2febe3b42302 100644
    --- a/usr.bin/write/write.c
    +++ b/usr.bin/write/write.c
    @@ -97,7 +97,7 @@ main(int argc, char **argv)
     		err(1, "open(/dev)");
     	cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL, CAP_LOOKUP,
     	    CAP_PWRITE);
    -	if (cap_rights_limit(devfd, &rights) < 0 && errno != ENOSYS)
    +	if (caph_rights_limit(devfd, &rights) < 0)
     		err(1, "can't limit devfd rights");
     
     	/*
    @@ -106,15 +106,15 @@ main(int argc, char **argv)
     	 */
     	cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL, CAP_READ,
     	    CAP_WRITE);
    -	if ((cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS) ||
    -	    (cap_rights_limit(STDOUT_FILENO, &rights) < 0 && errno != ENOSYS) ||
    -	    (cap_rights_limit(STDERR_FILENO, &rights) < 0 && errno != ENOSYS) ||
    -	    (cap_ioctls_limit(STDIN_FILENO, cmds, nitems(cmds)) < 0 && errno != ENOSYS) ||
    -	    (cap_ioctls_limit(STDOUT_FILENO, cmds, nitems(cmds)) < 0 && errno != ENOSYS) ||
    -	    (cap_ioctls_limit(STDERR_FILENO, cmds, nitems(cmds)) < 0 && errno != ENOSYS) ||
    -	    (cap_fcntls_limit(STDIN_FILENO, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) ||
    -	    (cap_fcntls_limit(STDOUT_FILENO, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) ||
    -	    (cap_fcntls_limit(STDERR_FILENO, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS))
    +	if (caph_rights_limit(STDIN_FILENO, &rights) < 0 ||
    +	    caph_rights_limit(STDOUT_FILENO, &rights) < 0 ||
    +	    caph_rights_limit(STDERR_FILENO, &rights) < 0 ||
    +	    caph_ioctls_limit(STDIN_FILENO, cmds, nitems(cmds)) < 0 ||
    +	    caph_ioctls_limit(STDOUT_FILENO, cmds, nitems(cmds)) < 0 ||
    +	    caph_ioctls_limit(STDERR_FILENO, cmds, nitems(cmds)) < 0 ||
    +	    caph_fcntls_limit(STDIN_FILENO, CAP_FCNTL_GETFL) < 0 ||
    +	    caph_fcntls_limit(STDOUT_FILENO, CAP_FCNTL_GETFL) < 0 ||
    +	    caph_fcntls_limit(STDERR_FILENO, CAP_FCNTL_GETFL) < 0)
     		err(1, "can't limit stdio rights");
     
     	caph_cache_catpages();
    diff --git a/usr.sbin/Makefile b/usr.sbin/Makefile
    index 25e3265b6992..3c371d404fcf 100644
    --- a/usr.sbin/Makefile
    +++ b/usr.sbin/Makefile
    @@ -59,9 +59,6 @@ SUBDIR=	adduser \
     	nologin \
     	pciconf \
     	periodic \
    -	pmcannotate \
    -	pmccontrol \
    -	pmcstat \
     	pnfsdscopymr \
     	pnfsdsfile \
     	pnfsdskill \
    @@ -191,7 +188,7 @@ SUBDIR.${MK_PKGBOOTSTRAP}+=	pkg
     .if ${COMPILER_FEATURES:Mc++11}
     SUBDIR.${MK_PMC}+=	pmc
     .endif
    -SUBDIR.${MK_PMC}+=	pmcstudy
    +SUBDIR.${MK_PMC}+=	pmcannotate pmccontrol pmcstat pmcstudy
     SUBDIR.${MK_PORTSNAP}+=	portsnap
     SUBDIR.${MK_PPP}+=	ppp
     SUBDIR.${MK_QUOTAS}+=	edquota
    diff --git a/usr.sbin/bhyve/pci_fbuf.c b/usr.sbin/bhyve/pci_fbuf.c
    index 8ed340580b5d..2669ea14d3f4 100644
    --- a/usr.sbin/bhyve/pci_fbuf.c
    +++ b/usr.sbin/bhyve/pci_fbuf.c
    @@ -319,7 +319,6 @@ pci_fbuf_parse_opts(struct pci_fbuf_softc *sc, char *opts)
     	}
     
     done:
    -	free(uopts);
     	return (ret);
     }
     
    diff --git a/usr.sbin/bhyve/pci_nvme.c b/usr.sbin/bhyve/pci_nvme.c
    index 83051f1aa186..9000655d5d07 100644
    --- a/usr.sbin/bhyve/pci_nvme.c
    +++ b/usr.sbin/bhyve/pci_nvme.c
    @@ -251,11 +251,13 @@ static void pci_nvme_io_partial(struct blockif_req *br, int err);
     	 (NVME_STATUS_SC_MASK << NVME_STATUS_SC_SHIFT))
     
     static __inline void
    -cpywithpad(char *dst, int dst_size, const char *src, char pad)
    +cpywithpad(char *dst, size_t dst_size, const char *src, char pad)
     {
    -	int len = strnlen(src, dst_size);
    +	size_t len;
    +
    +	len = strnlen(src, dst_size);
    +	memset(dst, pad, dst_size);
     	memcpy(dst, src, len);
    -	memset(dst + len, pad, dst_size - len);
     }
     
     static __inline void
    diff --git a/usr.sbin/rwhod/rwhod.c b/usr.sbin/rwhod/rwhod.c
    index 7bb15f7d6f07..23c307e33829 100644
    --- a/usr.sbin/rwhod/rwhod.c
    +++ b/usr.sbin/rwhod/rwhod.c
    @@ -369,7 +369,7 @@ receiver_process(void)
     	}
     	cap_rights_init(&rights, CAP_CREATE, CAP_FSTAT, CAP_FTRUNCATE,
     	    CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
    -	if (cap_rights_limit(dirfd, &rights) < 0 && errno != ENOSYS) {
    +	if (caph_rights_limit(dirfd, &rights) < 0) {
     		syslog(LOG_WARNING, "cap_rights_limit: %m");
     		exit(1);
     	}
    @@ -415,7 +415,7 @@ receiver_process(void)
     			continue;
     		}
     		cap_rights_init(&rights, CAP_FSTAT, CAP_FTRUNCATE, CAP_WRITE);
    -		if (cap_rights_limit(whod, &rights) < 0 && errno != ENOSYS) {
    +		if (caph_rights_limit(whod, &rights) < 0) {
     			syslog(LOG_WARNING, "cap_rights_limit: %m");
     			exit(1);
     		}