ADDED .editorconfig
Index: .editorconfig
==================================================================
--- .editorconfig
+++ .editorconfig
@@ -0,0 +1,14 @@
+# EditorConfig (https://editorconfig.com) Configuration for Fossil
+#
+# Following https://fossil-scm.org/fossil/doc/trunk/www/style.wiki
+#
+
+# Defaults for all files
+[*]
+end_of_line = lf
+insert_final_newline = true
+indent_style = space
+indent_size = 2
+
+[{Makefile,Makefile.*,*.mk}]
+indent_style = tab
ADDED .fossil-settings/binary-glob
Index: .fossil-settings/binary-glob
==================================================================
--- .fossil-settings/binary-glob
+++ .fossil-settings/binary-glob
@@ -0,0 +1,13 @@
+*.gif
+*.ico
+*.jpg
+*.odp
+*.dia
+*.pdf
+*.png
+*.wav
+compat/zlib/contrib/blast/test.pk
+compat/zlib/contrib/dotzlib/DotZLib.chm
+compat/zlib/contrib/puff/zeros.raw
+compat/zlib/zlib.3.pdf
+extsrc/pikchr.wasm
ADDED .fossil-settings/clean-glob
Index: .fossil-settings/clean-glob
==================================================================
--- .fossil-settings/clean-glob
+++ .fossil-settings/clean-glob
@@ -0,0 +1,20 @@
+*.a
+*.lib
+*.manifest
+*.o
+*.obj
+*.pdb
+*.res
+Makefile
+autosetup/jimsh0
+autosetup/jimsh0.exe
+bld/*
+msvcbld/*
+wbld/*
+win/*.c
+win/*.h
+win/*.exe
+win/headers
+win/linkopts
+autoconfig.h
+config.log
ADDED .fossil-settings/crlf-glob
Index: .fossil-settings/crlf-glob
==================================================================
--- .fossil-settings/crlf-glob
+++ .fossil-settings/crlf-glob
@@ -0,0 +1,5 @@
+compat/zlib/*
+setup/fossil.iss
+test/th1-docs-input.txt
+test/th1-hooks-input.txt
+win/buildmsvc.bat
ADDED .fossil-settings/encoding-glob
Index: .fossil-settings/encoding-glob
==================================================================
--- .fossil-settings/encoding-glob
+++ .fossil-settings/encoding-glob
@@ -0,0 +1,4 @@
+compat/zlib/contrib/dotzlib/DotZLib/*.cs
+test/utf16be.txt
+test/utf16le.txt
+win/fossil.rc
ADDED .fossil-settings/ignore-glob
Index: .fossil-settings/ignore-glob
==================================================================
--- .fossil-settings/ignore-glob
+++ .fossil-settings/ignore-glob
@@ -0,0 +1,9 @@
+compat/openssl*
+compat/tcl*
+compat/zlib/contrib/ada/*
+compat/zlib/doc/*
+fossil
+fossil.exe
+win/fossil.exe
+*shell-see.*
+*sqlite3-see.*
ADDED .project
Index: .project
==================================================================
--- .project
+++ .project
@@ -0,0 +1,11 @@
+
+
+ fossil
+
+
+
+
+
+
+
+
ADDED .settings/org.eclipse.core.resources.prefs
Index: .settings/org.eclipse.core.resources.prefs
==================================================================
--- .settings/org.eclipse.core.resources.prefs
+++ .settings/org.eclipse.core.resources.prefs
@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+encoding/=UTF-8
ADDED .settings/org.eclipse.core.runtime.prefs
Index: .settings/org.eclipse.core.runtime.prefs
==================================================================
--- .settings/org.eclipse.core.runtime.prefs
+++ .settings/org.eclipse.core.runtime.prefs
@@ -0,0 +1,2 @@
+eclipse.preferences.version=1
+line.separator=\n
Index: BUILD.txt
==================================================================
--- BUILD.txt
+++ BUILD.txt
@@ -1,56 +1,78 @@
-All of the source code for fossil is contained in the src/ subdirectory.
-But there is a lot of generated code, so you will probably want to
-use the Makefile. To do a complete build, just type:
-
- make
-
-That should work out-of-the-box on Macs and Linux systems. If you are
-building on a Windows box, install MinGW as well as MinGW's make (or
-MSYS). You can then type:
-
- make -f Makefile.w32
+To do a complete build, just type:
+
+ ./configure; make
+
+The ./configure script builds Makefile from Makefile.in based on
+your system and any options you select (run "./configure --help"
+for a listing of the available options.)
+
+If you wish to use the original Makefile with no configuration, you can
+instead use:
+
+ make -f Makefile.classic
+
+On a windows box, use one of the Makefiles in the win/ subdirectory,
+according to your compiler and environment. If you have MinGW or
+MinGW-w64 installed on your system (Msys or Cygwin, or as
+cross-compile environment on Linux or Darwin), then consider:
+
+ make -f win/Makefile.mingw
+
+If you have VC++ installed on your system, then consider:
+
+ cd win; nmake /f Makefile.msc
If you have trouble, or you want to do something fancy, just look at
-top level makefile. There are 6 configuration options that are all well
-commented. Instead of editing the Makefile, consider copying the Makefile
-to an alternative name such as "GNUMakefile", "BSDMakefile", or "makefile"
-and editing the copy.
+Makefile.classic. There are 6 configuration options that are all well
+commented. Instead of editing the Makefile.classic, consider copying
+Makefile.classic to an alternative name such as "GNUMakefile",
+"BSDMakefile", or "makefile" and editing the copy.
+
-Out of source builds?
---------------------------------------------------------------------------
+BUILDING OUTSIDE THE SOURCE TREE
An out of source build is pretty easy:
- 1. Make a new directory to do the builds in.
- 2. Copy "Makefile" from the source into the build directory and
- modify the SRCDIR macro along the lines of:
-
- SRCDIR=../src
-
- 3. type: "make"
-
-This will now keep all generates files seperate from the maintained
+ 1. Make and change to a new directory to do the builds in.
+ 2. Run the "configure" script from this directory.
+ 3. Type: "make"
+
+For example:
+
+ mkdir build
+ cd build
+ ../configure
+ make
+
+This will now keep all generates files separate from the maintained
source code.
--------------------------------------------------------------------------
Here are some notes on what is happening behind the scenes:
+
+* The configure script (if used) examines the options given
+ and runs various tests with the C compiler to create Makefile
+ from the Makefile.in template as well as autoconfig.h
* The Makefile just sets up a few macros and then invokes the
real makefile in src/main.mk. The src/main.mk makefile is
- automatically generated by a TCL script found at src/makemake.tcl.
- Do not edit src/main.mk directly. Update src/makemake.tcl and
+ automatically generated by a TCL script found at tools/makemake.tcl.
+ Do not edit src/main.mk directly. Update tools/makemake.tcl and
then rerun it.
* The *.h header files are automatically generated using a program
called "makeheaders". Source code to the makeheaders program is
- found in src/makeheaders.c. Documentation is found in
- src/makeheaders.html.
+ found in tools/makeheaders.c. Documentation is found in
+ tools/makeheaders.html.
* Most *.c source files are preprocessed using a program called
- "translate". The sources to translate are found in src/translate.c.
- A header comment in src/translate.c explains in detail what it does.
+ "translate". The sources to translate are found in tools/translate.c.
+ A header comment in tools/translate.c explains in detail what it does.
-* The src/mkindex.c program generates some C code that implements
+* The tools/mkindex.c program generates some C code that implements
static lookup tables. See the header comment in the source code
for details on what it does.
+
+Additional information on the build process is available from
+http://fossil-scm.org/home/doc/trunk/www/makefile.wiki
Index: COPYRIGHT-BSD2.txt
==================================================================
--- COPYRIGHT-BSD2.txt
+++ COPYRIGHT-BSD2.txt
@@ -1,31 +1,31 @@
Copyright 2007 D. Richard Hipp. All rights reserved.
-Redistribution and use in source and binary forms, with or
-without modification, are permitted provided that the
+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
+ 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 AUTHORS ``AS IS'' AND ANY EXPRESS
-OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS OR CONTRIBUTORS BE
+ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS 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
+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,
+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 views and conclusions contained in the software and documentation
-are those of the authors and contributors and should not be interpreted
+The views and conclusions contained in the software and documentation
+are those of the authors and contributors and should not be interpreted
as representing official policies, either expressed or implied, of anybody
else.
ADDED Dockerfile
Index: Dockerfile
==================================================================
--- Dockerfile
+++ Dockerfile
@@ -0,0 +1,90 @@
+# syntax=docker/dockerfile:1.3
+# See www/containers.md for documentation on how to use this file.
+
+## ---------------------------------------------------------------------
+## STAGE 1: Build static Fossil binary
+## ---------------------------------------------------------------------
+
+### We aren't pinning to a more stable version of Alpine because we want
+### to build with the latest tools and libraries available in case they
+### fixed something that matters to us since the last build. Everything
+### below depends on this layer, and so, alas, we toss this container's
+### cache on Alpine's release schedule, roughly once a month.
+FROM alpine:latest AS bld
+WORKDIR /fsl
+
+### Bake the basic Alpine Linux into a base layer so it only changes
+### when the upstream image is updated or we change the package set.
+RUN set -x \
+ && apk update \
+ && apk upgrade --no-cache \
+ && apk add --no-cache \
+ gcc make \
+ linux-headers musl-dev \
+ openssl-dev openssl-libs-static \
+ zlib-dev zlib-static
+
+### Build Fossil as a separate layer so we don't have to rebuild the
+### Alpine environment for each iteration of Fossil's dev cycle.
+###
+### We must cope with a bizarre ADD misfeature here: it unpacks tarballs
+### automatically when you give it a local file name but not if you give
+### it a /tarball URL! It matters because we default to a URL in case
+### you're building outside a Fossil checkout, but when building via the
+### container-image target, we avoid a costly hit on fossil-scm.org
+### by leveraging its DVCS nature via the "tarball" command and passing
+### the resulting file's name in.
+ARG FSLCFG=""
+ARG FSLVER="trunk"
+ARG FSLURL="https://fossil-scm.org/home/tarball/src?r=${FSLVER}"
+ENV FSLSTB=/fsl/src.tar.gz
+ADD $FSLURL $FSLSTB
+RUN set -x \
+ && if [ -d $FSLSTB ] ; \
+ then mv $FSLSTB/src . ; \
+ else tar -xf src.tar.gz ; fi \
+ && src/configure --static CFLAGS='-Os -s' $FSLCFG && make -j16
+
+
+## ---------------------------------------------------------------------
+## STAGE 2: Pare that back to the bare essentials.
+## ---------------------------------------------------------------------
+
+FROM busybox AS os
+ARG UID=499
+
+### Set up that base OS for our specific use without tying it to
+### anything likely to change often. So long as the user leaves
+### UID alone, this layer will be durable.
+RUN set -x \
+ && mkdir e log museum \
+ && echo "root:x:0:0:Admin:/:/false" > /e/passwd \
+ && echo "root:x:0:root" > /e/group \
+ && echo "fossil:x:${UID}:${UID}:User:/museum:/false" >> /e/passwd \
+ && echo "fossil:x:${UID}:fossil" >> /e/group
+
+
+## ---------------------------------------------------------------------
+## STAGE 3: Drop BusyBox, too, now that we're done with its /bin/sh &c
+## ---------------------------------------------------------------------
+
+FROM scratch AS run
+COPY --from=bld --chmod=755 /fsl/fossil /bin/
+COPY --from=os --chmod=600 /e/* /etc/
+COPY --from=os --chmod=1777 /tmp /tmp/
+COPY --from=os --chown=fossil:fossil /log /log/
+COPY --from=os --chown=fossil:fossil /museum /museum/
+
+
+## ---------------------------------------------------------------------
+## RUN!
+## ---------------------------------------------------------------------
+
+ENV PATH "/bin"
+EXPOSE 8080/tcp
+USER fossil
+ENTRYPOINT [ "fossil", "server", "museum/repo.fossil" ]
+CMD [ \
+ "--create", \
+ "--jsmode", "bundled", \
+ "--user", "admin" ]
DELETED Makefile
Index: Makefile
==================================================================
--- Makefile
+++ Makefile
@@ -1,56 +0,0 @@
-#!/usr/bin/make
-#
-#### The toplevel directory of the source tree. Fossil can be built
-# in a directory that is separate from the source tree. Just change
-# the following to point from the build directory to the src/ folder.
-#
-SRCDIR = ./src
-
-#### The directory into which object code files should be written.
-#
-#
-OBJDIR = ./obj
-
-#### C Compiler and options for use in building executables that
-# will run on the platform that is doing the build. This is used
-# to compile code-generator programs as part of the build process.
-# See TCC below for the C compiler for building the finished binary.
-#
-BCC = gcc -g -O2
-
-#### The suffix to add to executable files. ".exe" for windows.
-# Nothing for unix.
-#
-E =
-
-#### C Compile and options for use in building executables that
-# will run on the target platform. This is usually the same
-# as BCC, unless you are cross-compiling. This C compiler builds
-# the finished binary for fossil. The BCC compiler above is used
-# for building intermediate code-generator tools.
-#
-#TCC = gcc -O6
-#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage
-TCC = gcc -g -Os -Wall
-
-#### Extra arguments for linking the finished binary. Fossil needs
-# to link against the Z-Lib compression library. There are no
-# other dependencies. We sometimes add the -static option here
-# so that we can build a static executable that will run in a
-# chroot jail.
-#
-LIB = -lz $(LDFLAGS)
-# If you're on OpenSolaris:
-# LIB += lsocket
-# Solaris 10 needs:
-# LIB += -lsocket -lnsl
-# My assumption is that the Sol10 flags will work for Sol8/9 and possibly 11.
-#
-
-#### Tcl shell for use in running the fossil testsuite.
-#
-TCLSH = tclsh
-
-# You should not need to change anything below this line
-###############################################################################
-include $(SRCDIR)/main.mk
ADDED Makefile.classic
Index: Makefile.classic
==================================================================
--- Makefile.classic
+++ Makefile.classic
@@ -0,0 +1,111 @@
+#!/usr/bin/make
+#
+# This is the top-level makefile for Fossil when the build is occurring
+# on a unix platform. This works out-of-the-box on most unix platforms.
+# But you are free to vary some of the definitions if desired.
+#
+#### The toplevel directory of the source tree. Fossil can be built
+# in a directory that is separate from the source tree. Just change
+# the following to point from the build directory to the src/ folder.
+#
+SRCDIR = ./src
+#### Upstream source files included directly in this repository.
+#
+SRCDIR_extsrc = ./extsrc
+#### In-tree tools such as code generators and translators:
+#
+SRCDIR_tools = ./tools
+
+#### The directory into which object code files should be written.
+#
+#
+OBJDIR = ./bld
+
+#### C Compiler and options for use in building executables that
+# will run on the platform that is doing the build. This is used
+# to compile code-generator programs as part of the build process.
+# See TCC below for the C compiler for building the finished binary.
+#
+BCC = gcc
+BCCFLAGS = $(CFLAGS)
+
+#### The suffix to add to final executable file. When cross-compiling
+# to windows, make this ".exe". Otherwise leave it blank.
+#
+E =
+
+#### C Compile and options for use in building executables that
+# will run on the target platform. This is usually the same
+# as BCC, unless you are cross-compiling. This C compiler builds
+# the finished binary for fossil. The BCC compiler above is used
+# for building intermediate code-generator tools.
+#
+#TCC = gcc -O6
+#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage
+TCC = gcc -g -Os -Wall
+
+# To add support for HTTPS
+TCC += -DFOSSIL_ENABLE_SSL
+
+#### We sometimes add the -static option here so that we can build a
+# static executable that will run in a chroot jail.
+#LIB = -static
+TCC += -DFOSSIL_DYNAMIC_BUILD=1
+
+TCCFLAGS = $(CFLAGS)
+
+# We don't attempt to use libedit or libreadline in this simplified
+# build system (contrast auto.def and Makefile.in) so use the included
+# copy of linenoise. MinGW can't make use of this, but linenoise is
+# ifdef'd out elsewhere for that platform. Note that this is a make
+# flag handled in src/main.mk, not a C preprocessor flag.
+USE_LINENOISE := 1
+
+#### Extra arguments for linking the finished binary. Fossil needs
+# to link against the Z-Lib compression library. There are no
+# other required dependencies.
+ZLIB_LIB = -lz
+
+# If using zlib:
+LIB += $(ZLIB_LIB) $(LDFLAGS)
+
+# If using HTTPS:
+LIB += -lcrypto -lssl
+
+# Many platforms put cos() needed by src/piechart.c in libm, rather than
+# in libc. We cannot enable this by default because libm doesn't exist
+# everywhere.
+#LIB += -lm
+
+#### Tcl shell for use in running the fossil testsuite. If you do not
+# care about testing the end result, this can be blank.
+#
+TCLSH = tclsh
+
+CFLAGS += -fPIE
+CPPFLAGS += -I. -I$(SRCDIR_extsrc) -I$(SRCDIR)
+LIB = -lm -lz -lssl
+INSTALLDIR = $(DESTDIR)$(prefix)/bin
+SQLITE3_ORIGINAL = 0
+USE_LINENOISE = 1
+
+
+# You should not need to change anything below this line
+###############################################################################
+#
+# Automatic platform-specific options.
+HOST_OS_CMD = uname -s
+HOST_OS = $(HOST_OS_CMD:sh)
+
+LIB.SunOS= -lsocket -lnsl
+LIB += $(LIB.$(HOST_OS))
+
+TCC.DragonFly += -DUSE_PREAD
+TCC.FreeBSD += -DUSE_PREAD
+TCC.NetBSD += -DUSE_PREAD
+TCC.OpenBSD += -DUSE_PREAD
+TCC += $(TCC.$(HOST_OS))
+
+APPNAME = fossil$(E)
+.PHONY: all tags
+include $(SRCDIR)/main.mk
ADDED Makefile.in
Index: Makefile.in
==================================================================
--- Makefile.in
+++ Makefile.in
@@ -0,0 +1,168 @@
+#!/usr/bin/make
+#
+# This is the top-level makefile for Fossil when the build is occurring
+# on a unix platform. This works out-of-the-box on most unix platforms.
+# But you are free to vary some of the definitions if desired.
+#
+#### The toplevel directory of the source tree. Fossil can be built
+# in a directory that is separate from the source tree. Just change
+# the following to point from the build directory to the src/ folder.
+#
+SRCDIR = @srcdir@/src
+#### Upstream source files included directly in this repository.
+#
+SRCDIR_extsrc = @srcdir@/extsrc
+#### In-tree tools such as code generators and translators:
+#
+SRCDIR_tools = @srcdir@/tools
+
+#### The directory into which object code files should be written.
+# Having a "./" prefix in the value of this variable breaks our use of the
+# "makeheaders" tool when running make on the MinGW platform, apparently
+# due to some command line argument manipulation performed automatically
+# by the shell.
+#
+#
+OBJDIR = bld
+
+#### C Compiler and options for use in building executables that
+# will run on the platform that is doing the build. This is used
+# to compile code-generator programs as part of the build process.
+# See TCC below for the C compiler for building the finished binary.
+#
+BCC = @CC_FOR_BUILD@
+
+#### The suffix to add to final executable file. When cross-compiling
+# to windows, make this ".exe". Otherwise leave it blank.
+#
+E = @EXEEXT@
+
+TCC = @CC@
+
+#### Tcl shell for use in running the fossil testsuite. If you do not
+# care about testing the end result, this can be blank.
+#
+TCLSH = @TCLSH@
+
+CFLAGS = @CFLAGS@
+CFLAGS_INCLUDE = @CFLAGS_INCLUDE@
+LIB = @LDFLAGS@ @EXTRA_LDFLAGS@ @LIBS@
+BCCFLAGS = @CPPFLAGS@ $(CFLAGS)
+TCCFLAGS = @EXTRA_CFLAGS@ @CPPFLAGS@ $(CFLAGS) -DHAVE_AUTOCONFIG_H
+#
+# Fuzzing may be enable by appending -fsanitize=fuzzer -DFOSSIL_FUZZ
+# to the TCCFLAGS variable.
+# For more thorouth (but also slower) investigation
+# -fsanitize=fuzzer,undefined,address
+# might be more useful.
+
+INSTALLDIR = $(DESTDIR)@prefix@/bin
+USE_SYSTEM_SQLITE = @USE_SYSTEM_SQLITE@
+SQLITE3_SRC.2 = @SQLITE3_SRC.2@
+SQLITE3_OBJ.2 = @SQLITE3_OBJ.2@
+SQLITE3_SHELL_SRC.2 = @SQLITE3_SHELL_SRC.2@
+SQLITE3_ORIGIN = @SQLITE3_ORIGIN@
+# SQLITE3_ORIGIN changes...
+# SQLITE3_SRC:
+# 0=src/sqlite3.c, 1=src/sqlite3-see.c, 2=$(SQLITE3_SRC.2)
+# SQLITE3_SHELL_SRC:
+# 0=src/shell.c, 1=src/shell-see.c, 2=$(SQLITE3_SHELL_SRC.2)
+USE_LINENOISE = @USE_LINENOISE@
+USE_MMAN_H = @USE_MMAN_H@
+USE_SEE = @USE_SEE@
+APPNAME = fossil
+#
+# APPNAME = fossil-fuzz
+# may be more appropriate for fuzzing.
+
+#### Emscripten stuff for optionally doing in-tree builds
+# of any WASM components. We store precompiled WASM in the the SCM, so
+# this is only useful for people who actively work on WASM
+# components. EMSDK_ENV refers to the "environment" script which comes
+# with the Emscripten SDK package:
+# https://emscripten.org/docs/getting_started/downloads.html
+EMSDK_HOME = @EMSDK_HOME@
+EMSDK_ENV = @EMSDK_ENV@
+EMCC_OPT = @EMCC_OPT@
+EMCC_WRAPPER = $(SRCDIR_tools)/emcc.sh
+
+.PHONY: all tags
+
+include $(SRCDIR)/main.mk
+
+distclean: clean
+ -rm -f autoconfig.h config.log Makefile
+ -rm -f cscope.out tags
+
+reconfig:
+ @AUTOREMAKE@
+
+tags:
+ ctags -R @srcdir@/src
+ @COLLECT_CSCOPE_DATA@
+
+# Automatically reconfigure whenever an autosetup file or one of the
+# make source files change.
+#
+# The "touch" is necessary to avoid a make loop due to a new upstream
+# feature in autosetup (GH 0a71e3c3b7) which rewrites *.in outputs only
+# if doing so will write different contents; otherwise, it leaves them
+# alone so the mtime doesn't change. This means that if you change one
+# our depdendencies besides Makefile.in, we'll reconfigure but Makefile
+# won't change, so this rule will remain out of date, so we'll reconfig
+# but Makefile won't change, so we'll reconfig but... endlessly.
+#
+# This is also why we repeat the reconfig target's command here instead
+# of delegating to it with "$(MAKE) reconfig": having children running
+# around interfering makes this failure mode even worse.
+Makefile: @srcdir@/Makefile.in $(SRCDIR)/main.mk @AUTODEPS@
+ @AUTOREMAKE@
+ touch @builddir@/Makefile
+
+# Container stuff
+SRCTB := src-@FOSSIL_CI_PFX@.tar.gz
+IMGVER := fossil:@FOSSIL_CI_PFX@
+CNTVER := fossil-@FOSSIL_CI_PFX@
+CENGINE := docker
+container:
+ $(CENGINE) image inspect $(IMGVER) > /dev/null 2>&1 || \
+ $(MAKE) container-image
+ $(CENGINE) container inspect $(CNTVER) > /dev/null 2>&1 || \
+ $(CENGINE) create \
+ --name $(CNTVER) \
+ --cap-drop AUDIT_WRITE \
+ --cap-drop CHOWN \
+ --cap-drop FSETID \
+ --cap-drop KILL \
+ --cap-drop MKNOD \
+ --cap-drop NET_BIND_SERVICE \
+ --cap-drop NET_RAW \
+ --cap-drop SETFCAP \
+ --cap-drop SETPCAP \
+ --publish 8080:8080 \
+ $(DCFLAGS) $(IMGVER) $(DCCMD)
+
+container-clean:
+ -$(CENGINE) container kill $(CNTVER)
+ -$(CENGINE) container rm $(CNTVER)
+ -$(CENGINE) image rm $(IMGVER)
+
+container-image:
+ $(APPNAME) tarball --name src @FOSSIL_CI_PFX@ $(SRCTB)
+ $(CENGINE) buildx build \
+ --load \
+ --tag $(IMGVER) \
+ --build-arg FSLURL=$(SRCTB) \
+ $(DBFLAGS) @srcdir@
+ rm -f $(SRCTB)
+
+container-run container-start: container
+ $(CENGINE) start $(DSFLAGS) $(CNTVER)
+ @sleep 1 # decrease likelihood of logging race condition
+ $(CENGINE) container logs $(CNTVER)
+
+container-stop:
+ $(CENGINE) stop $(CNTVER)
+
+container-version:
+ @echo $(CNTVER)
ADDED Makefile.osx-jaguar
Index: Makefile.osx-jaguar
==================================================================
--- Makefile.osx-jaguar
+++ Makefile.osx-jaguar
@@ -0,0 +1,71 @@
+#!/usr/bin/make
+#
+# This is a specially modified version of the Makefile that will build
+# Fossil on Mac OSX Jaguar (10.2) circa 2002. This Makefile is used for
+# testing on an old PPC iBook. The use of this old platform helps to verify
+# Fossil and SQLite running on big-endian hardware.
+#
+# To build with this Makefile, run:
+#
+# make -f Makefile.osx-jaguar
+#
+#
+# This is the top-level makefile for Fossil when the build is occurring
+# on a unix platform. This works out-of-the-box on most unix platforms.
+# But you are free to vary some of the definitions if desired.
+#
+#### The toplevel directory of the source tree. Fossil can be built
+# in a directory that is separate from the source tree. Just change
+# the following to point from the build directory to the src/ folder.
+#
+SRCDIR = ./src
+
+#### The directory into which object code files should be written.
+# Having a "./" prefix in the value of this variable breaks our use of the
+# "makeheaders" tool when running make on the MinGW platform, apparently
+# due to some command line argument manipulation performed automatically
+# by the shell.
+#
+#
+OBJDIR = bld
+
+#### C Compiler and options for use in building executables that
+# will run on the platform that is doing the build. This is used
+# to compile code-generator programs as part of the build process.
+# See TCC below for the C compiler for building the finished binary.
+#
+BCC = cc
+BCCFLAGS = $(CFLAGS)
+
+#### The suffix to add to final executable file. When cross-compiling
+# to windows, make this ".exe". Otherwise leave it blank.
+#
+E =
+
+TCC = cc
+TCCFLAGS = $(CFLAGS)
+
+#### Tcl shell for use in running the fossil testsuite. If you do not
+# care about testing the end result, this can be blank.
+#
+TCLSH = tclsh
+
+# LIB = -lz
+LIB = compat/zlib/libz.a
+TCC += -g -O0 -DHAVE_AUTOCONFIG_H
+TCC += -Icompat/zlib
+TCC += -DSQLITE_WITHOUT_ZONEMALLOC
+TCC += -D_BSD_SOURCE=1
+TCC += -DWITHOUT_ICONV
+TCC += -Dsocklen_t=int
+TCC += -DSQLITE_MAX_MMAP_SIZE=0
+INSTALLDIR = $(DESTDIR)/usr/local/bin
+USE_SYSTEM_SQLITE =
+USE_LINENOISE = 1
+# FOSSIL_ENABLE_TCL = @FOSSIL_ENABLE_TCL@
+FOSSIL_ENABLE_TCL = 0
+
+include $(SRCDIR)/main.mk
+
+distclean: clean
+ rm -f autoconfig.h config.log Makefile
DELETED Makefile.w32
Index: Makefile.w32
==================================================================
--- Makefile.w32
+++ Makefile.w32
@@ -1,67 +0,0 @@
-#!/usr/bin/make
-#
-#### The toplevel directory of the source tree. Fossil can be built
-# in a directory that is separate from the source tree. Just change
-# the following to point from the build directory to the src/ folder.
-#
-SRCDIR = ./src
-OBJDIR = ./wobj
-
-#### C Compiler and options for use in building executables that
-# will run on the platform that is doing the build. This is used
-# to compile code-generator programs as part of the build process.
-# See TCC below for the C compiler for building the finished binary.
-#
-BCC = gcc -g -O2
-
-#### The suffix to add to executable files. ".exe" for windows.
-# Nothing for unix.
-#
-E = .exe
-
-#### Enable HTTPS support via OpenSSL (links to libssl and libcrypto)
-#
-# FOSSIL_ENABLE_SSL=1
-
-#### C Compile and options for use in building executables that
-# will run on the target platform. This is usually the same
-# as BCC, unless you are cross-compiling. This C compiler builds
-# the finished binary for fossil. The BCC compiler above is used
-# for building intermediate code-generator tools.
-#
-#TCC = gcc -O6
-#TCC = gcc -g -O0 -Wall -fprofile-arcs -ftest-coverage
-#TCC = gcc -g -Os -Wall
-#TCC = gcc -g -Os -Wall -DFOSSIL_I18N=0 -L/usr/local/lib -I/usr/local/include
-TCC = gcc -Os -Wall -DFOSSIL_I18N=0 -L/mingw/lib -I/mingw/include
-
-# With HTTPS support
-ifdef FOSSIL_ENABLE_SSL
-TCC += -DFOSSIL_ENABLE_SSL=1
-endif
-
-#### Extra arguments for linking the finished binary. Fossil needs
-# to link against the Z-Lib compression library. There are no
-# other dependencies. We sometimes add the -static option here
-# so that we can build a static executable that will run in a
-# chroot jail.
-#
-#LIB = -lz
-#LIB = -lz -lws2_32
-LIB = -lmingwex -lz -lws2_32
-# OpenSSL:
-ifdef FOSSIL_ENABLE_SSL
-LIB += -lcrypto -lssl
-endif
-
-#### Tcl shell for use in running the fossil testsuite.
-#
-TCLSH = tclsh
-
-#### Include a configuration file that can override any one of these settings.
-#
--include config.w32
-
-# You should not need to change anything below this line
-###############################################################################
-include $(SRCDIR)/main.mk
ADDED README.md
Index: README.md
==================================================================
--- README.md
+++ README.md
@@ -0,0 +1,15 @@
+# About Fossil
+
+Fossil is a distributed version control system that has been widely
+used since 2007. Fossil was originally designed to support the
+[SQLite](https://sqlite.org) project but has been adopted by many other
+projects as well.
+
+Fossil is self-hosting at .
+
+If you are reading this on GitHub, then you are looking at a Git mirror
+of the self-hosting Fossil repository. The purpose of that mirror is to
+test and exercise Fossil's ability to export a Git mirror. Nobody much
+uses the GitHub mirror, except to verify that the mirror logic works. If
+you want to know more about Fossil, visit the official self-hosting site
+linked above.
ADDED VERSION
Index: VERSION
==================================================================
--- VERSION
+++ VERSION
@@ -0,0 +1,1 @@
+2.22
DELETED art/CollRev1.dia
Index: art/CollRev1.dia
==================================================================
--- art/CollRev1.dia
+++ art/CollRev1.dia
@@ -1,793 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #File#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Project#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Meta#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Symbol#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #has#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #(Line of Development / Branch)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/CollRev2.dia
Index: art/CollRev2.dia
==================================================================
--- art/CollRev2.dia
+++ art/CollRev2.dia
@@ -1,576 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision' (Child)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #File#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Line of
-Development#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- # parent#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #branch parent symbol
- (NULL)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- # child#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/CollRev3.dia
Index: art/CollRev3.dia
==================================================================
--- art/CollRev3.dia
+++ art/CollRev3.dia
@@ -1,980 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ##
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Line of
-Development#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Line' of
-Development#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision''
-(Branch Start)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #File#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision'
-(Child)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- # branch
- parent#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- # parent#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- # child#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
- belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
- belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
- belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
- parent#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- # belongs to#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #=/=#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/CollRev4.dia
Index: art/CollRev4.dia
==================================================================
--- art/CollRev4.dia
+++ art/CollRev4.dia
@@ -1,640 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision'
-(Child NTDB)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision
-(NTDB)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision''
-(Child NTDB)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Revision""
-(non-NTDB)#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
- parent#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
-child#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
-child#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
- dbparent#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- # dbchild#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #
- parent#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/branching.odp
Index: art/branching.odp
==================================================================
--- art/branching.odp
+++ art/branching.odp
cannot compute difference between binary files
DELETED art/concept1.dia
Index: art/concept1.dia
==================================================================
--- art/concept1.dia
+++ art/concept1.dia
cannot compute difference between binary files
DELETED art/concept2.dia
Index: art/concept2.dia
==================================================================
--- art/concept2.dia
+++ art/concept2.dia
cannot compute difference between binary files
DELETED art/delta1.dia
Index: art/delta1.dia
==================================================================
--- art/delta1.dia
+++ art/delta1.dia
@@ -1,234 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Header#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Segments#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Trailer#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/delta2.dia
Index: art/delta2.dia
==================================================================
--- art/delta2.dia
+++ art/delta2.dia
@@ -1,352 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Copy Range#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Insert Literal#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #***#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/delta3.dia
Index: art/delta3.dia
==================================================================
--- art/delta3.dia
+++ art/delta3.dia
@@ -1,289 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Length#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #"@"#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Offset#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #","#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/delta4.dia
Index: art/delta4.dia
==================================================================
--- art/delta4.dia
+++ art/delta4.dia
@@ -1,234 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Length#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Bytes#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #":"#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/delta5.dia
Index: art/delta5.dia
==================================================================
--- art/delta5.dia
+++ art/delta5.dia
@@ -1,179 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #";"#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Checksum#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/delta6.dia
Index: art/delta6.dia
==================================================================
--- art/delta6.dia
+++ art/delta6.dia
@@ -1,179 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Size#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #"\n"#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/encode1.tex
Index: art/encode1.tex
==================================================================
--- art/encode1.tex
+++ art/encode1.tex
@@ -1,2 +0,0 @@
-\LARGE A = (\sum_{i=0}^{NHASH-1} z_i) \bmod 2^{16}
-
DELETED art/encode10.dia
Index: art/encode10.dia
==================================================================
--- art/encode10.dia
+++ art/encode10.dia
@@ -1,657 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
- #Letter#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Gap => Insert#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Processed#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Common => Copy#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Window#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Signature#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Base#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Slide#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Target#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #Origin#
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
DELETED art/encode2.tex
Index: art/encode2.tex
==================================================================
--- art/encode2.tex
+++ art/encode2.tex
@@ -1,1 +0,0 @@
-\LARGE B = (\sum_{i=0}^{NHASH-1} (NHASH-i)z_i) \bmod 2^{16}
DELETED art/encode3.tex
Index: art/encode3.tex
==================================================================
--- art/encode3.tex
+++ art/encode3.tex
@@ -1,1 +0,0 @@
-\LARGE V = 2^{16}B + A
DELETED art/encode4.tex
Index: art/encode4.tex
==================================================================
--- art/encode4.tex
+++ art/encode4.tex
@@ -1,1 +0,0 @@
-\LARGE z_0
DELETED art/encode5.tex
Index: art/encode5.tex
==================================================================
--- art/encode5.tex
+++ art/encode5.tex
@@ -1,1 +0,0 @@
-\LARGE z_{new}
DELETED art/encode6.tex
Index: art/encode6.tex
==================================================================
--- art/encode6.tex
+++ art/encode6.tex
@@ -1,1 +0,0 @@
-\LARGE A_{new} = (A - z_0 + z_{new}) \bmod 2^{16}
DELETED art/encode7.tex
Index: art/encode7.tex
==================================================================
--- art/encode7.tex
+++ art/encode7.tex
@@ -1,1 +0,0 @@
-\LARGE B_{new} = (B - z_0 NHASH + A_{new}) \bmod 2^{16}
DELETED art/encode8.tex
Index: art/encode8.tex
==================================================================
--- art/encode8.tex
+++ art/encode8.tex
@@ -1,1 +0,0 @@
-\LARGE V_{new} = 2^{16}B_{new} + A_{new}
DELETED art/encode9.tex
Index: art/encode9.tex
==================================================================
--- art/encode9.tex
+++ art/encode9.tex
@@ -1,1 +0,0 @@
-\LARGE A_{new}
ADDED auto.def
Index: auto.def
==================================================================
--- auto.def
+++ auto.def
@@ -0,0 +1,780 @@
+# System autoconfiguration. Try: ./configure --help
+
+# This must be above "options" below because it implicitly brings in the
+# default Autosetup options, things like --prefix.
+use cc cc-lib
+
+options {
+ with-openssl:path|auto|tree|none
+ => {Look for OpenSSL in the given path, automatically, in the source tree, or none}
+ with-zlib:path|auto|tree
+ => {Look for zlib in the given path, automatically, or in the source tree}
+ with-sqlite:path|auto|tree
+ => {Look for sqlite in the given path, automatically, or in the source tree.}
+ with-exec-rel-paths=0
+ => {Enable relative paths for external diff/gdiff}
+ with-sanitizer: => {Build with C compiler's -fsanitize=LIST; e.g. address,enum,null,undefined}
+ with-th1-docs=0 => {Enable TH1 for embedded documentation pages}
+ with-th1-hooks=0 => {Enable TH1 hooks for commands and web pages}
+ with-tcl:path => {Enable Tcl integration, with Tcl in the specified path}
+ with-tcl-stubs=0 => {Enable Tcl integration via stubs library mechanism}
+ with-tcl-private-stubs=0
+ => {Enable Tcl integration via private stubs mechanism}
+ with-mman=0 => {Enable use of POSIX memory APIs from "sys/mman.h"}
+ with-see=0 => {Enable the SQLite Encryption Extension (SEE)}
+ print-minimum-sqlite-version=0
+ => {print the minimum SQLite version number required, and exit}
+ internal-sqlite=1 => {Don't use the internal SQLite, use the system one}
+ static=0 => {Link a static executable}
+ fusefs=1 => {Disable the Fuse Filesystem}
+ fossil-debug=0 => {Build with fossil debugging enabled}
+ no-opt=0 => {Build without optimization}
+ json=0 => {Build with fossil JSON API enabled}
+ with-emsdk:path => {Directory containing the Emscripten SDK}
+}
+
+# Update the minimum required SQLite version number here, and also
+# in src/main.c near the sqlite3_libversion_number() call. Take care
+# that both places agree!
+define MINIMUM_SQLITE_VERSION "3.38.0"
+
+# This is useful for people wanting Fossil to use an external SQLite library
+# to compare the one they have against the minimum required
+if {[opt-bool print-minimum-sqlite-version]} {
+ puts [get-define MINIMUM_SQLITE_VERSION]
+ exit 0
+}
+
+# sqlite wants these types if possible
+cc-with {-includes {stdint.h inttypes.h}} {
+ cc-check-types uint32_t uint16_t int16_t uint8_t
+}
+
+# Use pread/pwrite system calls in place of seek + read/write if possible
+define USE_PREAD [cc-check-functions pread]
+
+# If we have cscope here, we'll use it in the "tags" target
+if {[cc-check-progs cscope]} {
+ define COLLECT_CSCOPE_DATA "cscope -bR $::autosetup(srcdir)/src/*.\[ch\]"
+} else {
+ define COLLECT_CSCOPE_DATA ""
+}
+
+# Find tclsh for the test suite.
+#
+# We can't use jimsh for this: the test suite uses features of Tcl that
+# Jim doesn't support, either statically or due to the way it's built by
+# autosetup. For example, Jim supports `file normalize`, but only if
+# you build it with HAVE_REALPATH, which won't ever be defined in this
+# context because autosetup doesn't try to discover platform-specific
+# details like that before it decides to build jimsh0. Besides which,
+# autosetup won't build jimsh0 at all if it can find tclsh itself.
+# Ironically, this means we may right now be running under either jimsh0
+# or a version of tclsh that we find unsuitable below!
+cc-check-progs tclsh
+set hbtd /usr/local/Cellar/tcl-tk
+if {[string equal false [get-define TCLSH]]} {
+ msg-result "WARNING: 'make test' will not run here."
+} else {
+ set v [exec /bin/sh -c "echo 'puts \$tcl_version' | tclsh"]
+ if {[expr {$v >= 8.6}]} {
+ msg-result "Found Tclsh version $v in the PATH."
+ define TCLSH tclsh
+ } elseif {[file isdirectory $hbtd]} {
+ # This is a macOS system with the Homebrew version of Tcl/Tk
+ # installed. Select the newest version. It won't normally be
+ # in the PATH to avoid shadowing /usr/bin/tclsh, and even if it
+ # were in the PATH, it's bad practice to put /usr/local/bin (the
+ # Homebrew default) ahead of /usr/bin, especially given that
+ # it's user-writeable by default with Homebrew. Thus, we can be
+ # pretty sure the only way to call it is with an absolute path.
+ set v [exec ls -tr $hbtd | tail -1]
+ set path "$hbtd/$v/bin/tclsh"
+ define TCLSH $path
+ msg-result "Using Homebrew Tcl/Tk version $path."
+ } else {
+ msg-result "WARNING: tclsh $v found; need >= 8.6 for 'make test'."
+ define TCLSH false ;# force "make test" failure via /usr/bin/false
+ }
+}
+
+define EXTRA_CFLAGS "-Wall"
+define EXTRA_LDFLAGS ""
+define USE_SYSTEM_SQLITE 0
+define USE_LINENOISE 0
+define USE_MMAN_H 0
+define USE_SEE 0
+define SQLITE3_ORIGIN 0
+# SQLITE3_ORIGIN 0 = src/sqlite3, 1=src/sqlite3-see.c, 2=client-provided
+
+# Maintain the C89/C90-style order of variable declarations before statements.
+# Check if the compiler supports the respective warning flag.
+if {[cctest -cflags -Wdeclaration-after-statement]} {
+ define-append EXTRA_CFLAGS -Wdeclaration-after-statement
+}
+
+
+# This procedure is a customized version of "cc-check-function-in-lib",
+# that does not modify the LIBS variable. Its use prevents prematurely
+# pulling in libraries that will be added later anyhow (e.g. "-ldl").
+proc check-function-in-lib {function libs {otherlibs {}}} {
+ if {[string length $otherlibs]} {
+ msg-checking "Checking for $function in $libs with $otherlibs..."
+ } else {
+ msg-checking "Checking for $function in $libs..."
+ }
+ set found 0
+ cc-with [list -libs $otherlibs] {
+ if {[cctest_function $function]} {
+ msg-result "none needed"
+ define lib_$function ""
+ incr found
+ } else {
+ foreach lib $libs {
+ cc-with [list -libs -l$lib] {
+ if {[cctest_function $function]} {
+ msg-result -l$lib
+ define lib_$function -l$lib
+ incr found
+ break
+ }
+ }
+ }
+ }
+ }
+ if {$found} {
+ define [feature-define-name $function]
+ } else {
+ msg-result "no"
+ }
+ return $found
+}
+
+if {![opt-bool internal-sqlite]} {
+ proc find_system_sqlite {} {
+
+ # On some systems (slackware), libsqlite3 requires -ldl to link. So
+ # search for the system SQLite once with -ldl, and once without. If
+ # the library can only be found with $extralibs set to -ldl, then
+ # the code below will append -ldl to LIBS.
+ #
+ foreach extralibs {{} {-ldl}} {
+
+ # Locate the system SQLite by searching for sqlite3_open(). Then check
+ # if sqlite3_stmt_isexplain can be found as well. If we can find open() but
+ # not stmt_isexplain(), then the system SQLite is too old to link against
+ # fossil.
+ #
+ if {[check-function-in-lib sqlite3_open sqlite3 $extralibs]} {
+ # Success. Update symbols and return.
+ #
+ define USE_SYSTEM_SQLITE 1
+ define-append LIBS -lsqlite3
+ define-append LIBS $extralibs
+ return
+ }
+ }
+ user-error "system sqlite3 not found"
+ }
+
+ find_system_sqlite
+
+ proc test_system_sqlite {} {
+ # Check compatibility of the system SQLite library by running the sqlcompttest.c
+ # program in the source tree
+ # passes MINIMUM_SQLITE_VERSION set at the top of this file to sqlcompttest.c
+ #
+ set cmdline {}
+ lappend cmdline {*}[get-define CCACHE]
+ lappend cmdline {*}[get-define CC] {*}[get-define CFLAGS]
+ lappend cmdline $::autosetup(dir)/../tools/sqlcompattest.c -o conftest__
+ lappend cmdline {*}[get-define LDFLAGS]
+ lappend cmdline {*}[get-define LIBS]
+ set sqlite-version [string cat "-D MINIMUM_SQLITE_VERSION=" [get-define MINIMUM_SQLITE_VERSION]]
+ lappend cmdline {*}[set sqlite-version]
+ set ok 1
+ set err [catch {exec-with-stderr {*}$cmdline} result errinfo]
+ if {$err} {
+ configlog "Failed: [join $cmdline]"
+ if {[string length $result]>0} {configlog $result}
+ configlog "============"
+ set ok 0
+ } elseif {$::autosetup(debug)} {
+ configlog "Compiled OK: [join $cmdline]"
+ configlog "============"
+ }
+ if {!$ok} {
+ user-error "unable to compile SQLite compatibility test program"
+ }
+ set err [catch {exec-with-stderr ./conftest__} result errinfo]
+ if {[get-define build] eq [get-define host]} {
+ set err [catch {exec-with-stderr ./conftest__} result errinfo]
+ if {$err} {
+ user-error $result
+ }
+ }
+ file delete ./conftest__
+ }
+ test_system_sqlite
+
+}
+
+proc is_mingw {} {
+ return [string match *mingw* [get-define host]]
+}
+
+if {[is_mingw]} {
+ define-append EXTRA_CFLAGS -DBROKEN_MINGW_CMDLINE
+ define-append LIBS -lkernel32 -lws2_32
+} else {
+ #
+ # NOTE: All platforms except MinGW should use the linenoise
+ # package. It is currently unsupported on Win32.
+ #
+ define USE_LINENOISE 1
+}
+
+if {[string match *-solaris* [get-define host]]} {
+ define-append EXTRA_CFLAGS {-D__EXTENSIONS__}
+}
+
+if {[opt-bool fossil-debug]} {
+ define CFLAGS {-g -O0 -Wall}
+ define-append CFLAGS -DFOSSIL_DEBUG
+ msg-result "Debugging support enabled"
+}
+
+if {[opt-bool no-opt]} {
+ define CFLAGS {-g -O0 -Wall}
+ msg-result "Builting without compiler optimization"
+ if {[opt-bool fossil-debug]} {
+ define-append CFLAGS -DFOSSIL_DEBUG
+ }
+}
+
+if {[opt-bool with-mman]} {
+ define-append EXTRA_CFLAGS -DUSE_MMAN_H
+ define USE_MMAN_H 1
+ msg-result "Enabling \"sys/mman.h\" support"
+}
+
+if {[opt-bool with-see]} {
+ define-append EXTRA_CFLAGS -DUSE_SEE
+ define USE_SEE 1
+ define SQLITE3_ORIGIN 1
+ msg-result "Enabling encryption support"
+}
+
+if {[opt-bool json]} {
+ # Reminder/FIXME (stephan): FOSSIL_ENABLE_JSON
+ # is required in the CFLAGS because json*.c
+ # have #ifdef guards around the whole file without
+ # reading config.h first.
+ define-append EXTRA_CFLAGS -DFOSSIL_ENABLE_JSON
+ define FOSSIL_ENABLE_JSON
+ msg-result "JSON support enabled"
+}
+
+if {[opt-bool with-exec-rel-paths]} {
+ define-append EXTRA_CFLAGS -DFOSSIL_ENABLE_EXEC_REL_PATHS
+ define FOSSIL_ENABLE_EXEC_REL_PATHS
+ msg-result "Relative paths in external diff/gdiff enabled"
+}
+
+if {[opt-bool with-th1-docs]} {
+ define-append EXTRA_CFLAGS -DFOSSIL_ENABLE_TH1_DOCS
+ define FOSSIL_ENABLE_TH1_DOCS
+ msg-result "TH1 embedded documentation support enabled"
+}
+
+if {[opt-bool with-th1-hooks]} {
+ define-append EXTRA_CFLAGS -DFOSSIL_ENABLE_TH1_HOOKS
+ define FOSSIL_ENABLE_TH1_HOOKS
+ msg-result "TH1 hooks support enabled"
+}
+
+#if {[opt-bool markdown]} {
+# # no-op. Markdown is now enabled by default.
+# msg-result "Markdown support enabled"
+#}
+
+if {[opt-bool static]} {
+ # XXX: This will not work on all systems.
+ define-append EXTRA_LDFLAGS -static
+ msg-result "Trying to link statically"
+} else {
+ define-append EXTRA_CFLAGS -DFOSSIL_DYNAMIC_BUILD=1
+ define FOSSIL_DYNAMIC_BUILD
+}
+
+# Check for libraries that need to be sorted out early
+cc-check-function-in-lib iconv iconv
+
+# Helper for OpenSSL checking
+proc check-for-openssl {msg {cflags {}} {libs {-lssl -lcrypto -lpthread}}} {
+ msg-checking "Checking for $msg..."
+ set rc 0
+ if {[is_mingw]} {
+ lappend libs -lgdi32 -lwsock32 -lcrypt32
+ }
+ if {[info exists ::zlib_lib]} {
+ lappend libs $::zlib_lib
+ }
+ msg-quiet cc-with [list -cflags $cflags -libs $libs] {
+ if {[cc-check-includes openssl/ssl.h] && \
+ [cc-check-functions SSL_new]} {
+ incr rc
+ }
+ }
+ if {!$rc && ![is_mingw]} {
+ # On some systems, OpenSSL appears to require -ldl to link.
+ lappend libs -ldl
+ msg-quiet cc-with [list -cflags $cflags -libs $libs] {
+ if {[cc-check-includes openssl/ssl.h] && \
+ [cc-check-functions SSL_new]} {
+ incr rc
+ }
+ }
+ }
+ if {$rc} {
+ msg-result "ok"
+ return 1
+ } else {
+ msg-result "no"
+ return 0
+ }
+}
+
+# Check for zlib, using the given location if specified
+set zlibpath [opt-val with-zlib]
+if {$zlibpath eq "tree"} {
+ set zlibdir [file dirname $autosetup(dir)]/compat/zlib
+ if {![file isdirectory $zlibdir]} {
+ user-error "The zlib in source tree directory does not exist"
+ } elseif { ([llength [glob -nocomplain -directory $zlibdir libz*]] == 0) } {
+ user-error "With --with-zlib=tree, $zlibdir must be configured and built first."
+ }
+ cc-with [list -cflags "-I$zlibdir -L$zlibdir"]
+ define-append EXTRA_CFLAGS -I$zlibdir
+ define-append LIBS $zlibdir/libz.a
+ set ::zlib_lib $zlibdir/libz.a
+ msg-result "Using zlib in source tree"
+} else {
+ if {$zlibpath ni {auto ""}} {
+ cc-with [list -cflags "-I$zlibpath -L$zlibpath"]
+ define-append EXTRA_CFLAGS -I$zlibpath
+ define-append EXTRA_LDFLAGS -L$zlibpath
+ msg-result "Using zlib from $zlibpath"
+ }
+ if {![cc-check-includes zlib.h] || ![check-function-in-lib inflateEnd z]} {
+ user-error "zlib not found please install it or specify the location with --with-zlib"
+ }
+ set ::zlib_lib -lz
+}
+
+set ssldirs [opt-val with-openssl]
+if {$ssldirs ne "none"} {
+ set found 0
+ if {$ssldirs eq "tree"} {
+ set ssldir [file dirname $autosetup(dir)]/compat/openssl
+ if {![file isdirectory $ssldir]} {
+ user-error "The OpenSSL in source tree directory does not exist"
+ }
+ set msg "ssl in $ssldir"
+ set cflags "-I$ssldir/include"
+ set ldflags "-L$ssldir"
+ set ssllibs "$ssldir/libssl.a $ssldir/libcrypto.a -lpthread"
+ set found [check-for-openssl "ssl in source tree" "$cflags $ldflags" $ssllibs]
+ } else {
+ if {$ssldirs in {auto ""}} {
+ catch {
+ set cflags [exec pkg-config openssl --cflags-only-I]
+ set ldflags [exec pkg-config openssl --libs-only-L]
+ set found [check-for-openssl "ssl via pkg-config" "$cflags $ldflags"]
+ } msg
+ if {!$found} {
+ set ssldirs "{} /usr/sfw /usr/local/ssl /usr/lib/ssl /usr/ssl \
+ /usr/pkg /usr/local /usr /usr/local/opt/openssl \
+ /opt/homebrew/opt/openssl"
+ }
+ }
+ if {!$found} {
+ foreach dir $ssldirs {
+ if {$dir eq ""} {
+ set msg "system ssl"
+ set cflags ""
+ set ldflags ""
+ } else {
+ set msg "ssl in $dir"
+ set cflags "-I$dir/include"
+ set ldflags "-L$dir/lib"
+ }
+ if {[check-for-openssl $msg "$cflags $ldflags"]} {
+ incr found
+ break
+ }
+ }
+ }
+ }
+ if {$found} {
+ define FOSSIL_ENABLE_SSL
+ define-append EXTRA_CFLAGS $cflags
+ define-append EXTRA_LDFLAGS $ldflags
+ if {[info exists ssllibs]} {
+ define-append LIBS $ssllibs
+ } else {
+ define-append LIBS -lssl -lcrypto
+ }
+ if {[info exists ::zlib_lib]} {
+ define-append LIBS $::zlib_lib
+ }
+ if {[is_mingw]} {
+ define-append LIBS -lgdi32 -lwsock32 -lcrypt32
+ }
+ msg-result "HTTPS support enabled"
+
+ # Silence OpenSSL deprecation warnings on Mac OS X 10.7.
+ if {[string match *-darwin* [get-define host]]} {
+ if {[cctest -cflags {-Wdeprecated-declarations}]} {
+ define-append EXTRA_CFLAGS -Wdeprecated-declarations
+ }
+ }
+ } else {
+ user-error "OpenSSL not found. Consider --with-openssl=none to disable HTTPS support"
+ }
+} else {
+ if {[info exists ::zlib_lib]} {
+ define-append LIBS $::zlib_lib
+ }
+}
+
+
+
+########################################################################
+# --with-sqlite=PATH checks for the first it finds of the following...
+# - PATH/sqlite3.c and PATH/sqlite3.h
+# - PATH/sqlite3.o (and assumes sqlite3.h is with it)
+# - PATH/lib/libsqlite3* and PATH/include/sqlite3.h
+define CFLAGS_INCLUDE {}
+# ^^^ CFLAGS_INCLUDE is ONLY for -I... flags and their order is
+# significant so that --with-sqlite=PATH's header can shadow our
+# own. One caveat with this is that we cannot point --with-sqlite=PATH
+# to the root of sqlite3's own build tree because that dir has a
+# config.h which ends up shadowing src/config.h, breaking our build.
+set sq3path [opt-val with-sqlite]
+define SQLITE3_SRC.2 {}
+define SQLITE3_OBJ.2 {}
+define SQLITE3_SHELL_SRC.2 {$(SQLITE3_SHELL_SRC.0)}
+if {$sq3path in {tree ""}} {
+ msg-result "Using sqlite3.c from this source tree."
+} else {
+ # SQLITE3_ORIGIN:
+ # 0 = local source tree
+ # 1 = use external lib or sqlite3.o
+ # 2 = use external sqlite3.c and (if found) shell.c
+ define USE_SYSTEM_SQLITE 1
+ define SQLITE3_ORIGIN 2
+ if {$sq3path != "auto"} {
+ if {([file exists $sq3path/sqlite3.c]) && \
+ ([file exists $sq3path/sqlite3.h]) } {
+ # Prefer sqlite3.[ch] if found.
+ define SQLITE3_SRC.2 $sq3path/sqlite3.c
+ define SQLITE3_OBJ.2 {$(SQLITE3_OBJ.0)}
+ define USE_SYSTEM_SQLITE 2
+ define SQLITE3_ORIGIN 2
+ if {[file exists $sq3path/shell.c]} {
+ define SQLITE3_SHELL_SRC.2 $sq3path/shell.c
+ }
+ define-append CFLAGS_INCLUDE -I$sq3path
+ define-append EXTRA_LDFLAGS -lpthread
+ # ^^^ additional -lXXX flags are conservative estimates
+ msg-result "Using sqlite3.c and sqlite3.h from $sq3path"
+ } elseif {[file exists $sq3path/sqlite3.o]} {
+ # Use sqlite3.o if found.
+ define SQLITE3_OBJ.2 $sq3path/sqlite3.o
+ define-append CFLAGS_INCLUDE -I$sq3path
+ define-append EXTRA_LDFLAGS $sq3path/sqlite3.o -lpthread
+ # ^^^ additional -lXXX flags are conservative estimates
+ msg-result "Using sqlite3.o from $sq3path"
+ } elseif { ([llength [glob -nocomplain -directory $sq3path/lib libsqlite3*]] != 0) \
+ && ([file exists $sq3path/include/sqlite3.h]) } {
+ # e.g. --with-sqlite=/usr/local. Try $sq3path/lib/libsqlite3*
+ # and $sq3path/include/sqlite3.h
+ define-append CFLAGS_INCLUDE -I$sq3path/include
+ define-append EXTRA_LDFLAGS -L$sq3path/lib -lsqlite3 -lpthread
+ # ^^^ additional -lXXX flags are conservative estimates
+ msg-result "Using -lsqlite3 from $sq3path"
+ } else {
+ # Assume $sq3path holds both the lib and header
+ cc-with [list -cflags "-I$sq3path -L$sq3path"]
+ define-append CFLAGS_INCLUDE -I$sq3path
+ define-append EXTRA_LDFLAGS -L$sq3path -lsqlite3 -lpthread
+ # ^^^ additional -lXXX flags are conservative estimates
+ msg-result "Using -lsqlite3 from $sq3path"
+ }
+ } elseif {![cc-check-includes sqlite3.h] || ![check-function-in-lib sqlite3_open_v2 sqlite3]} {
+ user-error "libsqlite3 not found please install it or specify the location with --with-sqlite"
+ }
+}
+define-append CFLAGS_INCLUDE {-I. -I$(SRCDIR) -I$(SRCDIR_extsrc)}
+
+set tclpath [opt-val with-tcl]
+if {$tclpath ne ""} {
+ set tclprivatestubs [opt-bool with-tcl-private-stubs]
+ # Note parse-tclconfig-sh is in autosetup/local.tcl
+ if {$tclpath eq "1"} {
+ set tcldir [file dirname $autosetup(dir)]/compat/tcl-8.6
+ if {$tclprivatestubs} {
+ set tclconfig(TCL_INCLUDE_SPEC) -I$tcldir/generic
+ set tclconfig(TCL_VERSION) {Private Stubs}
+ set tclconfig(TCL_PATCH_LEVEL) {}
+ set tclconfig(TCL_PREFIX) $tcldir
+ set tclconfig(TCL_LD_FLAGS) { }
+ } else {
+ # Use the system Tcl. Look in some likely places.
+ array set tclconfig [parse-tclconfig-sh \
+ $tcldir/unix $tcldir/win \
+ /usr /usr/local /usr/share /opt/local]
+ set msg "on your system"
+ }
+ } else {
+ array set tclconfig [parse-tclconfig-sh $tclpath]
+ set msg "at $tclpath"
+ }
+ if {[opt-bool static]} {
+ set tclconfig(TCL_LD_FLAGS) { }
+ }
+ if {![info exists tclconfig(TCL_INCLUDE_SPEC)]} {
+ user-error "Cannot find Tcl $msg"
+ }
+ set tclstubs [opt-bool with-tcl-stubs]
+ if {$tclprivatestubs} {
+ define FOSSIL_ENABLE_TCL_PRIVATE_STUBS
+ define USE_TCL_STUBS
+ } elseif {$tclstubs && $tclconfig(TCL_SUPPORTS_STUBS)} {
+ set libs "$tclconfig(TCL_STUB_LIB_SPEC)"
+ define FOSSIL_ENABLE_TCL_STUBS
+ define USE_TCL_STUBS
+ } else {
+ set libs "$tclconfig(TCL_LIB_SPEC) $tclconfig(TCL_LIBS)"
+ }
+ set cflags $tclconfig(TCL_INCLUDE_SPEC)
+ if {!$tclprivatestubs} {
+ set foundtcl 0; # Did we find a working Tcl library?
+ cc-with [list -cflags $cflags -libs $libs] {
+ if {$tclstubs} {
+ if {[cc-check-functions Tcl_InitStubs]} {
+ set foundtcl 1
+ }
+ } else {
+ if {[cc-check-functions Tcl_CreateInterp]} {
+ set foundtcl 1
+ }
+ }
+ }
+ if {!$foundtcl && [string match *-lieee* $libs]} {
+ # On some systems, using "-lieee" from TCL_LIB_SPEC appears
+ # to cause issues.
+ msg-result "Removing \"-lieee\" and retrying for Tcl..."
+ set libs [string map [list -lieee ""] $libs]
+ cc-with [list -cflags $cflags -libs $libs] {
+ if {$tclstubs} {
+ if {[cc-check-functions Tcl_InitStubs]} {
+ set foundtcl 1
+ }
+ } else {
+ if {[cc-check-functions Tcl_CreateInterp]} {
+ set foundtcl 1
+ }
+ }
+ }
+ }
+ if {!$foundtcl && ![string match *-lpthread* $libs]} {
+ # On some systems, TCL_LIB_SPEC appears to be missing
+ # "-lpthread". Try adding it.
+ msg-result "Adding \"-lpthread\" and retrying for Tcl..."
+ set libs "$libs -lpthread"
+ cc-with [list -cflags $cflags -libs $libs] {
+ if {$tclstubs} {
+ if {[cc-check-functions Tcl_InitStubs]} {
+ set foundtcl 1
+ }
+ } else {
+ if {[cc-check-functions Tcl_CreateInterp]} {
+ set foundtcl 1
+ }
+ }
+ }
+ }
+ if {!$foundtcl} {
+ if {$tclstubs} {
+ user-error "Cannot find a usable Tcl stubs library $msg"
+ } else {
+ user-error "Cannot find a usable Tcl library $msg"
+ }
+ }
+ }
+ set version $tclconfig(TCL_VERSION)$tclconfig(TCL_PATCH_LEVEL)
+ msg-result "Found Tcl $version at $tclconfig(TCL_PREFIX)"
+ if {!$tclprivatestubs} {
+ define-append LIBS $libs
+ }
+ define-append EXTRA_CFLAGS $cflags
+ if {[info exists zlibpath] && $zlibpath eq "tree"} {
+ #
+ # NOTE: When using zlib in the source tree, prevent Tcl from
+ # pulling in the system one.
+ #
+ set tclconfig(TCL_LD_FLAGS) [string map [list -lz ""] \
+ $tclconfig(TCL_LD_FLAGS)]
+ }
+ #
+ # NOTE: Remove "-ldl" from the TCL_LD_FLAGS because it will be
+ # be checked for near the bottom of this file.
+ #
+ set tclconfig(TCL_LD_FLAGS) [string map [list -ldl ""] \
+ $tclconfig(TCL_LD_FLAGS)]
+ define-append EXTRA_LDFLAGS $tclconfig(TCL_LD_FLAGS)
+ define FOSSIL_ENABLE_TCL
+}
+
+# Emscripten is a purely optional component used only for doing
+# in-tree builds of WASM stuff, as opposed to WASM binaries we import
+# from other places. This is only set up for Unix-style OSes and is
+# untested anywhere but Linux.
+set emsdkHome [opt-val with-emsdk]
+define EMSDK_HOME ""
+define EMSDK_ENV ""
+define EMCC_OPT "-Oz"
+if {$emsdkHome eq "" && [info exists ::env(EMSDK)]} {
+ # Fall back to checking the environment. $EMSDK gets set
+ # by sourcing emsdk_env.sh.
+ set emsdkHome $::env(EMSDK)
+}
+if {$emsdkHome ne ""} {
+ define EMSDK_HOME $emsdkHome
+ set emsdkEnv "$emsdkHome/emsdk_env.sh"
+ if {[file exists $emsdkEnv]} {
+ puts "Using Emscripten SDK environment from $emsdkEnv."
+ define EMSDK_ENV $emsdkEnv
+ if {[info exists ::env(EMCC_OPT)]} {
+ define EMCC_OPT $::env(EMCC_OPT)
+ }
+ } else {
+ puts "emsdk_env.sh not found. Assuming emcc is in the PATH."
+ }
+}
+
+# Network functions require libraries on some systems
+cc-check-function-in-lib gethostbyname nsl
+if {![cc-check-function-in-lib socket {socket network}]} {
+ # Last resort, may be Windows
+ if {[is_mingw]} {
+ define-append LIBS -lwsock32
+ }
+}
+
+# The SMTP module requires special libraries and headers for MX DNS
+# record lookups and such.
+cc-check-includes arpa/nameser.h
+cc-include-needs bind/resolv.h netinet/in.h
+cc-check-includes bind/resolv.h
+cc-check-includes resolv.h
+if { !(([cc-check-function-in-lib dn_expand resolv] ||
+ [cc-check-function-in-lib ns_name_uncompress {bind resolv}] ||
+ [cc-check-function-in-lib __ns_name_uncompress {bind resolv}]) &&
+ ([cc-check-function-in-lib ns_parserr {bind resolv}] ||
+ [cc-check-function-in-lib __ns_parserr {bind resolv}]) &&
+ ([cc-check-function-in-lib res_query {bind resolv}] ||
+ [cc-check-function-in-lib __res_query {bind resolv}]))} {
+ msg-result "WARNING: SMTP feature will not be able to look up local MX."
+}
+cc-check-function-in-lib res_9_ns_initparse resolv
+
+# Other nonstandard function checks
+cc-check-functions utime
+cc-check-functions usleep
+cc-check-functions strchrnul
+cc-check-functions pledge
+cc-check-functions backtrace
+
+# Termux on Android adds "getpass(char *)" to unistd.h, so check this so we
+# guard against including it again; use cctest as cc-check-functions and
+# cctest_function check for "getpass()" with no args and fail
+if {[cctest -link 1 -includes {unistd.h} -code "getpass(0);"]} {
+ define FOSSIL_HAVE_GETPASS 1
+ msg-result "Found getpass() with unistd.h"
+}
+
+# Check for getloadavg(), and if it doesn't exist, define FOSSIL_OMIT_LOAD_AVERAGE
+if {![cc-check-functions getloadavg]} {
+ define FOSSIL_OMIT_LOAD_AVERAGE 1
+ msg-result "Load average support unavailable"
+}
+
+# Check for getpassphrase() for Solaris 10 where getpass() truncates to 10 chars
+if {![cc-check-functions getpassphrase]} {
+ # Haiku needs this
+ cc-check-function-in-lib getpass bsd
+}
+cc-check-function-in-lib sin m
+
+# Check for the FuseFS library
+if {[opt-bool fusefs]} {
+ if {[opt-bool static]} {
+ msg-result "FuseFS support disabled due to -static"
+ } elseif {[cc-check-function-in-lib fuse_mount fuse]} {
+ define-append EXTRA_CFLAGS -DFOSSIL_HAVE_FUSEFS
+ define FOSSIL_HAVE_FUSEFS 1
+ define-append LIBS -lfuse
+ msg-result "FuseFS support enabled"
+ }
+}
+
+# Add -fsanitize compile and link options late: we don't want the C
+# checks above to run with those sanitizers enabled. It can not only
+# be pointless, it can actually break correct tests.
+set fsan [opt-val with-sanitizer]
+if {[string length $fsan]} {
+ define-append EXTRA_CFLAGS -fsanitize=$fsan
+ define-append EXTRA_LDFLAGS -fsanitize=$fsan
+ if {[string first "undefined" $fsan] != -1} {
+ # We need to link with libubsan if we're compiling under
+ # GCC with -fsanitize=undefined.
+ cc-check-function-in-lib __ubsan_handle_add_overflow ubsan
+ }
+}
+
+# Finally, append libraries that must be last. This matters more on some
+# OSes than others, but is most broadly required for static linking.
+if {[check-function-in-lib dlopen dl]} {
+ # Some platforms (*BSD) have the dl functions already in libc and no libdl.
+ # In such case we can link directly without -ldl.
+ define-append LIBS [get-define lib_dlopen]
+}
+if {[opt-bool static]} {
+ # Linux can only infer the dependency on pthread from OpenSSL when
+ # doing dynamic linkage.
+ define-append LIBS -lpthread
+}
+
+if {[get-define EMSDK_HOME] ne ""} {
+ define EMCC_WRAPPER $::autosetup(dir)/../tools/emcc.sh
+ make-template tools/emcc.sh.in
+ catch {exec chmod u+x tools/emcc.sh}
+} else {
+ define EMCC_WRAPPER ""
+ catch {exec rm -f tools/emcc.sh}
+}
+
+# Tag container builds with a prefix of the checkin ID of the version
+# of Fossil each one contains. This not only allows multiple images
+# to coexist and multiple containers to be created unamgiguosly from
+# them, it also changes the URL we fetch the source tarball from, so
+# repeated builds of a given version generate and fetch the source
+# tarball once only, keeping it in the local Docker/Podman cache.
+set ci [readfile "$::autosetup(srcdir)/manifest.uuid"]
+define FOSSIL_CI_PFX [string range $ci 0 11]
+
+make-template Makefile.in
+make-config-header autoconfig.h -auto {USE_* FOSSIL_*}
ADDED autosetup/LICENSE
Index: autosetup/LICENSE
==================================================================
--- autosetup/LICENSE
+++ autosetup/LICENSE
@@ -0,0 +1,35 @@
+Unless explicitly stated, all files which form part of autosetup
+are released under the following license:
+
+---------------------------------------------------------------------
+autosetup - A build environment "autoconfigurator"
+
+Copyright (c) 2010-2011, WorkWare Systems
+
+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 WORKWARE SYSTEMS ``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 WORKWARE
+SYSTEMS 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 views and conclusions contained in the software and documentation
+are those of the authors and should not be interpreted as representing
+official policies, either expressed or implied, of WorkWare Systems.
ADDED autosetup/README.autosetup
Index: autosetup/README.autosetup
==================================================================
--- autosetup/README.autosetup
+++ autosetup/README.autosetup
@@ -0,0 +1,11 @@
+README.autosetup created by autosetup v0.6.9
+
+This is the autosetup directory for a local install of autosetup.
+It contains autosetup, support files and loadable modules.
+
+*.tcl files in this directory are optional modules which
+can be loaded with the 'use' directive.
+
+*.auto files in this directory are auto-loaded.
+
+For more information, see http://msteveb.github.com/autosetup/
ADDED autosetup/autosetup
Index: autosetup/autosetup
==================================================================
--- autosetup/autosetup
+++ autosetup/autosetup
@@ -0,0 +1,2459 @@
+#!/bin/sh
+# Copyright (c) 2006-2011 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+# vim:se syntax=tcl:
+# \
+dir=`dirname "$0"`; exec "`$dir/autosetup-find-tclsh`" "$0" "$@"
+
+# Note that the version has a trailing + on unreleased versions
+set autosetup(version) 0.6.9
+
+# Can be set to 1 to debug early-init problems
+set autosetup(debug) [expr {"--debug" in $argv}]
+
+##################################################################
+#
+# Main flow of control, option handling
+#
+proc main {argv} {
+ global autosetup define
+
+ # There are 3 potential directories involved:
+ # 1. The directory containing autosetup (this script)
+ # 2. The directory containing auto.def
+ # 3. The current directory
+
+ # From this we need to determine:
+ # a. The path to this script (and related support files)
+ # b. The path to auto.def
+ # c. The build directory, where output files are created
+
+ # This is also complicated by the fact that autosetup may
+ # have been run via the configure wrapper ([getenv WRAPPER] is set)
+
+ # Here are the rules.
+ # a. This script is $::argv0
+ # => dir, prog, exe, libdir
+ # b. auto.def is in the directory containing the configure wrapper,
+ # otherwise it is in the current directory.
+ # => srcdir, autodef
+ # c. The build directory is the current directory
+ # => builddir, [pwd]
+
+ # 'misc' is needed before we can do anything, so set a temporary libdir
+ # in case this is the development version
+ set autosetup(libdir) [file dirname $::argv0]/lib
+ use misc
+
+ # (a)
+ set autosetup(dir) [realdir [file dirname [realpath $::argv0]]]
+ set autosetup(prog) [file join $autosetup(dir) [file tail $::argv0]]
+ set autosetup(exe) [getenv WRAPPER $autosetup(prog)]
+ if {$autosetup(installed)} {
+ set autosetup(libdir) $autosetup(dir)
+ } else {
+ set autosetup(libdir) [file join $autosetup(dir) lib]
+ }
+ autosetup_add_dep $autosetup(prog)
+
+ # (b)
+ if {[getenv WRAPPER ""] eq ""} {
+ # Invoked directly
+ set autosetup(srcdir) [pwd]
+ } else {
+ # Invoked via the configure wrapper
+ set autosetup(srcdir) [file-normalize [file dirname $autosetup(exe)]]
+ }
+ set autosetup(autodef) [relative-path $autosetup(srcdir)/auto.def]
+
+ # (c)
+ set autosetup(builddir) [pwd]
+
+ set autosetup(argv) $argv
+ set autosetup(cmdline) {}
+ # options is a list of known options
+ set autosetup(options) {}
+ # optset is a dictionary of option values set by the user based on getopt
+ set autosetup(optset) {}
+ # optdefault is a dictionary of default values
+ set autosetup(optdefault) {}
+ # options-defaults is a dictionary of overrides for default values for options
+ set autosetup(options-defaults) {}
+ set autosetup(optionhelp) {}
+ set autosetup(showhelp) 0
+
+ use util
+
+ # Parse options
+ use getopt
+
+ # At the is point we don't know what is a valid option
+ # We simply parse anything that looks like an option
+ set autosetup(getopt) [getopt argv]
+
+ #"=Core Options:"
+ options-add {
+ help:=local => "display help and options. Optionally specify a module name, such as --help=system"
+ licence license => "display the autosetup license"
+ version => "display the version of autosetup"
+ ref:=text manual:=text
+ reference:=text => "display the autosetup command reference. 'text', 'wiki', 'asciidoc' or 'markdown'"
+ debug => "display debugging output as autosetup runs"
+ install:=. => "install autosetup to the current or given directory"
+ }
+ if {$autosetup(installed)} {
+ # hidden options so we can produce a nice error
+ options-add {
+ sysinstall:path
+ }
+ } else {
+ options-add {
+ sysinstall:path => "install standalone autosetup to the given directory (e.g.: /usr/local)"
+ }
+ }
+ options-add {
+ force init:=help => "create initial auto.def, etc. Use --init=help for known types"
+ # Undocumented options
+ option-checking=1
+ nopager
+ quiet
+ timing
+ conf:
+ }
+
+ if {[opt-bool version]} {
+ puts $autosetup(version)
+ exit 0
+ }
+
+ # autosetup --conf=alternate-auto.def
+ if {[opt-str conf o]} {
+ set autosetup(autodef) $o
+ }
+
+ # Debugging output (set this early)
+ incr autosetup(debug) [opt-bool debug]
+ incr autosetup(force) [opt-bool force]
+ incr autosetup(msg-quiet) [opt-bool quiet]
+ incr autosetup(msg-timing) [opt-bool timing]
+
+ # If the local module exists, source it now to allow for
+ # project-local customisations
+ if {[file exists $autosetup(libdir)/local.tcl]} {
+ use local
+ }
+
+ # Now any auto-load modules
+ autosetup_load_auto_modules
+
+ if {[opt-str help o]} {
+ incr autosetup(showhelp)
+ use help
+ autosetup_help $o
+ }
+
+ if {[opt-bool licence license]} {
+ use help
+ autosetup_show_license
+ exit 0
+ }
+
+ if {[opt-str {manual ref reference} o]} {
+ use help
+ autosetup_reference $o
+ }
+
+ # Allow combining --install and --init
+ set earlyexit 0
+ if {[opt-str install o]} {
+ use install
+ autosetup_install $o
+ incr earlyexit
+ }
+
+ if {[opt-str init o]} {
+ use init
+ autosetup_init $o
+ incr earlyexit
+ }
+
+ if {$earlyexit} {
+ exit 0
+ }
+ if {[opt-str sysinstall o]} {
+ use install
+ autosetup_install $o 1
+ exit 0
+ }
+
+ if {![file exists $autosetup(autodef)]} {
+ # Check for invalid option first
+ options {}
+ user-error "No auto.def found in \"$autosetup(srcdir)\" (use [file tail $::autosetup(exe)] --init to create one)"
+ }
+
+ # Parse extra arguments into autosetup(cmdline)
+ foreach arg $argv {
+ if {[regexp {([^=]*)=(.*)} $arg -> n v]} {
+ dict set autosetup(cmdline) $n $v
+ define $n $v
+ } else {
+ user-error "Unexpected parameter: $arg"
+ }
+ }
+
+ autosetup_add_dep $autosetup(autodef)
+
+ define CONFIGURE_OPTS ""
+ foreach arg $autosetup(argv) {
+ define-append CONFIGURE_OPTS [quote-if-needed $arg]
+ }
+ define AUTOREMAKE [file-normalize $autosetup(exe)]
+ define-append AUTOREMAKE [get-define CONFIGURE_OPTS]
+
+
+ # Log how we were invoked
+ configlog "Invoked as: [getenv WRAPPER $::argv0] [quote-argv $autosetup(argv)]"
+ configlog "Tclsh: [info nameofexecutable]"
+
+ # Note that auto.def is *not* loaded in the global scope
+ source $autosetup(autodef)
+
+ # Could warn here if options {} was not specified
+
+ show-notices
+
+ if {$autosetup(debug)} {
+ msg-result "Writing all defines to config.log"
+ configlog "================ defines ======================"
+ foreach n [lsort [array names define]] {
+ configlog "define $n $define($n)"
+ }
+ }
+
+ exit 0
+}
+
+# @opt-bool ?-nodefault? option ...
+#
+# Check each of the named, boolean options and if any have been explicitly enabled
+# or disabled by the user, return 1 or 0 accordingly.
+#
+# If the option was specified more than once, the last value wins.
+# e.g. With '--enable-foo --disable-foo', '[opt-bool foo]' will return 0
+#
+# If no value was specified by the user, returns the default value for the
+# first option. If '-nodefault' is given, this behaviour changes and
+# -1 is returned instead.
+#
+proc opt-bool {args} {
+ set nodefault 0
+ if {[lindex $args 0] eq "-nodefault"} {
+ set nodefault 1
+ set args [lrange $args 1 end]
+ }
+ option-check-names {*}$args
+
+ foreach opt $args {
+ if {[dict exists $::autosetup(optset) $opt]} {
+ return [dict get $::autosetup(optset) $opt]
+ }
+ }
+
+ if {$nodefault} {
+ return -1
+ }
+ # Default value is the default for the first option
+ return [dict get $::autosetup(optdefault) [lindex $args 0]]
+}
+
+# @opt-val optionlist ?default=""?
+#
+# Returns a list containing all the values given for the non-boolean options in '$optionlist'.
+# There will be one entry in the list for each option given by the user, including if the
+# same option was used multiple times.
+#
+# If no options were set, '$default' is returned (exactly, not as a list).
+#
+# Note: For most use cases, 'opt-str' should be preferred.
+#
+proc opt-val {names {default ""}} {
+ option-check-names {*}$names
+
+ foreach opt $names {
+ if {[dict exists $::autosetup(optset) $opt]} {
+ lappend result {*}[dict get $::autosetup(optset) $opt]
+ }
+ }
+ if {[info exists result]} {
+ return $result
+ }
+ return $default
+}
+
+# @opt-str optionlist varname ?default?
+#
+# Sets '$varname' in the callers scope to the value for one of the given options.
+#
+# For the list of options given in '$optionlist', if any value is set for any option,
+# the option value is taken to be the *last* value of the last option (in the order given).
+#
+# If no option was given, and a default was specified with 'options-defaults',
+# that value is used.
+#
+# If no 'options-defaults' value was given and '$default' was given, it is used.
+#
+# If none of the above provided a value, no value is set.
+#
+# The return value depends on whether '$default' was specified.
+# If it was, the option value is returned.
+# If it was not, 1 is returns if a value was set, or 0 if not.
+#
+# Typical usage is as follows:
+#
+## if {[opt-str {myopt altname} o]} {
+## do something with $o
+## }
+#
+# Or:
+## define myname [opt-str {myopt altname} o "/usr/local"]
+#
+proc opt-str {names varname args} {
+ global autosetup
+
+ option-check-names {*}$names
+ upvar $varname value
+
+ if {[llength $args]} {
+ # A default was given, so always return the string value of the option
+ set default [lindex $args 0]
+ set retopt 1
+ } else {
+ # No default, so return 0 or 1 to indicate if a value was found
+ set retopt 0
+ }
+
+ foreach opt $names {
+ if {[dict exists $::autosetup(optset) $opt]} {
+ set result [lindex [dict get $::autosetup(optset) $opt] end]
+ }
+ }
+
+ if {![info exists result]} {
+ # No user-specified value. Has options-defaults been set?
+ foreach opt $names {
+ if {[dict exists $::autosetup(options-defaults) $opt]} {
+ set result [dict get $autosetup(options-defaults) $opt]
+ }
+ }
+ }
+
+ if {[info exists result]} {
+ set value $result
+ if {$retopt} {
+ return $value
+ }
+ return 1
+ }
+
+ if {$retopt} {
+ set value $default
+ return $value
+ }
+
+ return 0
+}
+
+proc option-check-names {args} {
+ foreach o $args {
+ if {$o ni $::autosetup(options)} {
+ autosetup-error "Request for undeclared option --$o"
+ }
+ }
+}
+
+# Parse the option definition in $opts and update
+# ::autosetup(setoptions) and ::autosetup(optionhelp) appropriately
+#
+proc options-add {opts {header ""}} {
+ global autosetup
+
+ # First weed out comment lines
+ set realopts {}
+ foreach line [split $opts \n] {
+ if {![string match "#*" [string trimleft $line]]} {
+ append realopts $line \n
+ }
+ }
+ set opts $realopts
+
+ for {set i 0} {$i < [llength $opts]} {incr i} {
+ set opt [lindex $opts $i]
+ if {[string match =* $opt]} {
+ # This is a special heading
+ lappend autosetup(optionhelp) $opt ""
+ set header {}
+ continue
+ }
+ unset -nocomplain defaultvalue equal value
+
+ #puts "i=$i, opt=$opt"
+ regexp {^([^:=]*)(:)?(=)?(.*)$} $opt -> name colon equal value
+ if {$name in $autosetup(options)} {
+ autosetup-error "Option $name already specified"
+ }
+
+ #puts "$opt => $name $colon $equal $value"
+
+ # Find the corresponding value in the user options
+ # and set the default if necessary
+ if {[string match "-*" $opt]} {
+ # This is a documentation-only option, like "-C "
+ set opthelp $opt
+ } elseif {$colon eq ""} {
+ # Boolean option
+ lappend autosetup(options) $name
+
+ # Check for override
+ if {[dict exists $autosetup(options-defaults) $name]} {
+ # A default was specified with options-defaults, so use it
+ set value [dict get $autosetup(options-defaults) $name]
+ }
+
+ if {$value eq "1"} {
+ set opthelp "--disable-$name"
+ } else {
+ set opthelp "--$name"
+ }
+
+ # Set the default
+ if {$value eq ""} {
+ set value 0
+ }
+ set defaultvalue $value
+ dict set autosetup(optdefault) $name $defaultvalue
+
+ if {[dict exists $autosetup(getopt) $name]} {
+ # The option was specified by the user. Look at the last value.
+ lassign [lindex [dict get $autosetup(getopt) $name] end] type setvalue
+ if {$type eq "str"} {
+ # Can we convert the value to a boolean?
+ if {$setvalue in {1 enabled yes}} {
+ set setvalue 1
+ } elseif {$setvalue in {0 disabled no}} {
+ set setvalue 0
+ } else {
+ user-error "Boolean option $name given as --$name=$setvalue"
+ }
+ }
+ dict set autosetup(optset) $name $setvalue
+ #puts "Found boolean option --$name=$setvalue"
+ }
+ } else {
+ # String option.
+ lappend autosetup(options) $name
+
+ if {$colon eq ":"} {
+ # Was ":name=default" given?
+ # If so, set $value to the display name and $defaultvalue to the default
+ # (This is the preferred way to set a default value for a string option)
+ if {[regexp {^([^=]+)=(.*)$} $value -> value defaultvalue]} {
+ dict set autosetup(optdefault) $name $defaultvalue
+ }
+ }
+
+ # Maybe override the default value
+ if {[dict exists $autosetup(options-defaults) $name]} {
+ # A default was specified with options-defaults, so use it
+ set defaultvalue [dict get $autosetup(options-defaults) $name]
+ dict set autosetup(optdefault) $name $defaultvalue
+ } elseif {![info exists defaultvalue]} {
+ # For backward compatibility, if ":name" was given, use name as both
+ # the display text and the default value, but only if the user
+ # specified the option without the value
+ set defaultvalue $value
+ }
+
+ if {$equal eq "="} {
+ # String option with optional value
+ set opthelp "--$name?=$value?"
+ } else {
+ # String option with required value
+ set opthelp "--$name=$value"
+ }
+
+ # Get the values specified by the user
+ if {[dict exists $autosetup(getopt) $name]} {
+ set listvalue {}
+
+ foreach pair [dict get $autosetup(getopt) $name] {
+ lassign $pair type setvalue
+ if {$type eq "bool" && $setvalue} {
+ if {$equal ne "="} {
+ user-error "Option --$name requires a value"
+ }
+ # If given as a boolean, use the default value
+ set setvalue $defaultvalue
+ }
+ lappend listvalue $setvalue
+ }
+
+ #puts "Found string option --$name=$listvalue"
+ dict set autosetup(optset) $name $listvalue
+ }
+ }
+
+ # Now create the help for this option if appropriate
+ if {[lindex $opts $i+1] eq "=>"} {
+ set desc [lindex $opts $i+2]
+ if {[info exists defaultvalue]} {
+ set desc [string map [list @default@ $defaultvalue] $desc]
+ }
+ #string match \n* $desc
+ if {$header ne ""} {
+ lappend autosetup(optionhelp) $header ""
+ set header ""
+ }
+ # A multi-line description
+ lappend autosetup(optionhelp) $opthelp $desc
+ incr i 2
+ }
+ }
+}
+
+# @module-options optionlist
+#
+# Like 'options', but used within a module.
+proc module-options {opts} {
+ set header ""
+ if {$::autosetup(showhelp) > 1 && [llength $opts]} {
+ set header "Module Options:"
+ }
+ options-add $opts $header
+
+ if {$::autosetup(showhelp)} {
+ # Ensure that the module isn't executed on --help
+ # We are running under eval or source, so use break
+ # to prevent further execution
+ #return -code break -level 2
+ return -code break
+ }
+}
+
+proc max {a b} {
+ expr {$a > $b ? $a : $b}
+}
+
+proc options-wrap-desc {text length firstprefix nextprefix initial} {
+ set len $initial
+ set space $firstprefix
+ foreach word [split $text] {
+ set word [string trim $word]
+ if {$word == ""} {
+ continue
+ }
+ if {$len && [string length $space$word] + $len >= $length} {
+ puts ""
+ set len 0
+ set space $nextprefix
+ }
+ incr len [string length $space$word]
+ puts -nonewline $space$word
+ set space " "
+ }
+ if {$len} {
+ puts ""
+ }
+}
+
+proc options-show {} {
+ # Determine the max option width
+ set max 0
+ foreach {opt desc} $::autosetup(optionhelp) {
+ if {[string match =* $opt] || [string match \n* $desc]} {
+ continue
+ }
+ set max [max $max [string length $opt]]
+ }
+ set indent [string repeat " " [expr $max+4]]
+ set cols [getenv COLUMNS 80]
+ catch {
+ lassign [exec stty size] rows cols
+ }
+ incr cols -1
+ # Now output
+ foreach {opt desc} $::autosetup(optionhelp) {
+ if {[string match =* $opt]} {
+ puts [string range $opt 1 end]
+ continue
+ }
+ puts -nonewline " [format %-${max}s $opt]"
+ if {[string match \n* $desc]} {
+ puts $desc
+ } else {
+ options-wrap-desc [string trim $desc] $cols " " $indent [expr $max + 2]
+ }
+ }
+}
+
+# @options optionspec
+#
+# Specifies configuration-time options which may be selected by the user
+# and checked with 'opt-str' and 'opt-bool'. '$optionspec' contains a series
+# of options specifications separated by newlines, as follows:
+#
+# A boolean option is of the form:
+#
+## name[=0|1] => "Description of this boolean option"
+#
+# The default is 'name=0', meaning that the option is disabled by default.
+# If 'name=1' is used to make the option enabled by default, the description should reflect
+# that with text like "Disable support for ...".
+#
+# An argument option (one which takes a parameter) is of the form:
+#
+## name:[=]value => "Description of this option"
+#
+# If the 'name:value' form is used, the value must be provided with the option (as '--name=myvalue').
+# If the 'name:=value' form is used, the value is optional and the given value is used as the default
+# if it is not provided.
+#
+# The description may contain '@default@', in which case it will be replaced with the default
+# value for the option (taking into account defaults specified with 'options-defaults'.
+#
+# Undocumented options are also supported by omitting the '=> description'.
+# These options are not displayed with '--help' and can be useful for internal options or as aliases.
+#
+# For example, '--disable-lfs' is an alias for '--disable=largefile':
+#
+## lfs=1 largefile=1 => "Disable large file support"
+#
+proc options {optlist} {
+ # Allow options as a list or args
+ options-add $optlist "Local Options:"
+
+ if {$::autosetup(showhelp)} {
+ options-show
+ exit 0
+ }
+
+ # Check for invalid options
+ if {[opt-bool option-checking]} {
+ foreach o [dict keys $::autosetup(getopt)] {
+ if {$o ni $::autosetup(options)} {
+ user-error "Unknown option --$o"
+ }
+ }
+ }
+}
+
+# @options-defaults dictionary
+#
+# Specifies a dictionary of options and a new default value for each of those options.
+# Use before any 'use' statements in 'auto.def' to change the defaults for
+# subsequently included modules.
+proc options-defaults {dict} {
+ foreach {n v} $dict {
+ dict set ::autosetup(options-defaults) $n $v
+ }
+}
+
+proc config_guess {} {
+ if {[file-isexec $::autosetup(dir)/autosetup-config.guess]} {
+ if {[catch {exec-with-stderr sh $::autosetup(dir)/autosetup-config.guess} alias]} {
+ user-error $alias
+ }
+ return $alias
+ } else {
+ configlog "No autosetup-config.guess, so using uname"
+ string tolower [exec uname -p]-unknown-[exec uname -s][exec uname -r]
+ }
+}
+
+proc config_sub {alias} {
+ if {[file-isexec $::autosetup(dir)/autosetup-config.sub]} {
+ if {[catch {exec-with-stderr sh $::autosetup(dir)/autosetup-config.sub $alias} alias]} {
+ user-error $alias
+ }
+ }
+ return $alias
+}
+
+# @define name ?value=1?
+#
+# Defines the named variable to the given value.
+# These (name, value) pairs represent the results of the configuration check
+# and are available to be subsequently checked, modified and substituted.
+#
+proc define {name {value 1}} {
+ set ::define($name) $value
+ #dputs "$name <= $value"
+}
+
+# @undefine name
+#
+# Undefine the named variable.
+#
+proc undefine {name} {
+ unset -nocomplain ::define($name)
+ #dputs "$name <= "
+}
+
+# @define-append name value ...
+#
+# Appends the given value(s) to the given "defined" variable.
+# If the variable is not defined or empty, it is set to '$value'.
+# Otherwise the value is appended, separated by a space.
+# Any extra values are similarly appended.
+# If any value is already contained in the variable (as a substring) it is omitted.
+#
+proc define-append {name args} {
+ if {[get-define $name ""] ne ""} {
+ # Avoid duplicates
+ foreach arg $args {
+ if {$arg eq ""} {
+ continue
+ }
+ set found 0
+ foreach str [split $::define($name) " "] {
+ if {$str eq $arg} {
+ incr found
+ }
+ }
+ if {!$found} {
+ append ::define($name) " " $arg
+ }
+ }
+ } else {
+ set ::define($name) [join $args]
+ }
+ #dputs "$name += [join $args] => $::define($name)"
+}
+
+# @get-define name ?default=0?
+#
+# Returns the current value of the "defined" variable, or '$default'
+# if not set.
+#
+proc get-define {name {default 0}} {
+ if {[info exists ::define($name)]} {
+ #dputs "$name => $::define($name)"
+ return $::define($name)
+ }
+ #dputs "$name => $default"
+ return $default
+}
+
+# @is-defined name
+#
+# Returns 1 if the given variable is defined.
+#
+proc is-defined {name} {
+ info exists ::define($name)
+}
+
+# @is-define-set name
+#
+# Returns 1 if the given variable is defined and is set
+# to a value other than "" or 0
+#
+proc is-define-set {name} {
+ if {[get-define $name] in {0 ""}} {
+ return 0
+ }
+ return 1
+}
+
+# @all-defines
+#
+# Returns a dictionary (name, value list) of all defined variables.
+#
+# This is suitable for use with 'dict', 'array set' or 'foreach'
+# and allows for arbitrary processing of the defined variables.
+#
+proc all-defines {} {
+ array get ::define
+}
+
+
+# @get-env name default
+#
+# If '$name' was specified on the command line, return it.
+# Otherwise if '$name' was set in the environment, return it.
+# Otherwise return '$default'.
+#
+proc get-env {name default} {
+ if {[dict exists $::autosetup(cmdline) $name]} {
+ return [dict get $::autosetup(cmdline) $name]
+ }
+ getenv $name $default
+}
+
+# @env-is-set name
+#
+# Returns 1 if '$name' was specified on the command line or in the environment.
+# Note that an empty environment variable is not considered to be set.
+#
+proc env-is-set {name} {
+ if {[dict exists $::autosetup(cmdline) $name]} {
+ return 1
+ }
+ if {[getenv $name ""] ne ""} {
+ return 1
+ }
+ return 0
+}
+
+# @readfile filename ?default=""?
+#
+# Return the contents of the file, without the trailing newline.
+# If the file doesn't exist or can't be read, returns '$default'.
+#
+proc readfile {filename {default_value ""}} {
+ set result $default_value
+ catch {
+ set f [open $filename]
+ set result [read -nonewline $f]
+ close $f
+ }
+ return $result
+}
+
+# @writefile filename value
+#
+# Creates the given file containing '$value'.
+# Does not add an extra newline.
+#
+proc writefile {filename value} {
+ set f [open $filename w]
+ puts -nonewline $f $value
+ close $f
+}
+
+proc quote-if-needed {str} {
+ if {[string match {*[\" ]*} $str]} {
+ return \"[string map [list \" \\" \\ \\\\] $str]\"
+ }
+ return $str
+}
+
+proc quote-argv {argv} {
+ set args {}
+ foreach arg $argv {
+ lappend args [quote-if-needed $arg]
+ }
+ join $args
+}
+
+# @list-non-empty list
+#
+# Returns a copy of the given list with empty elements removed
+proc list-non-empty {list} {
+ set result {}
+ foreach p $list {
+ if {$p ne ""} {
+ lappend result $p
+ }
+ }
+ return $result
+}
+
+# @find-executable-path name
+#
+# Searches the path for an executable with the given name.
+# Note that the name may include some parameters, e.g. 'cc -mbig-endian',
+# in which case the parameters are ignored.
+# The full path to the executable if found, or "" if not found.
+# Returns 1 if found, or 0 if not.
+#
+proc find-executable-path {name} {
+ # Ignore any parameters
+ set name [lindex $name 0]
+ # The empty string is never a valid executable
+ if {$name ne ""} {
+ foreach p [split-path] {
+ dputs "Looking for $name in $p"
+ set exec [file join $p $name]
+ if {[file-isexec $exec]} {
+ dputs "Found $name -> $exec"
+ return $exec
+ }
+ }
+ }
+ return {}
+}
+
+# @find-executable name
+#
+# Searches the path for an executable with the given name.
+# Note that the name may include some parameters, e.g. 'cc -mbig-endian',
+# in which case the parameters are ignored.
+# Returns 1 if found, or 0 if not.
+#
+proc find-executable {name} {
+ if {[find-executable-path $name] eq {}} {
+ return 0
+ }
+ return 1
+}
+
+# @find-an-executable ?-required? name ...
+#
+# Given a list of possible executable names,
+# searches for one of these on the path.
+#
+# Returns the name found, or "" if none found.
+# If the first parameter is '-required', an error is generated
+# if no executable is found.
+#
+proc find-an-executable {args} {
+ set required 0
+ if {[lindex $args 0] eq "-required"} {
+ set args [lrange $args 1 end]
+ incr required
+ }
+ foreach name $args {
+ if {[find-executable $name]} {
+ return $name
+ }
+ }
+ if {$required} {
+ if {[llength $args] == 1} {
+ user-error "failed to find: [join $args]"
+ } else {
+ user-error "failed to find one of: [join $args]"
+ }
+ }
+ return ""
+}
+
+# @configlog msg
+#
+# Writes the given message to the configuration log, 'config.log'.
+#
+proc configlog {msg} {
+ if {![info exists ::autosetup(logfh)]} {
+ set ::autosetup(logfh) [open config.log w]
+ }
+ puts $::autosetup(logfh) $msg
+}
+
+# @msg-checking msg
+#
+# Writes the message with no newline to stdout.
+#
+proc msg-checking {msg} {
+ if {$::autosetup(msg-quiet) == 0} {
+ maybe-show-timestamp
+ puts -nonewline $msg
+ set ::autosetup(msg-checking) 1
+ }
+}
+
+# @msg-result msg
+#
+# Writes the message to stdout.
+#
+proc msg-result {msg} {
+ if {$::autosetup(msg-quiet) == 0} {
+ maybe-show-timestamp
+ puts $msg
+ set ::autosetup(msg-checking) 0
+ show-notices
+ }
+}
+
+# @msg-quiet command ...
+#
+# 'msg-quiet' evaluates it's arguments as a command with output
+# from 'msg-checking' and 'msg-result' suppressed.
+#
+# This is useful if a check needs to run a subcheck which isn't
+# of interest to the user.
+proc msg-quiet {args} {
+ incr ::autosetup(msg-quiet)
+ set rc [uplevel 1 $args]
+ incr ::autosetup(msg-quiet) -1
+ return $rc
+}
+
+# Will be overridden by 'use misc'
+proc error-stacktrace {msg} {
+ return $msg
+}
+
+proc error-location {msg} {
+ return $msg
+}
+
+##################################################################
+#
+# Debugging output
+#
+proc dputs {msg} {
+ if {$::autosetup(debug)} {
+ puts $msg
+ }
+}
+
+##################################################################
+#
+# User and system warnings and errors
+#
+# Usage errors such as wrong command line options
+
+# @user-error msg
+#
+# Indicate incorrect usage to the user, including if required components
+# or features are not found.
+# 'autosetup' exits with a non-zero return code.
+#
+proc user-error {msg} {
+ show-notices
+ puts stderr "Error: $msg"
+ puts stderr "Try: '[file tail $::autosetup(exe)] --help' for options"
+ exit 1
+}
+
+# @user-notice msg
+#
+# Output the given message to stderr.
+#
+proc user-notice {msg} {
+ lappend ::autosetup(notices) $msg
+}
+
+# Incorrect usage in the auto.def file. Identify the location.
+proc autosetup-error {msg} {
+ autosetup-full-error [error-location $msg]
+}
+
+# Like autosetup-error, except $msg is the full error message.
+proc autosetup-full-error {msg} {
+ show-notices
+ puts stderr $msg
+ exit 1
+}
+
+proc show-notices {} {
+ if {$::autosetup(msg-checking)} {
+ puts ""
+ set ::autosetup(msg-checking) 0
+ }
+ flush stdout
+ if {[info exists ::autosetup(notices)]} {
+ puts stderr [join $::autosetup(notices) \n]
+ unset ::autosetup(notices)
+ }
+}
+
+proc maybe-show-timestamp {} {
+ if {$::autosetup(msg-timing) && $::autosetup(msg-checking) == 0} {
+ puts -nonewline [format {[%6.2f] } [expr {([clock millis] - $::autosetup(start)) % 10000 / 1000.0}]]
+ }
+}
+
+# @autosetup-require-version required
+#
+# Checks the current version of 'autosetup' against '$required'.
+# A fatal error is generated if the current version is less than that required.
+#
+proc autosetup-require-version {required} {
+ if {[compare-versions $::autosetup(version) $required] < 0} {
+ user-error "autosetup version $required is required, but this is $::autosetup(version)"
+ }
+}
+
+proc autosetup_version {} {
+ return "autosetup v$::autosetup(version)"
+}
+
+##################################################################
+#
+# Directory/path handling
+#
+
+proc realdir {dir} {
+ set oldpwd [pwd]
+ cd $dir
+ set pwd [pwd]
+ cd $oldpwd
+ return $pwd
+}
+
+# Follow symlinks until we get to something which is not a symlink
+proc realpath {path} {
+ while {1} {
+ if {[catch {
+ set path [file readlink $path]
+ }]} {
+ # Not a link
+ break
+ }
+ }
+ return $path
+}
+
+# Convert absolute path, $path into a path relative
+# to the given directory (or the current dir, if not given).
+#
+proc relative-path {path {pwd {}}} {
+ set diff 0
+ set same 0
+ set newf {}
+ set prefix {}
+ set path [file-normalize $path]
+ if {$pwd eq ""} {
+ set pwd [pwd]
+ } else {
+ set pwd [file-normalize $pwd]
+ }
+
+ if {$path eq $pwd} {
+ return .
+ }
+
+ # Try to make the filename relative to the current dir
+ foreach p [split $pwd /] f [split $path /] {
+ if {$p ne $f} {
+ incr diff
+ } elseif {!$diff} {
+ incr same
+ }
+ if {$diff} {
+ if {$p ne ""} {
+ # Add .. for sibling or parent dir
+ lappend prefix ..
+ }
+ if {$f ne ""} {
+ lappend newf $f
+ }
+ }
+ }
+ if {$same == 1 || [llength $prefix] > 3} {
+ return $path
+ }
+
+ file join [join $prefix /] [join $newf /]
+}
+
+# Add filename as a dependency to rerun autosetup
+# The name will be normalised (converted to a full path)
+#
+proc autosetup_add_dep {filename} {
+ lappend ::autosetup(deps) [file-normalize $filename]
+}
+
+##################################################################
+#
+# Library module support
+#
+
+# @use module ...
+#
+# Load the given library modules.
+# e.g. 'use cc cc-shared'
+#
+# Note that module 'X' is implemented in either 'autosetup/X.tcl'
+# or 'autosetup/X/init.tcl'
+#
+# The latter form is useful for a complex module which requires additional
+# support file. In this form, '$::usedir' is set to the module directory
+# when it is loaded.
+#
+proc use {args} {
+ global autosetup libmodule modsource
+
+ set dirs [list $autosetup(libdir)]
+ if {[info exists autosetup(srcdir)]} {
+ lappend dirs $autosetup(srcdir)/autosetup
+ }
+ foreach m $args {
+ if {[info exists libmodule($m)]} {
+ continue
+ }
+ set libmodule($m) 1
+ if {[info exists modsource(${m}.tcl)]} {
+ automf_load eval $modsource(${m}.tcl)
+ } else {
+ set locs [list ${m}.tcl ${m}/init.tcl]
+ set found 0
+ foreach dir $dirs {
+ foreach loc $locs {
+ set source $dir/$loc
+ if {[file exists $source]} {
+ incr found
+ break
+ }
+ }
+ if {$found} {
+ break
+ }
+ }
+ if {$found} {
+ # For the convenience of the "use" source, point to the directory
+ # it is being loaded from
+ set ::usedir [file dirname $source]
+ automf_load source $source
+ autosetup_add_dep $source
+ } else {
+ autosetup-error "use: No such module: $m"
+ }
+ }
+ }
+}
+
+proc autosetup_load_auto_modules {} {
+ global autosetup modsource
+ # First load any embedded auto modules
+ foreach mod [array names modsource *.auto] {
+ automf_load eval $modsource($mod)
+ }
+ # Now any external auto modules
+ foreach file [glob -nocomplain $autosetup(libdir)/*.auto $autosetup(libdir)/*/*.auto] {
+ automf_load source $file
+ }
+}
+
+# Load module source in the global scope by executing the given command
+proc automf_load {args} {
+ if {[catch [list uplevel #0 $args] msg opts] ni {0 2 3}} {
+ autosetup-full-error [error-dump $msg $opts $::autosetup(debug)]
+ }
+}
+
+# Initial settings
+set autosetup(exe) $::argv0
+set autosetup(istcl) 1
+set autosetup(start) [clock millis]
+set autosetup(installed) 0
+set autosetup(sysinstall) 0
+set autosetup(msg-checking) 0
+set autosetup(msg-quiet) 0
+set autosetup(inittypes) {}
+
+# Embedded modules are inserted below here
+set autosetup(installed) 1
+set autosetup(sysinstall) 0
+# ----- @module asciidoc-formatting.tcl -----
+
+set modsource(asciidoc-formatting.tcl) {
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module which provides text formatting
+# asciidoc format
+
+use formatting
+
+proc para {text} {
+ regsub -all "\[ \t\n\]+" [string trim $text] " "
+}
+proc title {text} {
+ underline [para $text] =
+ nl
+}
+proc p {text} {
+ puts [para $text]
+ nl
+}
+proc code {text} {
+ foreach line [parse_code_block $text] {
+ puts " $line"
+ }
+ nl
+}
+proc codelines {lines} {
+ foreach line $lines {
+ puts " $line"
+ }
+ nl
+}
+proc nl {} {
+ puts ""
+}
+proc underline {text char} {
+ regexp "^(\[ \t\]*)(.*)" $text -> indent words
+ puts $text
+ puts $indent[string repeat $char [string length $words]]
+}
+proc section {text} {
+ underline "[para $text]" -
+ nl
+}
+proc subsection {text} {
+ underline "$text" ~
+ nl
+}
+proc bullet {text} {
+ puts "* [para $text]"
+}
+proc indent {text} {
+ puts " :: "
+ puts [para $text]
+}
+proc defn {first args} {
+ set sep ""
+ if {$first ne ""} {
+ puts "${first}::"
+ } else {
+ puts " :: "
+ }
+ set defn [string trim [join $args \n]]
+ regsub -all "\n\n" $defn "\n ::\n" defn
+ puts $defn
+}
+}
+
+# ----- @module formatting.tcl -----
+
+set modsource(formatting.tcl) {
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module which provides common text formatting
+
+# This is designed for documentation which looks like:
+# code {...}
+# or
+# code {
+# ...
+# ...
+# }
+# In the second case, we need to work out the indenting
+# and strip it from all lines but preserve the remaining indenting.
+# Note that all lines need to be indented with the same initial
+# spaces/tabs.
+#
+# Returns a list of lines with the indenting removed.
+#
+proc parse_code_block {text} {
+ # If the text begins with newline, take the following text,
+ # otherwise just return the original
+ if {![regexp "^\n(.*)" $text -> text]} {
+ return [list [string trim $text]]
+ }
+
+ # And trip spaces off the end
+ set text [string trimright $text]
+
+ set min 100
+ # Examine each line to determine the minimum indent
+ foreach line [split $text \n] {
+ if {$line eq ""} {
+ # Ignore empty lines for the indent calculation
+ continue
+ }
+ regexp "^(\[ \t\]*)" $line -> indent
+ set len [string length $indent]
+ if {$len < $min} {
+ set min $len
+ }
+ }
+
+ # Now make a list of lines with this indent removed
+ set lines {}
+ foreach line [split $text \n] {
+ lappend lines [string range $line $min end]
+ }
+
+ # Return the result
+ return $lines
+}
+}
+
+# ----- @module getopt.tcl -----
+
+set modsource(getopt.tcl) {
+# Copyright (c) 2006 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Simple getopt module
+
+# Parse everything out of the argv list which looks like an option
+# Everything which doesn't look like an option, or is after --, is left unchanged
+# Understands --enable-xxx as a synonym for --xxx to enable the boolean option xxx.
+# Understands --disable-xxx to disable the boolean option xxx.
+#
+# The returned value is a dictionary keyed by option name
+# Each value is a list of {type value} ... where type is "bool" or "str".
+# The value for a boolean option is 0 or 1. The value of a string option is the value given.
+proc getopt {argvname} {
+ upvar $argvname argv
+ set nargv {}
+
+ set opts {}
+
+ for {set i 0} {$i < [llength $argv]} {incr i} {
+ set arg [lindex $argv $i]
+
+ #dputs arg=$arg
+
+ if {$arg eq "--"} {
+ # End of options
+ incr i
+ lappend nargv {*}[lrange $argv $i end]
+ break
+ }
+
+ if {[regexp {^--([^=][^=]+)=(.*)$} $arg -> name value]} {
+ # --name=value
+ dict lappend opts $name [list str $value]
+ } elseif {[regexp {^--(enable-|disable-)?([^=]*)$} $arg -> prefix name]} {
+ if {$prefix in {enable- ""}} {
+ set value 1
+ } else {
+ set value 0
+ }
+ dict lappend opts $name [list bool $value]
+ } else {
+ lappend nargv $arg
+ }
+ }
+
+ #puts "getopt: argv=[join $argv] => [join $nargv]"
+ #array set getopt $opts
+ #parray getopt
+
+ set argv $nargv
+
+ return $opts
+}
+}
+
+# ----- @module help.tcl -----
+
+set modsource(help.tcl) {
+# Copyright (c) 2010 WorkWare Systems http://workware.net.au/
+# All rights reserved
+
+# Module which provides usage, help and the command reference
+
+proc autosetup_help {what} {
+ use_pager
+
+ puts "Usage: [file tail $::autosetup(exe)] \[options\] \[settings\]\n"
+ puts "This is [autosetup_version], a build environment \"autoconfigurator\""
+ puts "See the documentation online at http://msteveb.github.com/autosetup/\n"
+
+ if {$what eq "local"} {
+ if {[file exists $::autosetup(autodef)]} {
+ # This relies on auto.def having a call to 'options'
+ # which will display options and quit
+ source $::autosetup(autodef)
+ } else {
+ options-show
+ }
+ } else {
+ incr ::autosetup(showhelp)
+ if {[catch {use $what}]} {
+ user-error "Unknown module: $what"
+ } else {
+ options-show
+ }
+ }
+ exit 0
+}
+
+proc autosetup_show_license {} {
+ global modsource autosetup
+ use_pager
+
+ if {[info exists modsource(LICENSE)]} {
+ puts $modsource(LICENSE)
+ return
+ }
+ foreach dir [list $autosetup(libdir) $autosetup(srcdir)] {
+ set path [file join $dir LICENSE]
+ if {[file exists $path]} {
+ puts [readfile $path]
+ return
+ }
+ }
+ puts "LICENSE not found"
+}
+
+# If not already paged and stdout is a tty, pipe the output through the pager
+# This is done by reinvoking autosetup with --nopager added
+proc use_pager {} {
+ if {![opt-bool nopager] && [getenv PAGER ""] ne "" && [isatty? stdin] && [isatty? stdout]} {
+ if {[catch {
+ exec [info nameofexecutable] $::argv0 --nopager {*}$::argv |& {*}[getenv PAGER] >@stdout <@stdin 2>@stderr
+ } msg opts] == 1} {
+ if {[dict get $opts -errorcode] eq "NONE"} {
+ # an internal/exec error
+ puts stderr $msg
+ exit 1
+ }
+ }
+ exit 0
+ }
+}
+
+# Outputs the autosetup references in one of several formats
+proc autosetup_reference {{type text}} {
+
+ use_pager
+
+ switch -glob -- $type {
+ wiki {use wiki-formatting}
+ ascii* {use asciidoc-formatting}
+ md - markdown {use markdown-formatting}
+ default {use text-formatting}
+ }
+
+ title "[autosetup_version] -- Command Reference"
+
+ section {Introduction}
+
+ p {
+ See http://msteveb.github.com/autosetup/ for the online documentation for 'autosetup'
+ }
+
+ p {
+ 'autosetup' provides a number of built-in commands which
+ are documented below. These may be used from 'auto.def' to test
+ for features, define variables, create files from templates and
+ other similar actions.
+ }
+
+ automf_command_reference
+
+ exit 0
+}
+
+proc autosetup_output_block {type lines} {
+ if {[llength $lines]} {
+ switch $type {
+ section {
+ section $lines
+ }
+ subsection {
+ subsection $lines
+ }
+ code {
+ codelines $lines
+ }
+ p {
+ p [join $lines]
+ }
+ list {
+ foreach line $lines {
+ bullet $line
+ }
+ nl
+ }
+ }
+ }
+}
+
+# Generate a command reference from inline documentation
+proc automf_command_reference {} {
+ lappend files $::autosetup(prog)
+ lappend files {*}[lsort [glob -nocomplain $::autosetup(libdir)/*.tcl]]
+
+ # We want to process all non-module files before module files
+ # and then modules in alphabetical order.
+ # So examine all files and extract docs into doc($modulename) and doc(_core_)
+ #
+ # Each entry is a list of {type data} where $type is one of: section, subsection, code, list, p
+ # and $data is a string for section, subsection or a list of text lines for other types.
+
+ # XXX: Should commands be in alphabetical order too? Currently they are in file order.
+
+ set doc(_core_) {}
+ lappend doc(_core_) [list section "Core Commands"]
+
+ foreach file $files {
+ set modulename [file rootname [file tail $file]]
+ set current _core_
+ set f [open $file]
+ while {![eof $f]} {
+ set line [gets $f]
+
+ # Find embedded module names
+ if {[regexp {^#.*@module ([^ ]*)} $line -> modulename]} {
+ continue
+ }
+
+ # Find lines starting with "# @*" and continuing through the remaining comment lines
+ if {![regexp {^# @(.*)} $line -> cmd]} {
+ continue
+ }
+
+ # Synopsis or command?
+ if {$cmd eq "synopsis:"} {
+ set current $modulename
+ lappend doc($current) [list section "Module: $modulename"]
+ } else {
+ lappend doc($current) [list subsection $cmd]
+ }
+
+ set lines {}
+ set type p
+
+ # Now the description
+ while {![eof $f]} {
+ set line [gets $f]
+
+ if {![regexp {^#(#)? ?(.*)} $line -> hash cmd]} {
+ break
+ }
+ if {$hash eq "#"} {
+ set t code
+ } elseif {[regexp {^- (.*)} $cmd -> cmd]} {
+ set t list
+ } else {
+ set t p
+ }
+
+ #puts "hash=$hash, oldhash=$oldhash, lines=[llength $lines], cmd=$cmd"
+
+ if {$t ne $type || $cmd eq ""} {
+ # Finish the current block
+ lappend doc($current) [list $type $lines]
+ set lines {}
+ set type $t
+ }
+ if {$cmd ne ""} {
+ lappend lines $cmd
+ }
+ }
+
+ lappend doc($current) [list $type $lines]
+ }
+ close $f
+ }
+
+ # Now format and output the results
+
+ # _core_ will sort first
+ foreach module [lsort [array names doc]] {
+ foreach item $doc($module) {
+ autosetup_output_block {*}$item
+ }
+ }
+}
+}
+
+# ----- @module init.tcl -----
+
+set modsource(init.tcl) {
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module to help create auto.def and configure
+
+proc autosetup_init {type} {
+ set help 0
+ if {$type in {? help}} {
+ incr help
+ } elseif {![dict exists $::autosetup(inittypes) $type]} {
+ puts "Unknown type, --init=$type"
+ incr help
+ }
+ if {$help} {
+ puts "Use one of the following types (e.g. --init=make)\n"
+ foreach type [lsort [dict keys $::autosetup(inittypes)]] {
+ lassign [dict get $::autosetup(inittypes) $type] desc
+ # XXX: Use the options-show code to wrap the description
+ puts [format "%-10s %s" $type $desc]
+ }
+ return
+ }
+ lassign [dict get $::autosetup(inittypes) $type] desc script
+
+ puts "Initialising $type: $desc\n"
+
+ # All initialisations happens in the top level srcdir
+ cd $::autosetup(srcdir)
+
+ uplevel #0 $script
+}
+
+proc autosetup_add_init_type {type desc script} {
+ dict set ::autosetup(inittypes) $type [list $desc $script]
+}
+
+# This is for in creating build-system init scripts
+#
+# If the file doesn't exist, create it containing $contents
+# If the file does exist, only overwrite if --force is specified.
+#
+proc autosetup_check_create {filename contents} {
+ if {[file exists $filename]} {
+ if {!$::autosetup(force)} {
+ puts "I see $filename already exists."
+ return
+ } else {
+ puts "I will overwrite the existing $filename because you used --force."
+ }
+ } else {
+ puts "I don't see $filename, so I will create it."
+ }
+ writefile $filename $contents
+}
+}
+
+# ----- @module install.tcl -----
+
+set modsource(install.tcl) {
+# Copyright (c) 2006-2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module which can install autosetup
+
+# autosetup(installed)=1 means that autosetup is not running from source
+# autosetup(sysinstall)=1 means that autosetup is running from a sysinstall version
+# shared=1 means that we are trying to do a sysinstall. This is only possible from the development source.
+
+proc autosetup_install {dir {shared 0}} {
+ global autosetup
+ if {$shared} {
+ if {$autosetup(installed) || $autosetup(sysinstall)} {
+ user-error "Can only --sysinstall from development sources"
+ }
+ } elseif {$autosetup(installed) && !$autosetup(sysinstall)} {
+ user-error "Can't --install from project install"
+ }
+
+ if {$autosetup(sysinstall)} {
+ # This is the sysinstall version, so install just uses references
+ cd $dir
+
+ puts "[autosetup_version] creating configure to use system-installed autosetup"
+ autosetup_create_configure 1
+ puts "Creating autosetup/README.autosetup"
+ file mkdir autosetup
+ autosetup_install_readme autosetup/README.autosetup 1
+ return
+ }
+
+ if {[catch {
+ if {$shared} {
+ set target $dir/bin/autosetup
+ set installedas $target
+ } else {
+ if {$dir eq "."} {
+ set installedas autosetup
+ } else {
+ set installedas $dir/autosetup
+ }
+ cd $dir
+ file mkdir autosetup
+ set target autosetup/autosetup
+ }
+ set targetdir [file dirname $target]
+ file mkdir $targetdir
+
+ set f [open $target w]
+
+ set publicmodules {}
+
+ # First the main script, but only up until "CUT HERE"
+ set in [open $autosetup(dir)/autosetup]
+ while {[gets $in buf] >= 0} {
+ if {$buf ne "##-- CUT HERE --##"} {
+ puts $f $buf
+ continue
+ }
+
+ # Insert the static modules here
+ # i.e. those which don't contain @synopsis:
+ # All modules are inserted if $shared is set
+ puts $f "set autosetup(installed) 1"
+ puts $f "set autosetup(sysinstall) $shared"
+ foreach file [lsort [glob $autosetup(libdir)/*.{tcl,auto}]] {
+ set modname [file tail $file]
+ set ext [file ext $modname]
+ set buf [readfile $file]
+ if {!$shared} {
+ if {$ext eq ".auto" || [string match "*\n# @synopsis:*" $buf]} {
+ lappend publicmodules $file
+ continue
+ }
+ }
+ dputs "install: importing lib/[file tail $file]"
+ puts $f "# ----- @module $modname -----"
+ puts $f "\nset modsource($modname) \{"
+ puts $f $buf
+ puts $f "\}\n"
+ }
+ if {$shared} {
+ foreach {srcname destname} [list $autosetup(libdir)/README.autosetup-lib README.autosetup \
+ $autosetup(srcdir)/LICENSE LICENSE] {
+ dputs "install: importing $srcname as $destname"
+ puts $f "\nset modsource($destname) \\\n[list [readfile $srcname]\n]\n"
+ }
+ }
+ }
+ close $in
+ close $f
+ catch {exec chmod 755 $target}
+
+ set installfiles {autosetup-config.guess autosetup-config.sub autosetup-test-tclsh}
+ set removefiles {}
+
+ if {!$shared} {
+ autosetup_install_readme $targetdir/README.autosetup 0
+
+ # Install public modules
+ foreach file $publicmodules {
+ set tail [file tail $file]
+ autosetup_install_file $file $targetdir/$tail
+ }
+ lappend installfiles jimsh0.c autosetup-find-tclsh LICENSE
+ lappend removefiles config.guess config.sub test-tclsh find-tclsh
+ } else {
+ lappend installfiles {sys-find-tclsh autosetup-find-tclsh}
+ }
+
+ # Install support files
+ foreach fileinfo $installfiles {
+ if {[llength $fileinfo] == 2} {
+ lassign $fileinfo source dest
+ } else {
+ lassign $fileinfo source
+ set dest $source
+ }
+ autosetup_install_file $autosetup(dir)/$source $targetdir/$dest
+ }
+
+ # Remove obsolete files
+ foreach file $removefiles {
+ if {[file exists $targetdir/$file]} {
+ file delete $targetdir/$file
+ }
+ }
+ } error]} {
+ user-error "Failed to install autosetup: $error"
+ }
+ if {$shared} {
+ set type "system"
+ } else {
+ set type "local"
+ }
+ puts "Installed $type [autosetup_version] to $installedas"
+
+ if {!$shared} {
+ # Now create 'configure' if necessary
+ autosetup_create_configure 0
+ }
+}
+
+proc autosetup_create_configure {shared} {
+ if {[file exists configure]} {
+ if {!$::autosetup(force)} {
+ # Could this be an autosetup configure?
+ if {![string match "*\nWRAPPER=*" [readfile configure]]} {
+ puts "I see configure, but not created by autosetup, so I won't overwrite it."
+ puts "Remove it or use --force to overwrite."
+ return
+ }
+ } else {
+ puts "I will overwrite the existing configure because you used --force."
+ }
+ } else {
+ puts "I don't see configure, so I will create it."
+ }
+ if {$shared} {
+ writefile configure \
+{#!/bin/sh
+WRAPPER="$0"; export WRAPPER; "autosetup" "$@"
+}
+ } else {
+ writefile configure \
+{#!/bin/sh
+dir="`dirname "$0"`/autosetup"
+WRAPPER="$0"; export WRAPPER; exec "`"$dir/autosetup-find-tclsh"`" "$dir/autosetup" "$@"
+}
+ }
+ catch {exec chmod 755 configure}
+}
+
+# Append the contents of $file to filehandle $f
+proc autosetup_install_append {f file} {
+ dputs "install: include $file"
+ set in [open $file]
+ puts $f [read $in]
+ close $in
+}
+
+proc autosetup_install_file {source target} {
+ dputs "install: $source => $target"
+ if {![file exists $source]} {
+ error "Missing installation file '$source'"
+ }
+ writefile $target [readfile $source]\n
+ # If possible, copy the file mode
+ file stat $source stat
+ set mode [format %o [expr {$stat(mode) & 0x1ff}]]
+ catch {exec chmod $mode $target}
+}
+
+proc autosetup_install_readme {target sysinstall} {
+ set readme "README.autosetup created by [autosetup_version]\n\n"
+ if {$sysinstall} {
+ append readme \
+{This is the autosetup directory for a system install of autosetup.
+Loadable modules can be added here.
+}
+ } else {
+ append readme \
+{This is the autosetup directory for a local install of autosetup.
+It contains autosetup, support files and loadable modules.
+}
+}
+
+ append readme {
+*.tcl files in this directory are optional modules which
+can be loaded with the 'use' directive.
+
+*.auto files in this directory are auto-loaded.
+
+For more information, see http://msteveb.github.com/autosetup/
+}
+ dputs "install: autosetup/README.autosetup"
+ writefile $target $readme
+}
+}
+
+# ----- @module markdown-formatting.tcl -----
+
+set modsource(markdown-formatting.tcl) {
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module which provides text formatting
+# markdown format (kramdown syntax)
+
+use formatting
+
+proc para {text} {
+ regsub -all "\[ \t\n\]+" [string trim $text] " " text
+ regsub -all {([^a-zA-Z])'([^']*)'} $text {\1**`\2`**} text
+ regsub -all {^'([^']*)'} $text {**`\1`**} text
+ regsub -all {(http[^ \t\n]*)} $text {[\1](\1)} text
+ return $text
+}
+proc title {text} {
+ underline [para $text] =
+ nl
+}
+proc p {text} {
+ puts [para $text]
+ nl
+}
+proc codelines {lines} {
+ puts "~~~~~~~~~~~~"
+ foreach line $lines {
+ puts $line
+ }
+ puts "~~~~~~~~~~~~"
+ nl
+}
+proc code {text} {
+ puts "~~~~~~~~~~~~"
+ foreach line [parse_code_block $text] {
+ puts $line
+ }
+ puts "~~~~~~~~~~~~"
+ nl
+}
+proc nl {} {
+ puts ""
+}
+proc underline {text char} {
+ regexp "^(\[ \t\]*)(.*)" $text -> indent words
+ puts $text
+ puts $indent[string repeat $char [string length $words]]
+}
+proc section {text} {
+ underline "[para $text]" -
+ nl
+}
+proc subsection {text} {
+ puts "### `$text`"
+ nl
+}
+proc bullet {text} {
+ puts "* [para $text]"
+}
+proc defn {first args} {
+ puts "^"
+ set defn [string trim [join $args \n]]
+ if {$first ne ""} {
+ puts "**${first}**"
+ puts -nonewline ": "
+ regsub -all "\n\n" $defn "\n: " defn
+ }
+ puts "$defn"
+}
+}
+
+# ----- @module misc.tcl -----
+
+set modsource(misc.tcl) {
+# Copyright (c) 2007-2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module containing misc procs useful to modules
+# Largely for platform compatibility
+
+set autosetup(istcl) [info exists ::tcl_library]
+set autosetup(iswin) [string equal windows $tcl_platform(platform)]
+
+if {$autosetup(iswin)} {
+ # mingw/windows separates $PATH with semicolons
+ # and doesn't have an executable bit
+ proc split-path {} {
+ split [getenv PATH .] {;}
+ }
+ proc file-isexec {exec} {
+ # Basic test for windows. We ignore .bat
+ if {[file isfile $exec] || [file isfile $exec.exe]} {
+ return 1
+ }
+ return 0
+ }
+} else {
+ # unix separates $PATH with colons and has and executable bit
+ proc split-path {} {
+ split [getenv PATH .] :
+ }
+ proc file-isexec {exec} {
+ file executable $exec
+ }
+}
+
+# Assume that exec can return stdout and stderr
+proc exec-with-stderr {args} {
+ exec {*}$args 2>@1
+}
+
+if {$autosetup(istcl)} {
+ # Tcl doesn't have the env command
+ proc getenv {name args} {
+ if {[info exists ::env($name)]} {
+ return $::env($name)
+ }
+ if {[llength $args]} {
+ return [lindex $args 0]
+ }
+ return -code error "environment variable \"$name\" does not exist"
+ }
+ proc isatty? {channel} {
+ dict exists [fconfigure $channel] -xchar
+ }
+} else {
+ if {$autosetup(iswin)} {
+ # On Windows, backslash convert all environment variables
+ # (Assume that Tcl does this for us)
+ proc getenv {name args} {
+ string map {\\ /} [env $name {*}$args]
+ }
+ } else {
+ # Jim on unix is simple
+ alias getenv env
+ }
+ proc isatty? {channel} {
+ set tty 0
+ catch {
+ # isatty is a recent addition to Jim Tcl
+ set tty [$channel isatty]
+ }
+ return $tty
+ }
+}
+
+# In case 'file normalize' doesn't exist
+#
+proc file-normalize {path} {
+ if {[catch {file normalize $path} result]} {
+ if {$path eq ""} {
+ return ""
+ }
+ set oldpwd [pwd]
+ if {[file isdir $path]} {
+ cd $path
+ set result [pwd]
+ } else {
+ cd [file dirname $path]
+ set result [file join [pwd] [file tail $path]]
+ }
+ cd $oldpwd
+ }
+ return $result
+}
+
+# If everything is working properly, the only errors which occur
+# should be generated in user code (e.g. auto.def).
+# By default, we only want to show the error location in user code.
+# We use [info frame] to achieve this, but it works differently on Tcl and Jim.
+#
+# This is designed to be called for incorrect usage in auto.def, via autosetup-error
+#
+proc error-location {msg} {
+ if {$::autosetup(debug)} {
+ return -code error $msg
+ }
+ # Search back through the stack trace for the first error in a .def file
+ for {set i 1} {$i < [info level]} {incr i} {
+ if {$::autosetup(istcl)} {
+ array set info [info frame -$i]
+ } else {
+ lassign [info frame -$i] info(caller) info(file) info(line)
+ }
+ if {[string match *.def $info(file)]} {
+ return "[relative-path $info(file)]:$info(line): Error: $msg"
+ }
+ #puts "Skipping $info(file):$info(line)"
+ }
+ return $msg
+}
+
+# If everything is working properly, the only errors which occur
+# should be generated in user code (e.g. auto.def).
+# By default, we only want to show the error location in user code.
+# We use [info frame] to achieve this, but it works differently on Tcl and Jim.
+#
+# This is designed to be called for incorrect usage in auto.def, via autosetup-error
+#
+proc error-stacktrace {msg} {
+ if {$::autosetup(debug)} {
+ return -code error $msg
+ }
+ # Search back through the stack trace for the first error in a .def file
+ for {set i 1} {$i < [info level]} {incr i} {
+ if {$::autosetup(istcl)} {
+ array set info [info frame -$i]
+ } else {
+ lassign [info frame -$i] info(caller) info(file) info(line)
+ }
+ if {[string match *.def $info(file)]} {
+ return "[relative-path $info(file)]:$info(line): Error: $msg"
+ }
+ #puts "Skipping $info(file):$info(line)"
+ }
+ return $msg
+}
+
+# Given the return from [catch {...} msg opts], returns an appropriate
+# error message. A nice one for Jim and a less-nice one for Tcl.
+# If 'fulltrace' is set, a full stack trace is provided.
+# Otherwise a simple message is provided.
+#
+# This is designed for developer errors, e.g. in module code or auto.def code
+#
+#
+proc error-dump {msg opts fulltrace} {
+ if {$::autosetup(istcl)} {
+ if {$fulltrace} {
+ return "Error: [dict get $opts -errorinfo]"
+ } else {
+ return "Error: $msg"
+ }
+ } else {
+ lassign $opts(-errorinfo) p f l
+ if {$f ne ""} {
+ set result "$f:$l: Error: "
+ }
+ append result "$msg\n"
+ if {$fulltrace} {
+ append result [stackdump $opts(-errorinfo)]
+ }
+
+ # Remove the trailing newline
+ string trim $result
+ }
+}
+}
+
+# ----- @module text-formatting.tcl -----
+
+set modsource(text-formatting.tcl) {
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module which provides text formatting
+
+use formatting
+
+proc wordwrap {text length {firstprefix ""} {nextprefix ""}} {
+ set len 0
+ set space $firstprefix
+
+ foreach word [split $text] {
+ set word [string trim $word]
+ if {$word eq ""} {
+ continue
+ }
+ if {[info exists partial]} {
+ append partial " " $word
+ if {[string first $quote $word] < 0} {
+ # Haven't found end of quoted word
+ continue
+ }
+ # Finished quoted word
+ set word $partial
+ unset partial
+ unset quote
+ } else {
+ set quote [string index $word 0]
+ if {$quote in {' *}} {
+ if {[string first $quote $word 1] < 0} {
+ # Haven't found end of quoted word
+ # Not a whole word.
+ set first [string index $word 0]
+ # Start of quoted word
+ set partial $word
+ continue
+ }
+ }
+ }
+
+ if {$len && [string length $space$word] + $len >= $length} {
+ puts ""
+ set len 0
+ set space $nextprefix
+ }
+ incr len [string length $space$word]
+
+ # Use man-page conventions for highlighting 'quoted' and *quoted*
+ # single words.
+ # Use x^Hx for *bold* and _^Hx for 'underline'.
+ #
+ # less and more will both understand this.
+ # Pipe through 'col -b' to remove them.
+ if {[regexp {^'(.*)'(.*)} $word -> quoted after]} {
+ set quoted [string map {~ " "} $quoted]
+ regsub -all . $quoted "&\b&" quoted
+ set word $quoted$after
+ } elseif {[regexp {^[*](.*)[*](.*)} $word -> quoted after]} {
+ set quoted [string map {~ " "} $quoted]
+ regsub -all . $quoted "_\b&" quoted
+ set word $quoted$after
+ }
+ puts -nonewline $space$word
+ set space " "
+ }
+ if {[info exists partial]} {
+ # Missing end of quote
+ puts -nonewline $space$partial
+ }
+ if {$len} {
+ puts ""
+ }
+}
+proc title {text} {
+ underline [string trim $text] =
+ nl
+}
+proc p {text} {
+ wordwrap $text 80
+ nl
+}
+proc codelines {lines} {
+ foreach line $lines {
+ puts " $line"
+ }
+ nl
+}
+proc nl {} {
+ puts ""
+}
+proc underline {text char} {
+ regexp "^(\[ \t\]*)(.*)" $text -> indent words
+ puts $text
+ puts $indent[string repeat $char [string length $words]]
+}
+proc section {text} {
+ underline "[string trim $text]" -
+ nl
+}
+proc subsection {text} {
+ underline "$text" ~
+ nl
+}
+proc bullet {text} {
+ wordwrap $text 76 " * " " "
+}
+proc indent {text} {
+ wordwrap $text 76 " " " "
+}
+proc defn {first args} {
+ if {$first ne ""} {
+ underline " $first" ~
+ }
+ foreach p $args {
+ if {$p ne ""} {
+ indent $p
+ }
+ }
+}
+}
+
+# ----- @module util.tcl -----
+
+set modsource(util.tcl) {
+# Copyright (c) 2012 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module which contains miscellaneous utility functions
+
+# @compare-versions version1 version2
+#
+# Versions are of the form 'a.b.c' (may be any number of numeric components)
+#
+# Compares the two versions and returns:
+## -1 if v1 < v2
+## 0 if v1 == v2
+## 1 if v1 > v2
+#
+# If one version has fewer components than the other, 0 is substituted to the right. e.g.
+## 0.2 < 0.3
+## 0.2.5 > 0.2
+## 1.1 == 1.1.0
+#
+proc compare-versions {v1 v2} {
+ foreach c1 [split $v1 .] c2 [split $v2 .] {
+ if {$c1 eq ""} {
+ set c1 0
+ }
+ if {$c2 eq ""} {
+ set c2 0
+ }
+ if {$c1 < $c2} {
+ return -1
+ }
+ if {$c1 > $c2} {
+ return 1
+ }
+ }
+ return 0
+}
+
+# @suffix suf list
+#
+# Takes a list and returns a new list with '$suf' appended
+# to each element
+#
+## suffix .c {a b c} => {a.c b.c c.c}
+#
+proc suffix {suf list} {
+ set result {}
+ foreach p $list {
+ lappend result $p$suf
+ }
+ return $result
+}
+
+# @prefix pre list
+#
+# Takes a list and returns a new list with '$pre' prepended
+# to each element
+#
+## prefix jim- {a.c b.c} => {jim-a.c jim-b.c}
+#
+proc prefix {pre list} {
+ set result {}
+ foreach p $list {
+ lappend result $pre$p
+ }
+ return $result
+}
+
+# @lpop list
+#
+# Removes the last entry from the given list and returns it.
+proc lpop {listname} {
+ upvar $listname list
+ set val [lindex $list end]
+ set list [lrange $list 0 end-1]
+ return $val
+}
+}
+
+# ----- @module wiki-formatting.tcl -----
+
+set modsource(wiki-formatting.tcl) {
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Module which provides text formatting
+# wiki.tcl.tk format output
+
+use formatting
+
+proc joinlines {text} {
+ set lines {}
+ foreach l [split [string trim $text] \n] {
+ lappend lines [string trim $l]
+ }
+ join $lines
+}
+proc p {text} {
+ puts [joinlines $text]
+ puts ""
+}
+proc title {text} {
+ puts "*** [joinlines $text] ***"
+ puts ""
+}
+proc codelines {lines} {
+ puts "======"
+ foreach line $lines {
+ puts " $line"
+ }
+ puts "======"
+}
+proc code {text} {
+ puts "======"
+ foreach line [parse_code_block $text] {
+ puts " $line"
+ }
+ puts "======"
+}
+proc nl {} {
+}
+proc section {text} {
+ puts "'''$text'''"
+ puts ""
+}
+proc subsection {text} {
+ puts "''$text''"
+ puts ""
+}
+proc bullet {text} {
+ puts " * [joinlines $text]"
+}
+proc indent {text} {
+ puts " : [joinlines $text]"
+}
+proc defn {first args} {
+ if {$first ne ""} {
+ indent '''$first'''
+ }
+
+ foreach p $args {
+ p $p
+ }
+}
+}
+
+
+##################################################################
+#
+# Entry/Exit
+#
+if {$autosetup(debug)} {
+ main $argv
+}
+if {[catch {main $argv} msg opts] == 1} {
+ show-notices
+ autosetup-full-error [error-dump $msg $opts $autosetup(debug)]
+ if {!$autosetup(debug)} {
+ puts stderr "Try: '[file tail $autosetup(exe)] --debug' for a full stack trace"
+ }
+ exit 1
+}
ADDED autosetup/autosetup-config.guess
Index: autosetup/autosetup-config.guess
==================================================================
--- autosetup/autosetup-config.guess
+++ autosetup/autosetup-config.guess
@@ -0,0 +1,1476 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+# Copyright 1992-2018 Free Software Foundation, Inc.
+
+timestamp='2018-03-08'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, see .
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that
+# program. This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+#
+# Originally written by Per Bothner; maintained since 2000 by Ben Elliston.
+#
+# You can get the latest version of this script from:
+# https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess
+#
+# Please send patches to .
+
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Options:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to ."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright 1992-2018 Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help" >&2
+ exit 1 ;;
+ * )
+ break ;;
+ esac
+done
+
+if test $# != 0; then
+ echo "$me: too many arguments$help" >&2
+ exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,) echo "int x;" > "$dummy.c" ;
+ for c in cc gcc c89 c99 ; do
+ if ($c -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then
+ CC_FOR_BUILD="$c"; break ;
+ fi ;
+ done ;
+ if test x"$CC_FOR_BUILD" = x ; then
+ CC_FOR_BUILD=no_compiler_found ;
+ fi
+ ;;
+ ,,*) CC_FOR_BUILD=$CC ;;
+ ,*,*) CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi@noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+ PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+case "$UNAME_SYSTEM" in
+Linux|GNU|GNU/*)
+ # If the system lacks a compiler, then just pick glibc.
+ # We could probably try harder.
+ LIBC=gnu
+
+ eval "$set_cc_for_build"
+ cat <<-EOF > "$dummy.c"
+ #include
+ #if defined(__UCLIBC__)
+ LIBC=uclibc
+ #elif defined(__dietlibc__)
+ LIBC=dietlibc
+ #else
+ LIBC=gnu
+ #endif
+ EOF
+ eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`"
+
+ # If ldd exists, use it to detect musl libc.
+ if command -v ldd >/dev/null && \
+ ldd --version 2>&1 | grep -q ^musl
+ then
+ LIBC=musl
+ fi
+ ;;
+esac
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "$UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION" in
+ *:NetBSD:*:*)
+ # NetBSD (nbsd) targets should (where applicable) match one or
+ # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
+ # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
+ # switched to ELF, *-*-netbsd* would select the old
+ # object file format. This provides both forward
+ # compatibility and a consistent mechanism for selecting the
+ # object file format.
+ #
+ # Note: NetBSD doesn't particularly care about the vendor
+ # portion of the name. We always set it to "unknown".
+ sysctl="sysctl -n hw.machine_arch"
+ UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \
+ "/sbin/$sysctl" 2>/dev/null || \
+ "/usr/sbin/$sysctl" 2>/dev/null || \
+ echo unknown)`
+ case "$UNAME_MACHINE_ARCH" in
+ armeb) machine=armeb-unknown ;;
+ arm*) machine=arm-unknown ;;
+ sh3el) machine=shl-unknown ;;
+ sh3eb) machine=sh-unknown ;;
+ sh5el) machine=sh5le-unknown ;;
+ earmv*)
+ arch=`echo "$UNAME_MACHINE_ARCH" | sed -e 's,^e\(armv[0-9]\).*$,\1,'`
+ endian=`echo "$UNAME_MACHINE_ARCH" | sed -ne 's,^.*\(eb\)$,\1,p'`
+ machine="${arch}${endian}"-unknown
+ ;;
+ *) machine="$UNAME_MACHINE_ARCH"-unknown ;;
+ esac
+ # The Operating System including object format, if it has switched
+ # to ELF recently (or will in the future) and ABI.
+ case "$UNAME_MACHINE_ARCH" in
+ earm*)
+ os=netbsdelf
+ ;;
+ arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+ eval "$set_cc_for_build"
+ if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ELF__
+ then
+ # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+ # Return netbsd for either. FIX?
+ os=netbsd
+ else
+ os=netbsdelf
+ fi
+ ;;
+ *)
+ os=netbsd
+ ;;
+ esac
+ # Determine ABI tags.
+ case "$UNAME_MACHINE_ARCH" in
+ earm*)
+ expr='s/^earmv[0-9]/-eabi/;s/eb$//'
+ abi=`echo "$UNAME_MACHINE_ARCH" | sed -e "$expr"`
+ ;;
+ esac
+ # The OS release
+ # Debian GNU/NetBSD machines have a different userland, and
+ # thus, need a distinct triplet. However, they do not need
+ # kernel version information, so it can be replaced with a
+ # suitable tag, in the style of linux-gnu.
+ case "$UNAME_VERSION" in
+ Debian*)
+ release='-gnu'
+ ;;
+ *)
+ release=`echo "$UNAME_RELEASE" | sed -e 's/[-_].*//' | cut -d. -f1,2`
+ ;;
+ esac
+ # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+ # contains redundant information, the shorter form:
+ # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+ echo "$machine-${os}${release}${abi}"
+ exit ;;
+ *:Bitrig:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
+ echo "$UNAME_MACHINE_ARCH"-unknown-bitrig"$UNAME_RELEASE"
+ exit ;;
+ *:OpenBSD:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+ echo "$UNAME_MACHINE_ARCH"-unknown-openbsd"$UNAME_RELEASE"
+ exit ;;
+ *:LibertyBSD:*:*)
+ UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'`
+ echo "$UNAME_MACHINE_ARCH"-unknown-libertybsd"$UNAME_RELEASE"
+ exit ;;
+ *:MidnightBSD:*:*)
+ echo "$UNAME_MACHINE"-unknown-midnightbsd"$UNAME_RELEASE"
+ exit ;;
+ *:ekkoBSD:*:*)
+ echo "$UNAME_MACHINE"-unknown-ekkobsd"$UNAME_RELEASE"
+ exit ;;
+ *:SolidBSD:*:*)
+ echo "$UNAME_MACHINE"-unknown-solidbsd"$UNAME_RELEASE"
+ exit ;;
+ macppc:MirBSD:*:*)
+ echo powerpc-unknown-mirbsd"$UNAME_RELEASE"
+ exit ;;
+ *:MirBSD:*:*)
+ echo "$UNAME_MACHINE"-unknown-mirbsd"$UNAME_RELEASE"
+ exit ;;
+ *:Sortix:*:*)
+ echo "$UNAME_MACHINE"-unknown-sortix
+ exit ;;
+ *:Redox:*:*)
+ echo "$UNAME_MACHINE"-unknown-redox
+ exit ;;
+ mips:OSF1:*.*)
+ echo mips-dec-osf1
+ exit ;;
+ alpha:OSF1:*:*)
+ case $UNAME_RELEASE in
+ *4.0)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+ ;;
+ *5.*)
+ UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+ ;;
+ esac
+ # According to Compaq, /usr/sbin/psrinfo has been available on
+ # OSF/1 and Tru64 systems produced since 1995. I hope that
+ # covers most systems running today. This code pipes the CPU
+ # types through head -n 1, so we only detect the type of CPU 0.
+ ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+ case "$ALPHA_CPU_TYPE" in
+ "EV4 (21064)")
+ UNAME_MACHINE=alpha ;;
+ "EV4.5 (21064)")
+ UNAME_MACHINE=alpha ;;
+ "LCA4 (21066/21068)")
+ UNAME_MACHINE=alpha ;;
+ "EV5 (21164)")
+ UNAME_MACHINE=alphaev5 ;;
+ "EV5.6 (21164A)")
+ UNAME_MACHINE=alphaev56 ;;
+ "EV5.6 (21164PC)")
+ UNAME_MACHINE=alphapca56 ;;
+ "EV5.7 (21164PC)")
+ UNAME_MACHINE=alphapca57 ;;
+ "EV6 (21264)")
+ UNAME_MACHINE=alphaev6 ;;
+ "EV6.7 (21264A)")
+ UNAME_MACHINE=alphaev67 ;;
+ "EV6.8CB (21264C)")
+ UNAME_MACHINE=alphaev68 ;;
+ "EV6.8AL (21264B)")
+ UNAME_MACHINE=alphaev68 ;;
+ "EV6.8CX (21264D)")
+ UNAME_MACHINE=alphaev68 ;;
+ "EV6.9A (21264/EV69A)")
+ UNAME_MACHINE=alphaev69 ;;
+ "EV7 (21364)")
+ UNAME_MACHINE=alphaev7 ;;
+ "EV7.9 (21364A)")
+ UNAME_MACHINE=alphaev79 ;;
+ esac
+ # A Pn.n version is a patched version.
+ # A Vn.n version is a released version.
+ # A Tn.n version is a released field test version.
+ # A Xn.n version is an unreleased experimental baselevel.
+ # 1.2 uses "1.2" for uname -r.
+ echo "$UNAME_MACHINE"-dec-osf"`echo "$UNAME_RELEASE" | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`"
+ # Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+ exitcode=$?
+ trap '' 0
+ exit $exitcode ;;
+ Amiga*:UNIX_System_V:4.0:*)
+ echo m68k-unknown-sysv4
+ exit ;;
+ *:[Aa]miga[Oo][Ss]:*:*)
+ echo "$UNAME_MACHINE"-unknown-amigaos
+ exit ;;
+ *:[Mm]orph[Oo][Ss]:*:*)
+ echo "$UNAME_MACHINE"-unknown-morphos
+ exit ;;
+ *:OS/390:*:*)
+ echo i370-ibm-openedition
+ exit ;;
+ *:z/VM:*:*)
+ echo s390-ibm-zvmoe
+ exit ;;
+ *:OS400:*:*)
+ echo powerpc-ibm-os400
+ exit ;;
+ arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+ echo arm-acorn-riscix"$UNAME_RELEASE"
+ exit ;;
+ arm*:riscos:*:*|arm*:RISCOS:*:*)
+ echo arm-unknown-riscos
+ exit ;;
+ SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+ echo hppa1.1-hitachi-hiuxmpp
+ exit ;;
+ Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+ # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+ if test "`(/bin/universe) 2>/dev/null`" = att ; then
+ echo pyramid-pyramid-sysv3
+ else
+ echo pyramid-pyramid-bsd
+ fi
+ exit ;;
+ NILE*:*:*:dcosx)
+ echo pyramid-pyramid-svr4
+ exit ;;
+ DRS?6000:unix:4.0:6*)
+ echo sparc-icl-nx6
+ exit ;;
+ DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+ case `/usr/bin/uname -p` in
+ sparc) echo sparc-icl-nx7; exit ;;
+ esac ;;
+ s390x:SunOS:*:*)
+ echo "$UNAME_MACHINE"-ibm-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`"
+ exit ;;
+ sun4H:SunOS:5.*:*)
+ echo sparc-hal-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`"
+ exit ;;
+ sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+ echo sparc-sun-solaris2"`echo "$UNAME_RELEASE" | sed -e 's/[^.]*//'`"
+ exit ;;
+ i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+ echo i386-pc-auroraux"$UNAME_RELEASE"
+ exit ;;
+ i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+ eval "$set_cc_for_build"
+ SUN_ARCH=i386
+ # If there is a compiler, see if it is configured for 64-bit objects.
+ # Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+ # This test works for both compilers.
+ if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
+ if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
+ grep IS_64BIT_ARCH >/dev/null
+ then
+ SUN_ARCH=x86_64
+ fi
+ fi
+ echo "$SUN_ARCH"-pc-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`"
+ exit ;;
+ sun4*:SunOS:6*:*)
+ # According to config.sub, this is the proper way to canonicalize
+ # SunOS6. Hard to guess exactly what SunOS6 will be like, but
+ # it's likely to be more like Solaris than SunOS4.
+ echo sparc-sun-solaris3"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`"
+ exit ;;
+ sun4*:SunOS:*:*)
+ case "`/usr/bin/arch -k`" in
+ Series*|S4*)
+ UNAME_RELEASE=`uname -v`
+ ;;
+ esac
+ # Japanese Language versions have a version number like `4.1.3-JL'.
+ echo sparc-sun-sunos"`echo "$UNAME_RELEASE"|sed -e 's/-/_/'`"
+ exit ;;
+ sun3*:SunOS:*:*)
+ echo m68k-sun-sunos"$UNAME_RELEASE"
+ exit ;;
+ sun*:*:4.2BSD:*)
+ UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+ test "x$UNAME_RELEASE" = x && UNAME_RELEASE=3
+ case "`/bin/arch`" in
+ sun3)
+ echo m68k-sun-sunos"$UNAME_RELEASE"
+ ;;
+ sun4)
+ echo sparc-sun-sunos"$UNAME_RELEASE"
+ ;;
+ esac
+ exit ;;
+ aushp:SunOS:*:*)
+ echo sparc-auspex-sunos"$UNAME_RELEASE"
+ exit ;;
+ # The situation for MiNT is a little confusing. The machine name
+ # can be virtually everything (everything which is not
+ # "atarist" or "atariste" at least should have a processor
+ # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
+ # to the lowercase version "mint" (or "freemint"). Finally
+ # the system name "TOS" denotes a system which is actually not
+ # MiNT. But MiNT is downward compatible to TOS, so this should
+ # be no problem.
+ atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint"$UNAME_RELEASE"
+ exit ;;
+ atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+ echo m68k-atari-mint"$UNAME_RELEASE"
+ exit ;;
+ *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+ echo m68k-atari-mint"$UNAME_RELEASE"
+ exit ;;
+ milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+ echo m68k-milan-mint"$UNAME_RELEASE"
+ exit ;;
+ hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+ echo m68k-hades-mint"$UNAME_RELEASE"
+ exit ;;
+ *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+ echo m68k-unknown-mint"$UNAME_RELEASE"
+ exit ;;
+ m68k:machten:*:*)
+ echo m68k-apple-machten"$UNAME_RELEASE"
+ exit ;;
+ powerpc:machten:*:*)
+ echo powerpc-apple-machten"$UNAME_RELEASE"
+ exit ;;
+ RISC*:Mach:*:*)
+ echo mips-dec-mach_bsd4.3
+ exit ;;
+ RISC*:ULTRIX:*:*)
+ echo mips-dec-ultrix"$UNAME_RELEASE"
+ exit ;;
+ VAX*:ULTRIX*:*:*)
+ echo vax-dec-ultrix"$UNAME_RELEASE"
+ exit ;;
+ 2020:CLIX:*:* | 2430:CLIX:*:*)
+ echo clipper-intergraph-clix"$UNAME_RELEASE"
+ exit ;;
+ mips:*:*:UMIPS | mips:*:*:RISCos)
+ eval "$set_cc_for_build"
+ sed 's/^ //' << EOF > "$dummy.c"
+#ifdef __cplusplus
+#include /* for printf() prototype */
+ int main (int argc, char *argv[]) {
+#else
+ int main (argc, argv) int argc; char *argv[]; {
+#endif
+ #if defined (host_mips) && defined (MIPSEB)
+ #if defined (SYSTYPE_SYSV)
+ printf ("mips-mips-riscos%ssysv\\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_SVR4)
+ printf ("mips-mips-riscos%ssvr4\\n", argv[1]); exit (0);
+ #endif
+ #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+ printf ("mips-mips-riscos%sbsd\\n", argv[1]); exit (0);
+ #endif
+ #endif
+ exit (-1);
+ }
+EOF
+ $CC_FOR_BUILD -o "$dummy" "$dummy.c" &&
+ dummyarg=`echo "$UNAME_RELEASE" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+ SYSTEM_NAME=`"$dummy" "$dummyarg"` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo mips-mips-riscos"$UNAME_RELEASE"
+ exit ;;
+ Motorola:PowerMAX_OS:*:*)
+ echo powerpc-motorola-powermax
+ exit ;;
+ Motorola:*:4.3:PL8-*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+ echo powerpc-harris-powermax
+ exit ;;
+ Night_Hawk:Power_UNIX:*:*)
+ echo powerpc-harris-powerunix
+ exit ;;
+ m88k:CX/UX:7*:*)
+ echo m88k-harris-cxux7
+ exit ;;
+ m88k:*:4*:R4*)
+ echo m88k-motorola-sysv4
+ exit ;;
+ m88k:*:3*:R3*)
+ echo m88k-motorola-sysv3
+ exit ;;
+ AViiON:dgux:*:*)
+ # DG/UX returns AViiON for all architectures
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ if [ "$UNAME_PROCESSOR" = mc88100 ] || [ "$UNAME_PROCESSOR" = mc88110 ]
+ then
+ if [ "$TARGET_BINARY_INTERFACE"x = m88kdguxelfx ] || \
+ [ "$TARGET_BINARY_INTERFACE"x = x ]
+ then
+ echo m88k-dg-dgux"$UNAME_RELEASE"
+ else
+ echo m88k-dg-dguxbcs"$UNAME_RELEASE"
+ fi
+ else
+ echo i586-dg-dgux"$UNAME_RELEASE"
+ fi
+ exit ;;
+ M88*:DolphinOS:*:*) # DolphinOS (SVR3)
+ echo m88k-dolphin-sysv3
+ exit ;;
+ M88*:*:R3*:*)
+ # Delta 88k system running SVR3
+ echo m88k-motorola-sysv3
+ exit ;;
+ XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+ echo m88k-tektronix-sysv3
+ exit ;;
+ Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+ echo m68k-tektronix-bsd
+ exit ;;
+ *:IRIX*:*:*)
+ echo mips-sgi-irix"`echo "$UNAME_RELEASE"|sed -e 's/-/_/g'`"
+ exit ;;
+ ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+ echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
+ exit ;; # Note that: echo "'`uname -s`'" gives 'AIX '
+ i*86:AIX:*:*)
+ echo i386-ibm-aix
+ exit ;;
+ ia64:AIX:*:*)
+ if [ -x /usr/bin/oslevel ] ; then
+ IBM_REV=`/usr/bin/oslevel`
+ else
+ IBM_REV="$UNAME_VERSION.$UNAME_RELEASE"
+ fi
+ echo "$UNAME_MACHINE"-ibm-aix"$IBM_REV"
+ exit ;;
+ *:AIX:2:3)
+ if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+ eval "$set_cc_for_build"
+ sed 's/^ //' << EOF > "$dummy.c"
+ #include
+
+ main()
+ {
+ if (!__power_pc())
+ exit(1);
+ puts("powerpc-ibm-aix3.2.5");
+ exit(0);
+ }
+EOF
+ if $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"`
+ then
+ echo "$SYSTEM_NAME"
+ else
+ echo rs6000-ibm-aix3.2.5
+ fi
+ elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+ echo rs6000-ibm-aix3.2.4
+ else
+ echo rs6000-ibm-aix3.2
+ fi
+ exit ;;
+ *:AIX:*:[4567])
+ IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+ if /usr/sbin/lsattr -El "$IBM_CPU_ID" | grep ' POWER' >/dev/null 2>&1; then
+ IBM_ARCH=rs6000
+ else
+ IBM_ARCH=powerpc
+ fi
+ if [ -x /usr/bin/lslpp ] ; then
+ IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc |
+ awk -F: '{ print $3 }' | sed s/[0-9]*$/0/`
+ else
+ IBM_REV="$UNAME_VERSION.$UNAME_RELEASE"
+ fi
+ echo "$IBM_ARCH"-ibm-aix"$IBM_REV"
+ exit ;;
+ *:AIX:*:*)
+ echo rs6000-ibm-aix
+ exit ;;
+ ibmrt:4.4BSD:*|romp-ibm:4.4BSD:*)
+ echo romp-ibm-bsd4.4
+ exit ;;
+ ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
+ echo romp-ibm-bsd"$UNAME_RELEASE" # 4.3 with uname added to
+ exit ;; # report: romp-ibm BSD 4.3
+ *:BOSX:*:*)
+ echo rs6000-bull-bosx
+ exit ;;
+ DPX/2?00:B.O.S.:*:*)
+ echo m68k-bull-sysv3
+ exit ;;
+ 9000/[34]??:4.3bsd:1.*:*)
+ echo m68k-hp-bsd
+ exit ;;
+ hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+ echo m68k-hp-bsd4.4
+ exit ;;
+ 9000/[34678]??:HP-UX:*:*)
+ HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'`
+ case "$UNAME_MACHINE" in
+ 9000/31?) HP_ARCH=m68000 ;;
+ 9000/[34]??) HP_ARCH=m68k ;;
+ 9000/[678][0-9][0-9])
+ if [ -x /usr/bin/getconf ]; then
+ sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+ sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+ case "$sc_cpu_version" in
+ 523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0
+ 528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1
+ 532) # CPU_PA_RISC2_0
+ case "$sc_kernel_bits" in
+ 32) HP_ARCH=hppa2.0n ;;
+ 64) HP_ARCH=hppa2.0w ;;
+ '') HP_ARCH=hppa2.0 ;; # HP-UX 10.20
+ esac ;;
+ esac
+ fi
+ if [ "$HP_ARCH" = "" ]; then
+ eval "$set_cc_for_build"
+ sed 's/^ //' << EOF > "$dummy.c"
+
+ #define _HPUX_SOURCE
+ #include
+ #include
+
+ int main ()
+ {
+ #if defined(_SC_KERNEL_BITS)
+ long bits = sysconf(_SC_KERNEL_BITS);
+ #endif
+ long cpu = sysconf (_SC_CPU_VERSION);
+
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+ case CPU_PA_RISC2_0:
+ #if defined(_SC_KERNEL_BITS)
+ switch (bits)
+ {
+ case 64: puts ("hppa2.0w"); break;
+ case 32: puts ("hppa2.0n"); break;
+ default: puts ("hppa2.0"); break;
+ } break;
+ #else /* !defined(_SC_KERNEL_BITS) */
+ puts ("hppa2.0"); break;
+ #endif
+ default: puts ("hppa1.0"); break;
+ }
+ exit (0);
+ }
+EOF
+ (CCOPTS="" $CC_FOR_BUILD -o "$dummy" "$dummy.c" 2>/dev/null) && HP_ARCH=`"$dummy"`
+ test -z "$HP_ARCH" && HP_ARCH=hppa
+ fi ;;
+ esac
+ if [ "$HP_ARCH" = hppa2.0w ]
+ then
+ eval "$set_cc_for_build"
+
+ # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+ # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler
+ # generating 64-bit code. GNU and HP use different nomenclature:
+ #
+ # $ CC_FOR_BUILD=cc ./config.guess
+ # => hppa2.0w-hp-hpux11.23
+ # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+ # => hppa64-hp-hpux11.23
+
+ if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) |
+ grep -q __LP64__
+ then
+ HP_ARCH=hppa2.0w
+ else
+ HP_ARCH=hppa64
+ fi
+ fi
+ echo "$HP_ARCH"-hp-hpux"$HPUX_REV"
+ exit ;;
+ ia64:HP-UX:*:*)
+ HPUX_REV=`echo "$UNAME_RELEASE"|sed -e 's/[^.]*.[0B]*//'`
+ echo ia64-hp-hpux"$HPUX_REV"
+ exit ;;
+ 3050*:HI-UX:*:*)
+ eval "$set_cc_for_build"
+ sed 's/^ //' << EOF > "$dummy.c"
+ #include
+ int
+ main ()
+ {
+ long cpu = sysconf (_SC_CPU_VERSION);
+ /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+ true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
+ results, however. */
+ if (CPU_IS_PA_RISC (cpu))
+ {
+ switch (cpu)
+ {
+ case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+ case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+ default: puts ("hppa-hitachi-hiuxwe2"); break;
+ }
+ }
+ else if (CPU_IS_HP_MC68K (cpu))
+ puts ("m68k-hitachi-hiuxwe2");
+ else puts ("unknown-hitachi-hiuxwe2");
+ exit (0);
+ }
+EOF
+ $CC_FOR_BUILD -o "$dummy" "$dummy.c" && SYSTEM_NAME=`"$dummy"` &&
+ { echo "$SYSTEM_NAME"; exit; }
+ echo unknown-hitachi-hiuxwe2
+ exit ;;
+ 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:*)
+ echo hppa1.1-hp-bsd
+ exit ;;
+ 9000/8??:4.3bsd:*:*)
+ echo hppa1.0-hp-bsd
+ exit ;;
+ *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+ echo hppa1.0-hp-mpeix
+ exit ;;
+ hp7??:OSF1:*:* | hp8?[79]:OSF1:*:*)
+ echo hppa1.1-hp-osf
+ exit ;;
+ hp8??:OSF1:*:*)
+ echo hppa1.0-hp-osf
+ exit ;;
+ i*86:OSF1:*:*)
+ if [ -x /usr/sbin/sysversion ] ; then
+ echo "$UNAME_MACHINE"-unknown-osf1mk
+ else
+ echo "$UNAME_MACHINE"-unknown-osf1
+ fi
+ exit ;;
+ parisc*:Lites*:*:*)
+ echo hppa1.1-hp-lites
+ exit ;;
+ C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+ echo c1-convex-bsd
+ exit ;;
+ C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+ if getsysinfo -f scalar_acc
+ then echo c32-convex-bsd
+ else echo c2-convex-bsd
+ fi
+ exit ;;
+ C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+ echo c34-convex-bsd
+ exit ;;
+ C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+ echo c38-convex-bsd
+ exit ;;
+ C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+ echo c4-convex-bsd
+ exit ;;
+ CRAY*Y-MP:*:*:*)
+ echo ymp-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*[A-Z]90:*:*:*)
+ echo "$UNAME_MACHINE"-cray-unicos"$UNAME_RELEASE" \
+ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+ -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*TS:*:*:*)
+ echo t90-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*T3E:*:*:*)
+ echo alphaev5-cray-unicosmk"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ CRAY*SV1:*:*:*)
+ echo sv1-cray-unicos"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ *:UNICOS/mp:*:*)
+ echo craynv-cray-unicosmp"$UNAME_RELEASE" | sed -e 's/\.[^.]*$/.X/'
+ exit ;;
+ F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+ FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
+ FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
+ FUJITSU_REL=`echo "$UNAME_RELEASE" | sed -e 's/ /_/'`
+ echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ 5000:UNIX_System_V:4.*:*)
+ FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
+ FUJITSU_REL=`echo "$UNAME_RELEASE" | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'`
+ echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+ exit ;;
+ i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+ echo "$UNAME_MACHINE"-pc-bsdi"$UNAME_RELEASE"
+ exit ;;
+ sparc*:BSD/OS:*:*)
+ echo sparc-unknown-bsdi"$UNAME_RELEASE"
+ exit ;;
+ *:BSD/OS:*:*)
+ echo "$UNAME_MACHINE"-unknown-bsdi"$UNAME_RELEASE"
+ exit ;;
+ *:FreeBSD:*:*)
+ UNAME_PROCESSOR=`/usr/bin/uname -p`
+ case "$UNAME_PROCESSOR" in
+ amd64)
+ UNAME_PROCESSOR=x86_64 ;;
+ i386)
+ UNAME_PROCESSOR=i586 ;;
+ esac
+ echo "$UNAME_PROCESSOR"-unknown-freebsd"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`"
+ exit ;;
+ i*:CYGWIN*:*)
+ echo "$UNAME_MACHINE"-pc-cygwin
+ exit ;;
+ *:MINGW64*:*)
+ echo "$UNAME_MACHINE"-pc-mingw64
+ exit ;;
+ *:MINGW*:*)
+ echo "$UNAME_MACHINE"-pc-mingw32
+ exit ;;
+ *:MSYS*:*)
+ echo "$UNAME_MACHINE"-pc-msys
+ exit ;;
+ i*:PW*:*)
+ echo "$UNAME_MACHINE"-pc-pw32
+ exit ;;
+ *:Interix*:*)
+ case "$UNAME_MACHINE" in
+ x86)
+ echo i586-pc-interix"$UNAME_RELEASE"
+ exit ;;
+ authenticamd | genuineintel | EM64T)
+ echo x86_64-unknown-interix"$UNAME_RELEASE"
+ exit ;;
+ IA64)
+ echo ia64-unknown-interix"$UNAME_RELEASE"
+ exit ;;
+ esac ;;
+ i*:UWIN*:*)
+ echo "$UNAME_MACHINE"-pc-uwin
+ exit ;;
+ amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+ echo x86_64-unknown-cygwin
+ exit ;;
+ prep*:SunOS:5.*:*)
+ echo powerpcle-unknown-solaris2"`echo "$UNAME_RELEASE"|sed -e 's/[^.]*//'`"
+ exit ;;
+ *:GNU:*:*)
+ # the GNU system
+ echo "`echo "$UNAME_MACHINE"|sed -e 's,[-/].*$,,'`-unknown-$LIBC`echo "$UNAME_RELEASE"|sed -e 's,/.*$,,'`"
+ exit ;;
+ *:GNU/*:*:*)
+ # other systems with GNU libc and userland
+ echo "$UNAME_MACHINE-unknown-`echo "$UNAME_SYSTEM" | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`-$LIBC"
+ exit ;;
+ i*86:Minix:*:*)
+ echo "$UNAME_MACHINE"-pc-minix
+ exit ;;
+ aarch64:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ aarch64_be:Linux:*:*)
+ UNAME_MACHINE=aarch64_be
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ alpha:Linux:*:*)
+ case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+ EV5) UNAME_MACHINE=alphaev5 ;;
+ EV56) UNAME_MACHINE=alphaev56 ;;
+ PCA56) UNAME_MACHINE=alphapca56 ;;
+ PCA57) UNAME_MACHINE=alphapca56 ;;
+ EV6) UNAME_MACHINE=alphaev6 ;;
+ EV67) UNAME_MACHINE=alphaev67 ;;
+ EV68*) UNAME_MACHINE=alphaev68 ;;
+ esac
+ objdump --private-headers /bin/sh | grep -q ld.so.1
+ if test "$?" = 0 ; then LIBC=gnulibc1 ; fi
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ arc:Linux:*:* | arceb:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ arm*:Linux:*:*)
+ eval "$set_cc_for_build"
+ if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ARM_EABI__
+ then
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ else
+ if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+ | grep -q __ARM_PCS_VFP
+ then
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabi
+ else
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"eabihf
+ fi
+ fi
+ exit ;;
+ avr32*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ cris:Linux:*:*)
+ echo "$UNAME_MACHINE"-axis-linux-"$LIBC"
+ exit ;;
+ crisv32:Linux:*:*)
+ echo "$UNAME_MACHINE"-axis-linux-"$LIBC"
+ exit ;;
+ e2k:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ frv:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ hexagon:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ i*86:Linux:*:*)
+ echo "$UNAME_MACHINE"-pc-linux-"$LIBC"
+ exit ;;
+ ia64:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ k1om:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ m32r*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ m68*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ mips:Linux:*:* | mips64:Linux:*:*)
+ eval "$set_cc_for_build"
+ sed 's/^ //' << EOF > "$dummy.c"
+ #undef CPU
+ #undef ${UNAME_MACHINE}
+ #undef ${UNAME_MACHINE}el
+ #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+ CPU=${UNAME_MACHINE}el
+ #else
+ #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+ CPU=${UNAME_MACHINE}
+ #else
+ CPU=
+ #endif
+ #endif
+EOF
+ eval "`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^CPU'`"
+ test "x$CPU" != x && { echo "$CPU-unknown-linux-$LIBC"; exit; }
+ ;;
+ mips64el:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ openrisc*:Linux:*:*)
+ echo or1k-unknown-linux-"$LIBC"
+ exit ;;
+ or32:Linux:*:* | or1k*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ padre:Linux:*:*)
+ echo sparc-unknown-linux-"$LIBC"
+ exit ;;
+ parisc64:Linux:*:* | hppa64:Linux:*:*)
+ echo hppa64-unknown-linux-"$LIBC"
+ exit ;;
+ parisc:Linux:*:* | hppa:Linux:*:*)
+ # Look for CPU level
+ case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+ PA7*) echo hppa1.1-unknown-linux-"$LIBC" ;;
+ PA8*) echo hppa2.0-unknown-linux-"$LIBC" ;;
+ *) echo hppa-unknown-linux-"$LIBC" ;;
+ esac
+ exit ;;
+ ppc64:Linux:*:*)
+ echo powerpc64-unknown-linux-"$LIBC"
+ exit ;;
+ ppc:Linux:*:*)
+ echo powerpc-unknown-linux-"$LIBC"
+ exit ;;
+ ppc64le:Linux:*:*)
+ echo powerpc64le-unknown-linux-"$LIBC"
+ exit ;;
+ ppcle:Linux:*:*)
+ echo powerpcle-unknown-linux-"$LIBC"
+ exit ;;
+ riscv32:Linux:*:* | riscv64:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ s390:Linux:*:* | s390x:Linux:*:*)
+ echo "$UNAME_MACHINE"-ibm-linux-"$LIBC"
+ exit ;;
+ sh64*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ sh*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ sparc:Linux:*:* | sparc64:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ tile*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ vax:Linux:*:*)
+ echo "$UNAME_MACHINE"-dec-linux-"$LIBC"
+ exit ;;
+ x86_64:Linux:*:*)
+ echo "$UNAME_MACHINE"-pc-linux-"$LIBC"
+ exit ;;
+ xtensa*:Linux:*:*)
+ echo "$UNAME_MACHINE"-unknown-linux-"$LIBC"
+ exit ;;
+ i*86:DYNIX/ptx:4*:*)
+ # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+ # earlier versions are messed up and put the nodename in both
+ # sysname and nodename.
+ echo i386-sequent-sysv4
+ exit ;;
+ i*86:UNIX_SV:4.2MP:2.*)
+ # Unixware is an offshoot of SVR4, but it has its own version
+ # number series starting with 2...
+ # I am not positive that other SVR4 systems won't match this,
+ # I just have to hope. -- rms.
+ # Use sysv4.2uw... so that sysv4* matches it.
+ echo "$UNAME_MACHINE"-pc-sysv4.2uw"$UNAME_VERSION"
+ exit ;;
+ i*86:OS/2:*:*)
+ # If we were able to find `uname', then EMX Unix compatibility
+ # is probably installed.
+ echo "$UNAME_MACHINE"-pc-os2-emx
+ exit ;;
+ i*86:XTS-300:*:STOP)
+ echo "$UNAME_MACHINE"-unknown-stop
+ exit ;;
+ i*86:atheos:*:*)
+ echo "$UNAME_MACHINE"-unknown-atheos
+ exit ;;
+ i*86:syllable:*:*)
+ echo "$UNAME_MACHINE"-pc-syllable
+ exit ;;
+ i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
+ echo i386-unknown-lynxos"$UNAME_RELEASE"
+ exit ;;
+ i*86:*DOS:*:*)
+ echo "$UNAME_MACHINE"-pc-msdosdjgpp
+ exit ;;
+ i*86:*:4.*:*)
+ UNAME_REL=`echo "$UNAME_RELEASE" | sed 's/\/MP$//'`
+ if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+ echo "$UNAME_MACHINE"-univel-sysv"$UNAME_REL"
+ else
+ echo "$UNAME_MACHINE"-pc-sysv"$UNAME_REL"
+ fi
+ exit ;;
+ i*86:*:5:[678]*)
+ # UnixWare 7.x, OpenUNIX and OpenServer 6.
+ case `/bin/uname -X | grep "^Machine"` in
+ *486*) UNAME_MACHINE=i486 ;;
+ *Pentium) UNAME_MACHINE=i586 ;;
+ *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+ esac
+ echo "$UNAME_MACHINE-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}{$UNAME_VERSION}"
+ exit ;;
+ i*86:*:3.2:*)
+ if test -f /usr/options/cb.name; then
+ UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then
+ UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+ (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+ (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+ && UNAME_MACHINE=i586
+ (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+ && UNAME_MACHINE=i686
+ (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+ && UNAME_MACHINE=i686
+ echo "$UNAME_MACHINE"-pc-sco"$UNAME_REL"
+ else
+ echo "$UNAME_MACHINE"-pc-sysv32
+ fi
+ exit ;;
+ pc:*:*:*)
+ # Left here for compatibility:
+ # uname -m prints for DJGPP always 'pc', but it prints nothing about
+ # the processor, so we play safe by assuming i586.
+ # Note: whatever this is, it MUST be the same as what config.sub
+ # prints for the "djgpp" host, or else GDB configure will decide that
+ # this is a cross-build.
+ echo i586-pc-msdosdjgpp
+ exit ;;
+ Intel:Mach:3*:*)
+ echo i386-pc-mach3
+ exit ;;
+ paragon:*:*:*)
+ echo i860-intel-osf1
+ exit ;;
+ i860:*:4.*:*) # i860-SVR4
+ if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+ echo i860-stardent-sysv"$UNAME_RELEASE" # Stardent Vistra i860-SVR4
+ else # Add other i860-SVR4 vendors below as they are discovered.
+ echo i860-unknown-sysv"$UNAME_RELEASE" # Unknown i860-SVR4
+ fi
+ exit ;;
+ mini*:CTIX:SYS*5:*)
+ # "miniframe"
+ echo m68010-convergent-sysv
+ exit ;;
+ mc68k:UNIX:SYSTEM5:3.51m)
+ echo m68k-convergent-sysv
+ exit ;;
+ M680?0:D-NIX:5.3:*)
+ echo m68k-diab-dnix
+ exit ;;
+ M68*:*:R3V[5678]*:*)
+ test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+ 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+ OS_REL=''
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;;
+ 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4; exit; } ;;
+ NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+ OS_REL='.3'
+ test -r /etc/.relid \
+ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+ /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+ && { echo i486-ncr-sysv4.3"$OS_REL"; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; }
+ /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+ && { echo i586-ncr-sysv4.3"$OS_REL"; exit; } ;;
+ m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+ echo m68k-unknown-lynxos"$UNAME_RELEASE"
+ exit ;;
+ mc68030:UNIX_System_V:4.*:*)
+ echo m68k-atari-sysv4
+ exit ;;
+ TSUNAMI:LynxOS:2.*:*)
+ echo sparc-unknown-lynxos"$UNAME_RELEASE"
+ exit ;;
+ rs6000:LynxOS:2.*:*)
+ echo rs6000-unknown-lynxos"$UNAME_RELEASE"
+ exit ;;
+ PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
+ echo powerpc-unknown-lynxos"$UNAME_RELEASE"
+ exit ;;
+ SM[BE]S:UNIX_SV:*:*)
+ echo mips-dde-sysv"$UNAME_RELEASE"
+ exit ;;
+ RM*:ReliantUNIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ RM*:SINIX-*:*:*)
+ echo mips-sni-sysv4
+ exit ;;
+ *:SINIX-*:*:*)
+ if uname -p 2>/dev/null >/dev/null ; then
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ echo "$UNAME_MACHINE"-sni-sysv4
+ else
+ echo ns32k-sni-sysv
+ fi
+ exit ;;
+ PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+ # says
+ echo i586-unisys-sysv4
+ exit ;;
+ *:UNIX_System_V:4*:FTX*)
+ # From Gerald Hewes .
+ # How about differentiating between stratus architectures? -djm
+ echo hppa1.1-stratus-sysv4
+ exit ;;
+ *:*:*:FTX*)
+ # From seanf@swdc.stratus.com.
+ echo i860-stratus-sysv4
+ exit ;;
+ i*86:VOS:*:*)
+ # From Paul.Green@stratus.com.
+ echo "$UNAME_MACHINE"-stratus-vos
+ exit ;;
+ *:VOS:*:*)
+ # From Paul.Green@stratus.com.
+ echo hppa1.1-stratus-vos
+ exit ;;
+ mc68*:A/UX:*:*)
+ echo m68k-apple-aux"$UNAME_RELEASE"
+ exit ;;
+ news*:NEWS-OS:6*:*)
+ echo mips-sony-newsos6
+ exit ;;
+ R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+ if [ -d /usr/nec ]; then
+ echo mips-nec-sysv"$UNAME_RELEASE"
+ else
+ echo mips-unknown-sysv"$UNAME_RELEASE"
+ fi
+ exit ;;
+ BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
+ echo powerpc-be-beos
+ exit ;;
+ BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
+ echo powerpc-apple-beos
+ exit ;;
+ BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
+ echo i586-pc-beos
+ exit ;;
+ BePC:Haiku:*:*) # Haiku running on Intel PC compatible.
+ echo i586-pc-haiku
+ exit ;;
+ x86_64:Haiku:*:*)
+ echo x86_64-unknown-haiku
+ exit ;;
+ SX-4:SUPER-UX:*:*)
+ echo sx4-nec-superux"$UNAME_RELEASE"
+ exit ;;
+ SX-5:SUPER-UX:*:*)
+ echo sx5-nec-superux"$UNAME_RELEASE"
+ exit ;;
+ SX-6:SUPER-UX:*:*)
+ echo sx6-nec-superux"$UNAME_RELEASE"
+ exit ;;
+ SX-7:SUPER-UX:*:*)
+ echo sx7-nec-superux"$UNAME_RELEASE"
+ exit ;;
+ SX-8:SUPER-UX:*:*)
+ echo sx8-nec-superux"$UNAME_RELEASE"
+ exit ;;
+ SX-8R:SUPER-UX:*:*)
+ echo sx8r-nec-superux"$UNAME_RELEASE"
+ exit ;;
+ SX-ACE:SUPER-UX:*:*)
+ echo sxace-nec-superux"$UNAME_RELEASE"
+ exit ;;
+ Power*:Rhapsody:*:*)
+ echo powerpc-apple-rhapsody"$UNAME_RELEASE"
+ exit ;;
+ *:Rhapsody:*:*)
+ echo "$UNAME_MACHINE"-apple-rhapsody"$UNAME_RELEASE"
+ exit ;;
+ *:Darwin:*:*)
+ UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+ eval "$set_cc_for_build"
+ if test "$UNAME_PROCESSOR" = unknown ; then
+ UNAME_PROCESSOR=powerpc
+ fi
+ if test "`echo "$UNAME_RELEASE" | sed -e 's/\..*//'`" -le 10 ; then
+ if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
+ if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
+ grep IS_64BIT_ARCH >/dev/null
+ then
+ case $UNAME_PROCESSOR in
+ i386) UNAME_PROCESSOR=x86_64 ;;
+ powerpc) UNAME_PROCESSOR=powerpc64 ;;
+ esac
+ fi
+ # On 10.4-10.6 one might compile for PowerPC via gcc -arch ppc
+ if (echo '#ifdef __POWERPC__'; echo IS_PPC; echo '#endif') | \
+ (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
+ grep IS_PPC >/dev/null
+ then
+ UNAME_PROCESSOR=powerpc
+ fi
+ fi
+ elif test "$UNAME_PROCESSOR" = i386 ; then
+ # Avoid executing cc on OS X 10.9, as it ships with a stub
+ # that puts up a graphical alert prompting to install
+ # developer tools. Any system running Mac OS X 10.7 or
+ # later (Darwin 11 and later) is required to have a 64-bit
+ # processor. This is not true of the ARM version of Darwin
+ # that Apple uses in portable devices.
+ UNAME_PROCESSOR=x86_64
+ fi
+ echo "$UNAME_PROCESSOR"-apple-darwin"$UNAME_RELEASE"
+ exit ;;
+ *:procnto*:*:* | *:QNX:[0123456789]*:*)
+ UNAME_PROCESSOR=`uname -p`
+ if test "$UNAME_PROCESSOR" = x86; then
+ UNAME_PROCESSOR=i386
+ UNAME_MACHINE=pc
+ fi
+ echo "$UNAME_PROCESSOR"-"$UNAME_MACHINE"-nto-qnx"$UNAME_RELEASE"
+ exit ;;
+ *:QNX:*:4*)
+ echo i386-pc-qnx
+ exit ;;
+ NEO-*:NONSTOP_KERNEL:*:*)
+ echo neo-tandem-nsk"$UNAME_RELEASE"
+ exit ;;
+ NSE-*:NONSTOP_KERNEL:*:*)
+ echo nse-tandem-nsk"$UNAME_RELEASE"
+ exit ;;
+ NSR-*:NONSTOP_KERNEL:*:*)
+ echo nsr-tandem-nsk"$UNAME_RELEASE"
+ exit ;;
+ NSV-*:NONSTOP_KERNEL:*:*)
+ echo nsv-tandem-nsk"$UNAME_RELEASE"
+ exit ;;
+ NSX-*:NONSTOP_KERNEL:*:*)
+ echo nsx-tandem-nsk"$UNAME_RELEASE"
+ exit ;;
+ *:NonStop-UX:*:*)
+ echo mips-compaq-nonstopux
+ exit ;;
+ BS2000:POSIX*:*:*)
+ echo bs2000-siemens-sysv
+ exit ;;
+ DS/*:UNIX_System_V:*:*)
+ echo "$UNAME_MACHINE"-"$UNAME_SYSTEM"-"$UNAME_RELEASE"
+ exit ;;
+ *:Plan9:*:*)
+ # "uname -m" is not consistent, so use $cputype instead. 386
+ # is converted to i386 for consistency with other x86
+ # operating systems.
+ if test "$cputype" = 386; then
+ UNAME_MACHINE=i386
+ else
+ UNAME_MACHINE="$cputype"
+ fi
+ echo "$UNAME_MACHINE"-unknown-plan9
+ exit ;;
+ *:TOPS-10:*:*)
+ echo pdp10-unknown-tops10
+ exit ;;
+ *:TENEX:*:*)
+ echo pdp10-unknown-tenex
+ exit ;;
+ KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+ echo pdp10-dec-tops20
+ exit ;;
+ XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+ echo pdp10-xkl-tops20
+ exit ;;
+ *:TOPS-20:*:*)
+ echo pdp10-unknown-tops20
+ exit ;;
+ *:ITS:*:*)
+ echo pdp10-unknown-its
+ exit ;;
+ SEI:*:*:SEIUX)
+ echo mips-sei-seiux"$UNAME_RELEASE"
+ exit ;;
+ *:DragonFly:*:*)
+ echo "$UNAME_MACHINE"-unknown-dragonfly"`echo "$UNAME_RELEASE"|sed -e 's/[-(].*//'`"
+ exit ;;
+ *:*VMS:*:*)
+ UNAME_MACHINE=`(uname -p) 2>/dev/null`
+ case "$UNAME_MACHINE" in
+ A*) echo alpha-dec-vms ; exit ;;
+ I*) echo ia64-dec-vms ; exit ;;
+ V*) echo vax-dec-vms ; exit ;;
+ esac ;;
+ *:XENIX:*:SysV)
+ echo i386-pc-xenix
+ exit ;;
+ i*86:skyos:*:*)
+ echo "$UNAME_MACHINE"-pc-skyos"`echo "$UNAME_RELEASE" | sed -e 's/ .*$//'`"
+ exit ;;
+ i*86:rdos:*:*)
+ echo "$UNAME_MACHINE"-pc-rdos
+ exit ;;
+ i*86:AROS:*:*)
+ echo "$UNAME_MACHINE"-pc-aros
+ exit ;;
+ x86_64:VMkernel:*:*)
+ echo "$UNAME_MACHINE"-unknown-esx
+ exit ;;
+ amd64:Isilon\ OneFS:*:*)
+ echo x86_64-unknown-onefs
+ exit ;;
+esac
+
+echo "$0: unable to guess system type" >&2
+
+case "$UNAME_MACHINE:$UNAME_SYSTEM" in
+ mips:Linux | mips64:Linux)
+ # If we got here on MIPS GNU/Linux, output extra information.
+ cat >&2 <&2 </dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo = `(hostinfo) 2>/dev/null`
+/bin/universe = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = "$UNAME_MACHINE"
+UNAME_RELEASE = "$UNAME_RELEASE"
+UNAME_SYSTEM = "$UNAME_SYSTEM"
+UNAME_VERSION = "$UNAME_VERSION"
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
ADDED autosetup/autosetup-config.sub
Index: autosetup/autosetup-config.sub
==================================================================
--- autosetup/autosetup-config.sub
+++ autosetup/autosetup-config.sub
@@ -0,0 +1,1801 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+# Copyright 1992-2018 Free Software Foundation, Inc.
+
+timestamp='2018-03-08'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, see .
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that
+# program. This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+
+
+# Please send patches to .
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# You can get the latest version of this script from:
+# https://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support. The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS
+
+Canonicalize a configuration name.
+
+Options:
+ -h, --help print this help, then exit
+ -t, --time-stamp print date of last modification, then exit
+ -v, --version print version number, then exit
+
+Report bugs and patches to ."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright 1992-2018 Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions. There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+ case $1 in
+ --time-stamp | --time* | -t )
+ echo "$timestamp" ; exit ;;
+ --version | -v )
+ echo "$version" ; exit ;;
+ --help | --h* | -h )
+ echo "$usage"; exit ;;
+ -- ) # Stop option processing
+ shift; break ;;
+ - ) # Use stdin as input.
+ break ;;
+ -* )
+ echo "$me: invalid option $1$help"
+ exit 1 ;;
+
+ *local*)
+ # First pass through any local machine types.
+ echo "$1"
+ exit ;;
+
+ * )
+ break ;;
+ esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+ exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+ exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo "$1" | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+ nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
+ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+ knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \
+ kopensolaris*-gnu* | cloudabi*-eabi* | \
+ storm-chaos* | os2-emx* | rtmk-nova*)
+ os=-$maybe_os
+ basic_machine=`echo "$1" | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+ ;;
+ android-linux)
+ os=-linux-android
+ basic_machine=`echo "$1" | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
+ ;;
+ *)
+ basic_machine=`echo "$1" | sed 's/-[^-]*$//'`
+ if [ "$basic_machine" != "$1" ]
+ then os=`echo "$1" | sed 's/.*-/-/'`
+ else os=; fi
+ ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work. We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+ -sun*os*)
+ # Prevent following clause from handling this invalid input.
+ ;;
+ -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+ -apple | -axis | -knuth | -cray | -microblaze*)
+ os=
+ basic_machine=$1
+ ;;
+ -bluegene*)
+ os=-cnk
+ ;;
+ -sim | -cisco | -oki | -wec | -winbond)
+ os=
+ basic_machine=$1
+ ;;
+ -scout)
+ ;;
+ -wrs)
+ os=-vxworks
+ basic_machine=$1
+ ;;
+ -chorusos*)
+ os=-chorusos
+ basic_machine=$1
+ ;;
+ -chorusrdb)
+ os=-chorusrdb
+ basic_machine=$1
+ ;;
+ -hiux*)
+ os=-hiuxwe2
+ ;;
+ -sco6)
+ os=-sco5v6
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5)
+ os=-sco3.2v5
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco4)
+ os=-sco3.2v4
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2.[4-9]*)
+ os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco3.2v[4-9]*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco5v6*)
+ # Don't forget version if it is 3.2v4 or newer.
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -sco*)
+ os=-sco3.2v2
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -udk*)
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -isc)
+ os=-isc2.2
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -clix*)
+ basic_machine=clipper-intergraph
+ ;;
+ -isc*)
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-pc/'`
+ ;;
+ -lynx*178)
+ os=-lynxos178
+ ;;
+ -lynx*5)
+ os=-lynxos5
+ ;;
+ -lynx*)
+ os=-lynxos
+ ;;
+ -ptx*)
+ basic_machine=`echo "$1" | sed -e 's/86-.*/86-sequent/'`
+ ;;
+ -psos*)
+ os=-psos
+ ;;
+ -mint | -mint[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+ # Recognize the basic CPU types without company name.
+ # Some are omitted here because they have special meanings below.
+ 1750a | 580 \
+ | a29k \
+ | aarch64 | aarch64_be \
+ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+ | am33_2.0 \
+ | arc | arceb \
+ | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
+ | avr | avr32 \
+ | ba \
+ | be32 | be64 \
+ | bfin \
+ | c4x | c8051 | clipper \
+ | d10v | d30v | dlx | dsp16xx \
+ | e2k | epiphany \
+ | fido | fr30 | frv | ft32 \
+ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+ | hexagon \
+ | i370 | i860 | i960 | ia16 | ia64 \
+ | ip2k | iq2000 \
+ | k1om \
+ | le32 | le64 \
+ | lm32 \
+ | m32c | m32r | m32rle | m68000 | m68k | m88k \
+ | maxq | mb | microblaze | microblazeel | mcore | mep | metag \
+ | mips | mipsbe | mipseb | mipsel | mipsle \
+ | mips16 \
+ | mips64 | mips64el \
+ | mips64octeon | mips64octeonel \
+ | mips64orion | mips64orionel \
+ | mips64r5900 | mips64r5900el \
+ | mips64vr | mips64vrel \
+ | mips64vr4100 | mips64vr4100el \
+ | mips64vr4300 | mips64vr4300el \
+ | mips64vr5000 | mips64vr5000el \
+ | mips64vr5900 | mips64vr5900el \
+ | mipsisa32 | mipsisa32el \
+ | mipsisa32r2 | mipsisa32r2el \
+ | mipsisa32r6 | mipsisa32r6el \
+ | mipsisa64 | mipsisa64el \
+ | mipsisa64r2 | mipsisa64r2el \
+ | mipsisa64r6 | mipsisa64r6el \
+ | mipsisa64sb1 | mipsisa64sb1el \
+ | mipsisa64sr71k | mipsisa64sr71kel \
+ | mipsr5900 | mipsr5900el \
+ | mipstx39 | mipstx39el \
+ | mn10200 | mn10300 \
+ | moxie \
+ | mt \
+ | msp430 \
+ | nds32 | nds32le | nds32be \
+ | nios | nios2 | nios2eb | nios2el \
+ | ns16k | ns32k \
+ | open8 | or1k | or1knd | or32 \
+ | pdp10 | pj | pjl \
+ | powerpc | powerpc64 | powerpc64le | powerpcle \
+ | pru \
+ | pyramid \
+ | riscv32 | riscv64 \
+ | rl78 | rx \
+ | score \
+ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[234]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+ | sh64 | sh64le \
+ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+ | spu \
+ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+ | ubicom32 \
+ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+ | visium \
+ | wasm32 \
+ | x86 | xc16x | xstormy16 | xtensa \
+ | z8k | z80)
+ basic_machine=$basic_machine-unknown
+ ;;
+ c54x)
+ basic_machine=tic54x-unknown
+ ;;
+ c55x)
+ basic_machine=tic55x-unknown
+ ;;
+ c6x)
+ basic_machine=tic6x-unknown
+ ;;
+ leon|leon[3-9])
+ basic_machine=sparc-$basic_machine
+ ;;
+ m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
+ basic_machine=$basic_machine-unknown
+ os=-none
+ ;;
+ m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65)
+ ;;
+ ms1)
+ basic_machine=mt-unknown
+ ;;
+
+ strongarm | thumb | xscale)
+ basic_machine=arm-unknown
+ ;;
+ xgate)
+ basic_machine=$basic_machine-unknown
+ os=-none
+ ;;
+ xscaleeb)
+ basic_machine=armeb-unknown
+ ;;
+
+ xscaleel)
+ basic_machine=armel-unknown
+ ;;
+
+ # We use `pc' rather than `unknown'
+ # because (1) that's what they normally are, and
+ # (2) the word "unknown" tends to confuse beginning users.
+ i*86 | x86_64)
+ basic_machine=$basic_machine-pc
+ ;;
+ # Object if more than one company name word.
+ *-*-*)
+ echo Invalid configuration \`"$1"\': machine \`"$basic_machine"\' not recognized 1>&2
+ exit 1
+ ;;
+ # Recognize the basic CPU types with company name.
+ 580-* \
+ | a29k-* \
+ | aarch64-* | aarch64_be-* \
+ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
+ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
+ | avr-* | avr32-* \
+ | ba-* \
+ | be32-* | be64-* \
+ | bfin-* | bs2000-* \
+ | c[123]* | c30-* | [cjt]90-* | c4x-* \
+ | c8051-* | clipper-* | craynv-* | cydra-* \
+ | d10v-* | d30v-* | dlx-* \
+ | e2k-* | elxsi-* \
+ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+ | h8300-* | h8500-* \
+ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+ | hexagon-* \
+ | i*86-* | i860-* | i960-* | ia16-* | ia64-* \
+ | ip2k-* | iq2000-* \
+ | k1om-* \
+ | le32-* | le64-* \
+ | lm32-* \
+ | m32c-* | m32r-* | m32rle-* \
+ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
+ | microblaze-* | microblazeel-* \
+ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+ | mips16-* \
+ | mips64-* | mips64el-* \
+ | mips64octeon-* | mips64octeonel-* \
+ | mips64orion-* | mips64orionel-* \
+ | mips64r5900-* | mips64r5900el-* \
+ | mips64vr-* | mips64vrel-* \
+ | mips64vr4100-* | mips64vr4100el-* \
+ | mips64vr4300-* | mips64vr4300el-* \
+ | mips64vr5000-* | mips64vr5000el-* \
+ | mips64vr5900-* | mips64vr5900el-* \
+ | mipsisa32-* | mipsisa32el-* \
+ | mipsisa32r2-* | mipsisa32r2el-* \
+ | mipsisa32r6-* | mipsisa32r6el-* \
+ | mipsisa64-* | mipsisa64el-* \
+ | mipsisa64r2-* | mipsisa64r2el-* \
+ | mipsisa64r6-* | mipsisa64r6el-* \
+ | mipsisa64sb1-* | mipsisa64sb1el-* \
+ | mipsisa64sr71k-* | mipsisa64sr71kel-* \
+ | mipsr5900-* | mipsr5900el-* \
+ | mipstx39-* | mipstx39el-* \
+ | mmix-* \
+ | mt-* \
+ | msp430-* \
+ | nds32-* | nds32le-* | nds32be-* \
+ | nios-* | nios2-* | nios2eb-* | nios2el-* \
+ | none-* | np1-* | ns16k-* | ns32k-* \
+ | open8-* \
+ | or1k*-* \
+ | orion-* \
+ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+ | pru-* \
+ | pyramid-* \
+ | riscv32-* | riscv64-* \
+ | rl78-* | romp-* | rs6000-* | rx-* \
+ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+ | sparclite-* \
+ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx*-* \
+ | tahoe-* \
+ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+ | tile*-* \
+ | tron-* \
+ | ubicom32-* \
+ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+ | vax-* \
+ | visium-* \
+ | wasm32-* \
+ | we32k-* \
+ | x86-* | x86_64-* | xc16x-* | xps100-* \
+ | xstormy16-* | xtensa*-* \
+ | ymp-* \
+ | z8k-* | z80-*)
+ ;;
+ # Recognize the basic CPU types without company name, with glob match.
+ xtensa*)
+ basic_machine=$basic_machine-unknown
+ ;;
+ # Recognize the various machine names and aliases which stand
+ # for a CPU type and a company and sometimes even an OS.
+ 386bsd)
+ basic_machine=i386-pc
+ os=-bsd
+ ;;
+ 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+ basic_machine=m68000-att
+ ;;
+ 3b*)
+ basic_machine=we32k-att
+ ;;
+ a29khif)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ abacus)
+ basic_machine=abacus-unknown
+ ;;
+ adobe68k)
+ basic_machine=m68010-adobe
+ os=-scout
+ ;;
+ alliant | fx80)
+ basic_machine=fx80-alliant
+ ;;
+ altos | altos3068)
+ basic_machine=m68k-altos
+ ;;
+ am29k)
+ basic_machine=a29k-none
+ os=-bsd
+ ;;
+ amd64)
+ basic_machine=x86_64-pc
+ ;;
+ amd64-*)
+ basic_machine=x86_64-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ amdahl)
+ basic_machine=580-amdahl
+ os=-sysv
+ ;;
+ amiga | amiga-*)
+ basic_machine=m68k-unknown
+ ;;
+ amigaos | amigados)
+ basic_machine=m68k-unknown
+ os=-amigaos
+ ;;
+ amigaunix | amix)
+ basic_machine=m68k-unknown
+ os=-sysv4
+ ;;
+ apollo68)
+ basic_machine=m68k-apollo
+ os=-sysv
+ ;;
+ apollo68bsd)
+ basic_machine=m68k-apollo
+ os=-bsd
+ ;;
+ aros)
+ basic_machine=i386-pc
+ os=-aros
+ ;;
+ asmjs)
+ basic_machine=asmjs-unknown
+ ;;
+ aux)
+ basic_machine=m68k-apple
+ os=-aux
+ ;;
+ balance)
+ basic_machine=ns32k-sequent
+ os=-dynix
+ ;;
+ blackfin)
+ basic_machine=bfin-unknown
+ os=-linux
+ ;;
+ blackfin-*)
+ basic_machine=bfin-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ bluegene*)
+ basic_machine=powerpc-ibm
+ os=-cnk
+ ;;
+ c54x-*)
+ basic_machine=tic54x-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ c55x-*)
+ basic_machine=tic55x-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ c6x-*)
+ basic_machine=tic6x-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ c90)
+ basic_machine=c90-cray
+ os=-unicos
+ ;;
+ cegcc)
+ basic_machine=arm-unknown
+ os=-cegcc
+ ;;
+ convex-c1)
+ basic_machine=c1-convex
+ os=-bsd
+ ;;
+ convex-c2)
+ basic_machine=c2-convex
+ os=-bsd
+ ;;
+ convex-c32)
+ basic_machine=c32-convex
+ os=-bsd
+ ;;
+ convex-c34)
+ basic_machine=c34-convex
+ os=-bsd
+ ;;
+ convex-c38)
+ basic_machine=c38-convex
+ os=-bsd
+ ;;
+ cray | j90)
+ basic_machine=j90-cray
+ os=-unicos
+ ;;
+ craynv)
+ basic_machine=craynv-cray
+ os=-unicosmp
+ ;;
+ cr16 | cr16-*)
+ basic_machine=cr16-unknown
+ os=-elf
+ ;;
+ crds | unos)
+ basic_machine=m68k-crds
+ ;;
+ crisv32 | crisv32-* | etraxfs*)
+ basic_machine=crisv32-axis
+ ;;
+ cris | cris-* | etrax*)
+ basic_machine=cris-axis
+ ;;
+ crx)
+ basic_machine=crx-unknown
+ os=-elf
+ ;;
+ da30 | da30-*)
+ basic_machine=m68k-da30
+ ;;
+ decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+ basic_machine=mips-dec
+ ;;
+ decsystem10* | dec10*)
+ basic_machine=pdp10-dec
+ os=-tops10
+ ;;
+ decsystem20* | dec20*)
+ basic_machine=pdp10-dec
+ os=-tops20
+ ;;
+ delta | 3300 | motorola-3300 | motorola-delta \
+ | 3300-motorola | delta-motorola)
+ basic_machine=m68k-motorola
+ ;;
+ delta88)
+ basic_machine=m88k-motorola
+ os=-sysv3
+ ;;
+ dicos)
+ basic_machine=i686-pc
+ os=-dicos
+ ;;
+ djgpp)
+ basic_machine=i586-pc
+ os=-msdosdjgpp
+ ;;
+ dpx20 | dpx20-*)
+ basic_machine=rs6000-bull
+ os=-bosx
+ ;;
+ dpx2*)
+ basic_machine=m68k-bull
+ os=-sysv3
+ ;;
+ e500v[12])
+ basic_machine=powerpc-unknown
+ os=$os"spe"
+ ;;
+ e500v[12]-*)
+ basic_machine=powerpc-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ os=$os"spe"
+ ;;
+ ebmon29k)
+ basic_machine=a29k-amd
+ os=-ebmon
+ ;;
+ elxsi)
+ basic_machine=elxsi-elxsi
+ os=-bsd
+ ;;
+ encore | umax | mmax)
+ basic_machine=ns32k-encore
+ ;;
+ es1800 | OSE68k | ose68k | ose | OSE)
+ basic_machine=m68k-ericsson
+ os=-ose
+ ;;
+ fx2800)
+ basic_machine=i860-alliant
+ ;;
+ genix)
+ basic_machine=ns32k-ns
+ ;;
+ gmicro)
+ basic_machine=tron-gmicro
+ os=-sysv
+ ;;
+ go32)
+ basic_machine=i386-pc
+ os=-go32
+ ;;
+ h3050r* | hiux*)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ h8300hms)
+ basic_machine=h8300-hitachi
+ os=-hms
+ ;;
+ h8300xray)
+ basic_machine=h8300-hitachi
+ os=-xray
+ ;;
+ h8500hms)
+ basic_machine=h8500-hitachi
+ os=-hms
+ ;;
+ harris)
+ basic_machine=m88k-harris
+ os=-sysv3
+ ;;
+ hp300-*)
+ basic_machine=m68k-hp
+ ;;
+ hp300bsd)
+ basic_machine=m68k-hp
+ os=-bsd
+ ;;
+ hp300hpux)
+ basic_machine=m68k-hp
+ os=-hpux
+ ;;
+ hp3k9[0-9][0-9] | hp9[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k2[0-9][0-9] | hp9k31[0-9])
+ basic_machine=m68000-hp
+ ;;
+ hp9k3[2-9][0-9])
+ basic_machine=m68k-hp
+ ;;
+ hp9k6[0-9][0-9] | hp6[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hp9k7[0-79][0-9] | hp7[0-79][0-9])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k78[0-9] | hp78[0-9])
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+ # FIXME: really hppa2.0-hp
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][13679] | hp8[0-9][13679])
+ basic_machine=hppa1.1-hp
+ ;;
+ hp9k8[0-9][0-9] | hp8[0-9][0-9])
+ basic_machine=hppa1.0-hp
+ ;;
+ hppaosf)
+ basic_machine=hppa1.1-hp
+ os=-osf
+ ;;
+ hppro)
+ basic_machine=hppa1.1-hp
+ os=-proelf
+ ;;
+ i370-ibm* | ibm*)
+ basic_machine=i370-ibm
+ ;;
+ i*86v32)
+ basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'`
+ os=-sysv32
+ ;;
+ i*86v4*)
+ basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'`
+ os=-sysv4
+ ;;
+ i*86v)
+ basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'`
+ os=-sysv
+ ;;
+ i*86sol2)
+ basic_machine=`echo "$1" | sed -e 's/86.*/86-pc/'`
+ os=-solaris2
+ ;;
+ i386mach)
+ basic_machine=i386-mach
+ os=-mach
+ ;;
+ vsta)
+ basic_machine=i386-unknown
+ os=-vsta
+ ;;
+ iris | iris4d)
+ basic_machine=mips-sgi
+ case $os in
+ -irix*)
+ ;;
+ *)
+ os=-irix4
+ ;;
+ esac
+ ;;
+ isi68 | isi)
+ basic_machine=m68k-isi
+ os=-sysv
+ ;;
+ leon-*|leon[3-9]-*)
+ basic_machine=sparc-`echo "$basic_machine" | sed 's/-.*//'`
+ ;;
+ m68knommu)
+ basic_machine=m68k-unknown
+ os=-linux
+ ;;
+ m68knommu-*)
+ basic_machine=m68k-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ magnum | m3230)
+ basic_machine=mips-mips
+ os=-sysv
+ ;;
+ merlin)
+ basic_machine=ns32k-utek
+ os=-sysv
+ ;;
+ microblaze*)
+ basic_machine=microblaze-xilinx
+ ;;
+ mingw64)
+ basic_machine=x86_64-pc
+ os=-mingw64
+ ;;
+ mingw32)
+ basic_machine=i686-pc
+ os=-mingw32
+ ;;
+ mingw32ce)
+ basic_machine=arm-unknown
+ os=-mingw32ce
+ ;;
+ miniframe)
+ basic_machine=m68000-convergent
+ ;;
+ *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+ basic_machine=m68k-atari
+ os=-mint
+ ;;
+ mips3*-*)
+ basic_machine=`echo "$basic_machine" | sed -e 's/mips3/mips64/'`
+ ;;
+ mips3*)
+ basic_machine=`echo "$basic_machine" | sed -e 's/mips3/mips64/'`-unknown
+ ;;
+ monitor)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ morphos)
+ basic_machine=powerpc-unknown
+ os=-morphos
+ ;;
+ moxiebox)
+ basic_machine=moxie-unknown
+ os=-moxiebox
+ ;;
+ msdos)
+ basic_machine=i386-pc
+ os=-msdos
+ ;;
+ ms1-*)
+ basic_machine=`echo "$basic_machine" | sed -e 's/ms1-/mt-/'`
+ ;;
+ msys)
+ basic_machine=i686-pc
+ os=-msys
+ ;;
+ mvs)
+ basic_machine=i370-ibm
+ os=-mvs
+ ;;
+ nacl)
+ basic_machine=le32-unknown
+ os=-nacl
+ ;;
+ ncr3000)
+ basic_machine=i486-ncr
+ os=-sysv4
+ ;;
+ netbsd386)
+ basic_machine=i386-unknown
+ os=-netbsd
+ ;;
+ netwinder)
+ basic_machine=armv4l-rebel
+ os=-linux
+ ;;
+ news | news700 | news800 | news900)
+ basic_machine=m68k-sony
+ os=-newsos
+ ;;
+ news1000)
+ basic_machine=m68030-sony
+ os=-newsos
+ ;;
+ news-3600 | risc-news)
+ basic_machine=mips-sony
+ os=-newsos
+ ;;
+ necv70)
+ basic_machine=v70-nec
+ os=-sysv
+ ;;
+ next | m*-next)
+ basic_machine=m68k-next
+ case $os in
+ -nextstep* )
+ ;;
+ -ns2*)
+ os=-nextstep2
+ ;;
+ *)
+ os=-nextstep3
+ ;;
+ esac
+ ;;
+ nh3000)
+ basic_machine=m68k-harris
+ os=-cxux
+ ;;
+ nh[45]000)
+ basic_machine=m88k-harris
+ os=-cxux
+ ;;
+ nindy960)
+ basic_machine=i960-intel
+ os=-nindy
+ ;;
+ mon960)
+ basic_machine=i960-intel
+ os=-mon960
+ ;;
+ nonstopux)
+ basic_machine=mips-compaq
+ os=-nonstopux
+ ;;
+ np1)
+ basic_machine=np1-gould
+ ;;
+ neo-tandem)
+ basic_machine=neo-tandem
+ ;;
+ nse-tandem)
+ basic_machine=nse-tandem
+ ;;
+ nsr-tandem)
+ basic_machine=nsr-tandem
+ ;;
+ nsv-tandem)
+ basic_machine=nsv-tandem
+ ;;
+ nsx-tandem)
+ basic_machine=nsx-tandem
+ ;;
+ op50n-* | op60c-*)
+ basic_machine=hppa1.1-oki
+ os=-proelf
+ ;;
+ openrisc | openrisc-*)
+ basic_machine=or32-unknown
+ ;;
+ os400)
+ basic_machine=powerpc-ibm
+ os=-os400
+ ;;
+ OSE68000 | ose68000)
+ basic_machine=m68000-ericsson
+ os=-ose
+ ;;
+ os68k)
+ basic_machine=m68k-none
+ os=-os68k
+ ;;
+ pa-hitachi)
+ basic_machine=hppa1.1-hitachi
+ os=-hiuxwe2
+ ;;
+ paragon)
+ basic_machine=i860-intel
+ os=-osf
+ ;;
+ parisc)
+ basic_machine=hppa-unknown
+ os=-linux
+ ;;
+ parisc-*)
+ basic_machine=hppa-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ os=-linux
+ ;;
+ pbd)
+ basic_machine=sparc-tti
+ ;;
+ pbb)
+ basic_machine=m68k-tti
+ ;;
+ pc532 | pc532-*)
+ basic_machine=ns32k-pc532
+ ;;
+ pc98)
+ basic_machine=i386-pc
+ ;;
+ pc98-*)
+ basic_machine=i386-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ pentium | p5 | k5 | k6 | nexgen | viac3)
+ basic_machine=i586-pc
+ ;;
+ pentiumpro | p6 | 6x86 | athlon | athlon_*)
+ basic_machine=i686-pc
+ ;;
+ pentiumii | pentium2 | pentiumiii | pentium3)
+ basic_machine=i686-pc
+ ;;
+ pentium4)
+ basic_machine=i786-pc
+ ;;
+ pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+ basic_machine=i586-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ pentiumpro-* | p6-* | 6x86-* | athlon-*)
+ basic_machine=i686-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+ basic_machine=i686-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ pentium4-*)
+ basic_machine=i786-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ pn)
+ basic_machine=pn-gould
+ ;;
+ power) basic_machine=power-ibm
+ ;;
+ ppc | ppcbe) basic_machine=powerpc-unknown
+ ;;
+ ppc-* | ppcbe-*)
+ basic_machine=powerpc-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ ppcle | powerpclittle)
+ basic_machine=powerpcle-unknown
+ ;;
+ ppcle-* | powerpclittle-*)
+ basic_machine=powerpcle-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ ppc64) basic_machine=powerpc64-unknown
+ ;;
+ ppc64-*) basic_machine=powerpc64-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ ppc64le | powerpc64little)
+ basic_machine=powerpc64le-unknown
+ ;;
+ ppc64le-* | powerpc64little-*)
+ basic_machine=powerpc64le-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ ps2)
+ basic_machine=i386-ibm
+ ;;
+ pw32)
+ basic_machine=i586-unknown
+ os=-pw32
+ ;;
+ rdos | rdos64)
+ basic_machine=x86_64-pc
+ os=-rdos
+ ;;
+ rdos32)
+ basic_machine=i386-pc
+ os=-rdos
+ ;;
+ rom68k)
+ basic_machine=m68k-rom68k
+ os=-coff
+ ;;
+ rm[46]00)
+ basic_machine=mips-siemens
+ ;;
+ rtpc | rtpc-*)
+ basic_machine=romp-ibm
+ ;;
+ s390 | s390-*)
+ basic_machine=s390-ibm
+ ;;
+ s390x | s390x-*)
+ basic_machine=s390x-ibm
+ ;;
+ sa29200)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ sb1)
+ basic_machine=mipsisa64sb1-unknown
+ ;;
+ sb1el)
+ basic_machine=mipsisa64sb1el-unknown
+ ;;
+ sde)
+ basic_machine=mipsisa32-sde
+ os=-elf
+ ;;
+ sei)
+ basic_machine=mips-sei
+ os=-seiux
+ ;;
+ sequent)
+ basic_machine=i386-sequent
+ ;;
+ sh5el)
+ basic_machine=sh5le-unknown
+ ;;
+ simso-wrs)
+ basic_machine=sparclite-wrs
+ os=-vxworks
+ ;;
+ sps7)
+ basic_machine=m68k-bull
+ os=-sysv2
+ ;;
+ spur)
+ basic_machine=spur-unknown
+ ;;
+ st2000)
+ basic_machine=m68k-tandem
+ ;;
+ stratus)
+ basic_machine=i860-stratus
+ os=-sysv4
+ ;;
+ strongarm-* | thumb-*)
+ basic_machine=arm-`echo "$basic_machine" | sed 's/^[^-]*-//'`
+ ;;
+ sun2)
+ basic_machine=m68000-sun
+ ;;
+ sun2os3)
+ basic_machine=m68000-sun
+ os=-sunos3
+ ;;
+ sun2os4)
+ basic_machine=m68000-sun
+ os=-sunos4
+ ;;
+ sun3os3)
+ basic_machine=m68k-sun
+ os=-sunos3
+ ;;
+ sun3os4)
+ basic_machine=m68k-sun
+ os=-sunos4
+ ;;
+ sun4os3)
+ basic_machine=sparc-sun
+ os=-sunos3
+ ;;
+ sun4os4)
+ basic_machine=sparc-sun
+ os=-sunos4
+ ;;
+ sun4sol2)
+ basic_machine=sparc-sun
+ os=-solaris2
+ ;;
+ sun3 | sun3-*)
+ basic_machine=m68k-sun
+ ;;
+ sun4)
+ basic_machine=sparc-sun
+ ;;
+ sun386 | sun386i | roadrunner)
+ basic_machine=i386-sun
+ ;;
+ sv1)
+ basic_machine=sv1-cray
+ os=-unicos
+ ;;
+ symmetry)
+ basic_machine=i386-sequent
+ os=-dynix
+ ;;
+ t3e)
+ basic_machine=alphaev5-cray
+ os=-unicos
+ ;;
+ t90)
+ basic_machine=t90-cray
+ os=-unicos
+ ;;
+ tile*)
+ basic_machine=$basic_machine-unknown
+ os=-linux-gnu
+ ;;
+ tx39)
+ basic_machine=mipstx39-unknown
+ ;;
+ tx39el)
+ basic_machine=mipstx39el-unknown
+ ;;
+ toad1)
+ basic_machine=pdp10-xkl
+ os=-tops20
+ ;;
+ tower | tower-32)
+ basic_machine=m68k-ncr
+ ;;
+ tpf)
+ basic_machine=s390x-ibm
+ os=-tpf
+ ;;
+ udi29k)
+ basic_machine=a29k-amd
+ os=-udi
+ ;;
+ ultra3)
+ basic_machine=a29k-nyu
+ os=-sym1
+ ;;
+ v810 | necv810)
+ basic_machine=v810-nec
+ os=-none
+ ;;
+ vaxv)
+ basic_machine=vax-dec
+ os=-sysv
+ ;;
+ vms)
+ basic_machine=vax-dec
+ os=-vms
+ ;;
+ vpp*|vx|vx-*)
+ basic_machine=f301-fujitsu
+ ;;
+ vxworks960)
+ basic_machine=i960-wrs
+ os=-vxworks
+ ;;
+ vxworks68)
+ basic_machine=m68k-wrs
+ os=-vxworks
+ ;;
+ vxworks29k)
+ basic_machine=a29k-wrs
+ os=-vxworks
+ ;;
+ w65*)
+ basic_machine=w65-wdc
+ os=-none
+ ;;
+ w89k-*)
+ basic_machine=hppa1.1-winbond
+ os=-proelf
+ ;;
+ x64)
+ basic_machine=x86_64-pc
+ ;;
+ xbox)
+ basic_machine=i686-pc
+ os=-mingw32
+ ;;
+ xps | xps100)
+ basic_machine=xps100-honeywell
+ ;;
+ xscale-* | xscalee[bl]-*)
+ basic_machine=`echo "$basic_machine" | sed 's/^xscale/arm/'`
+ ;;
+ ymp)
+ basic_machine=ymp-cray
+ os=-unicos
+ ;;
+ none)
+ basic_machine=none-none
+ os=-none
+ ;;
+
+# Here we handle the default manufacturer of certain CPU types. It is in
+# some cases the only manufacturer, in others, it is the most popular.
+ w89k)
+ basic_machine=hppa1.1-winbond
+ ;;
+ op50n)
+ basic_machine=hppa1.1-oki
+ ;;
+ op60c)
+ basic_machine=hppa1.1-oki
+ ;;
+ romp)
+ basic_machine=romp-ibm
+ ;;
+ mmix)
+ basic_machine=mmix-knuth
+ ;;
+ rs6000)
+ basic_machine=rs6000-ibm
+ ;;
+ vax)
+ basic_machine=vax-dec
+ ;;
+ pdp11)
+ basic_machine=pdp11-dec
+ ;;
+ we32k)
+ basic_machine=we32k-att
+ ;;
+ sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
+ basic_machine=sh-unknown
+ ;;
+ cydra)
+ basic_machine=cydra-cydrome
+ ;;
+ orion)
+ basic_machine=orion-highlevel
+ ;;
+ orion105)
+ basic_machine=clipper-highlevel
+ ;;
+ mac | mpw | mac-mpw)
+ basic_machine=m68k-apple
+ ;;
+ pmac | pmac-mpw)
+ basic_machine=powerpc-apple
+ ;;
+ *-unknown)
+ # Make sure to match an already-canonicalized machine name.
+ ;;
+ *)
+ echo Invalid configuration \`"$1"\': machine \`"$basic_machine"\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+ *-digital*)
+ basic_machine=`echo "$basic_machine" | sed 's/digital.*/dec/'`
+ ;;
+ *-commodore*)
+ basic_machine=`echo "$basic_machine" | sed 's/commodore.*/cbm/'`
+ ;;
+ *)
+ ;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+ # First match some system type aliases that might get confused
+ # with valid system types.
+ # -solaris* is a basic system type, with this one exception.
+ -auroraux)
+ os=-auroraux
+ ;;
+ -solaris1 | -solaris1.*)
+ os=`echo $os | sed -e 's|solaris1|sunos4|'`
+ ;;
+ -solaris)
+ os=-solaris2
+ ;;
+ -unixware*)
+ os=-sysv4.2uw
+ ;;
+ -gnu/linux*)
+ os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+ ;;
+ # es1800 is here to avoid being matched by es* (a different OS)
+ -es1800*)
+ os=-ose
+ ;;
+ # Now accept the basic system types.
+ # The portable systems comes first.
+ # Each alternative MUST end in a * to match a version number.
+ # -sysv* is not here because it comes later, after sysvr4.
+ -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
+ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+ | -sym* | -kopensolaris* | -plan9* \
+ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+ | -aos* | -aros* | -cloudabi* | -sortix* \
+ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+ | -hiux* | -knetbsd* | -mirbsd* | -netbsd* \
+ | -bitrig* | -openbsd* | -solidbsd* | -libertybsd* \
+ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* | -hcos* \
+ | -chorusos* | -chorusrdb* | -cegcc* | -glidix* \
+ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+ | -midipix* | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+ | -linux-newlib* | -linux-musl* | -linux-uclibc* \
+ | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
+ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* \
+ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+ | -morphos* | -superux* | -rtmk* | -windiss* \
+ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* \
+ | -onefs* | -tirtos* | -phoenix* | -fuchsia* | -redox* | -bme* \
+ | -midnightbsd*)
+ # Remember, each alternative MUST END IN *, to match a version number.
+ ;;
+ -qnx*)
+ case $basic_machine in
+ x86-* | i*86-*)
+ ;;
+ *)
+ os=-nto$os
+ ;;
+ esac
+ ;;
+ -nto-qnx*)
+ ;;
+ -nto*)
+ os=`echo $os | sed -e 's|nto|nto-qnx|'`
+ ;;
+ -sim | -xray | -os68k* | -v88r* \
+ | -windows* | -osx | -abug | -netware* | -os9* \
+ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+ ;;
+ -mac*)
+ os=`echo "$os" | sed -e 's|mac|macos|'`
+ ;;
+ -linux-dietlibc)
+ os=-linux-dietlibc
+ ;;
+ -linux*)
+ os=`echo $os | sed -e 's|linux|linux-gnu|'`
+ ;;
+ -sunos5*)
+ os=`echo "$os" | sed -e 's|sunos5|solaris2|'`
+ ;;
+ -sunos6*)
+ os=`echo "$os" | sed -e 's|sunos6|solaris3|'`
+ ;;
+ -opened*)
+ os=-openedition
+ ;;
+ -os400*)
+ os=-os400
+ ;;
+ -wince*)
+ os=-wince
+ ;;
+ -utek*)
+ os=-bsd
+ ;;
+ -dynix*)
+ os=-bsd
+ ;;
+ -acis*)
+ os=-aos
+ ;;
+ -atheos*)
+ os=-atheos
+ ;;
+ -syllable*)
+ os=-syllable
+ ;;
+ -386bsd)
+ os=-bsd
+ ;;
+ -ctix* | -uts*)
+ os=-sysv
+ ;;
+ -nova*)
+ os=-rtmk-nova
+ ;;
+ -ns2)
+ os=-nextstep2
+ ;;
+ -nsk*)
+ os=-nsk
+ ;;
+ # Preserve the version number of sinix5.
+ -sinix5.*)
+ os=`echo $os | sed -e 's|sinix|sysv|'`
+ ;;
+ -sinix*)
+ os=-sysv4
+ ;;
+ -tpf*)
+ os=-tpf
+ ;;
+ -triton*)
+ os=-sysv3
+ ;;
+ -oss*)
+ os=-sysv3
+ ;;
+ -svr4*)
+ os=-sysv4
+ ;;
+ -svr3)
+ os=-sysv3
+ ;;
+ -sysvr4)
+ os=-sysv4
+ ;;
+ # This must come after -sysvr4.
+ -sysv*)
+ ;;
+ -ose*)
+ os=-ose
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ os=-mint
+ ;;
+ -zvmoe)
+ os=-zvmoe
+ ;;
+ -dicos*)
+ os=-dicos
+ ;;
+ -pikeos*)
+ # Until real need of OS specific support for
+ # particular features comes up, bare metal
+ # configurations are quite functional.
+ case $basic_machine in
+ arm*)
+ os=-eabi
+ ;;
+ *)
+ os=-elf
+ ;;
+ esac
+ ;;
+ -nacl*)
+ ;;
+ -ios)
+ ;;
+ -none)
+ ;;
+ *)
+ # Get rid of the `-' at the beginning of $os.
+ os=`echo $os | sed 's/[^-]*-//'`
+ echo Invalid configuration \`"$1"\': system \`"$os"\' not recognized 1>&2
+ exit 1
+ ;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system. Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+ score-*)
+ os=-elf
+ ;;
+ spu-*)
+ os=-elf
+ ;;
+ *-acorn)
+ os=-riscix1.2
+ ;;
+ arm*-rebel)
+ os=-linux
+ ;;
+ arm*-semi)
+ os=-aout
+ ;;
+ c4x-* | tic4x-*)
+ os=-coff
+ ;;
+ c8051-*)
+ os=-elf
+ ;;
+ hexagon-*)
+ os=-elf
+ ;;
+ tic54x-*)
+ os=-coff
+ ;;
+ tic55x-*)
+ os=-coff
+ ;;
+ tic6x-*)
+ os=-coff
+ ;;
+ # This must come before the *-dec entry.
+ pdp10-*)
+ os=-tops20
+ ;;
+ pdp11-*)
+ os=-none
+ ;;
+ *-dec | vax-*)
+ os=-ultrix4.2
+ ;;
+ m68*-apollo)
+ os=-domain
+ ;;
+ i386-sun)
+ os=-sunos4.0.2
+ ;;
+ m68000-sun)
+ os=-sunos3
+ ;;
+ m68*-cisco)
+ os=-aout
+ ;;
+ mep-*)
+ os=-elf
+ ;;
+ mips*-cisco)
+ os=-elf
+ ;;
+ mips*-*)
+ os=-elf
+ ;;
+ or32-*)
+ os=-coff
+ ;;
+ *-tti) # must be before sparc entry or we get the wrong os.
+ os=-sysv3
+ ;;
+ sparc-* | *-sun)
+ os=-sunos4.1.1
+ ;;
+ pru-*)
+ os=-elf
+ ;;
+ *-be)
+ os=-beos
+ ;;
+ *-ibm)
+ os=-aix
+ ;;
+ *-knuth)
+ os=-mmixware
+ ;;
+ *-wec)
+ os=-proelf
+ ;;
+ *-winbond)
+ os=-proelf
+ ;;
+ *-oki)
+ os=-proelf
+ ;;
+ *-hp)
+ os=-hpux
+ ;;
+ *-hitachi)
+ os=-hiux
+ ;;
+ i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+ os=-sysv
+ ;;
+ *-cbm)
+ os=-amigaos
+ ;;
+ *-dg)
+ os=-dgux
+ ;;
+ *-dolphin)
+ os=-sysv3
+ ;;
+ m68k-ccur)
+ os=-rtu
+ ;;
+ m88k-omron*)
+ os=-luna
+ ;;
+ *-next)
+ os=-nextstep
+ ;;
+ *-sequent)
+ os=-ptx
+ ;;
+ *-crds)
+ os=-unos
+ ;;
+ *-ns)
+ os=-genix
+ ;;
+ i370-*)
+ os=-mvs
+ ;;
+ *-gould)
+ os=-sysv
+ ;;
+ *-highlevel)
+ os=-bsd
+ ;;
+ *-encore)
+ os=-bsd
+ ;;
+ *-sgi)
+ os=-irix
+ ;;
+ *-siemens)
+ os=-sysv4
+ ;;
+ *-masscomp)
+ os=-rtu
+ ;;
+ f30[01]-fujitsu | f700-fujitsu)
+ os=-uxpv
+ ;;
+ *-rom68k)
+ os=-coff
+ ;;
+ *-*bug)
+ os=-coff
+ ;;
+ *-apple)
+ os=-macos
+ ;;
+ *-atari*)
+ os=-mint
+ ;;
+ *)
+ os=-none
+ ;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer. We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+ *-unknown)
+ case $os in
+ -riscix*)
+ vendor=acorn
+ ;;
+ -sunos*)
+ vendor=sun
+ ;;
+ -cnk*|-aix*)
+ vendor=ibm
+ ;;
+ -beos*)
+ vendor=be
+ ;;
+ -hpux*)
+ vendor=hp
+ ;;
+ -mpeix*)
+ vendor=hp
+ ;;
+ -hiux*)
+ vendor=hitachi
+ ;;
+ -unos*)
+ vendor=crds
+ ;;
+ -dgux*)
+ vendor=dg
+ ;;
+ -luna*)
+ vendor=omron
+ ;;
+ -genix*)
+ vendor=ns
+ ;;
+ -mvs* | -opened*)
+ vendor=ibm
+ ;;
+ -os400*)
+ vendor=ibm
+ ;;
+ -ptx*)
+ vendor=sequent
+ ;;
+ -tpf*)
+ vendor=ibm
+ ;;
+ -vxsim* | -vxworks* | -windiss*)
+ vendor=wrs
+ ;;
+ -aux*)
+ vendor=apple
+ ;;
+ -hms*)
+ vendor=hitachi
+ ;;
+ -mpw* | -macos*)
+ vendor=apple
+ ;;
+ -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+ vendor=atari
+ ;;
+ -vos*)
+ vendor=stratus
+ ;;
+ esac
+ basic_machine=`echo "$basic_machine" | sed "s/unknown/$vendor/"`
+ ;;
+esac
+
+echo "$basic_machine$os"
+exit
+
+# Local variables:
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
ADDED autosetup/autosetup-find-tclsh
Index: autosetup/autosetup-find-tclsh
==================================================================
--- autosetup/autosetup-find-tclsh
+++ autosetup/autosetup-find-tclsh
@@ -0,0 +1,17 @@
+#!/bin/sh
+# Looks for a suitable tclsh or jimsh in the PATH
+# If not found, builds a bootstrap jimsh from source
+# Prefer $autosetup_tclsh if is set in the environment
+d=`dirname "$0"`
+{ "$d/jimsh0" "$d/autosetup-test-tclsh"; } 2>/dev/null && exit 0
+PATH="$PATH:$d"; export PATH
+for tclsh in $autosetup_tclsh jimsh tclsh tclsh8.5 tclsh8.6; do
+ { $tclsh "$d/autosetup-test-tclsh"; } 2>/dev/null && exit 0
+done
+echo 1>&2 "No installed jimsh or tclsh, building local bootstrap jimsh0"
+for cc in ${CC_FOR_BUILD:-cc} gcc; do
+ { $cc -o "$d/jimsh0" "$d/jimsh0.c"; } 2>/dev/null || continue
+ "$d/jimsh0" "$d/autosetup-test-tclsh" && exit 0
+done
+echo 1>&2 "No working C compiler found. Tried ${CC_FOR_BUILD:-cc} and gcc."
+echo false
ADDED autosetup/autosetup-test-tclsh
Index: autosetup/autosetup-test-tclsh
==================================================================
--- autosetup/autosetup-test-tclsh
+++ autosetup/autosetup-test-tclsh
@@ -0,0 +1,20 @@
+# A small Tcl script to verify that the chosen
+# interpreter works. Sometimes we might e.g. pick up
+# an interpreter for a different arch.
+# Outputs the full path to the interpreter
+
+if {[catch {info version} version] == 0} {
+ # This is Jim Tcl
+ if {$version >= 0.72} {
+ # Ensure that regexp works
+ regexp (a.*?) a
+ puts [info nameofexecutable]
+ exit 0
+ }
+} elseif {[catch {info tclversion} version] == 0} {
+ if {$version >= 8.5 && ![string match 8.5a* [info patchlevel]]} {
+ puts [info nameofexecutable]
+ exit 0
+ }
+}
+exit 1
ADDED autosetup/cc-db.tcl
Index: autosetup/cc-db.tcl
==================================================================
--- autosetup/cc-db.tcl
+++ autosetup/cc-db.tcl
@@ -0,0 +1,15 @@
+# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# @synopsis:
+#
+# The 'cc-db' module provides a knowledge-base of system idiosyncrasies.
+# In general, this module can always be included.
+
+use cc
+
+module-options {}
+
+# openbsd needs sys/types.h to detect some system headers
+cc-include-needs sys/socket.h sys/types.h
+cc-include-needs netinet/in.h sys/types.h
ADDED autosetup/cc-lib.tcl
Index: autosetup/cc-lib.tcl
==================================================================
--- autosetup/cc-lib.tcl
+++ autosetup/cc-lib.tcl
@@ -0,0 +1,189 @@
+# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# @synopsis:
+#
+# Provides a library of common tests on top of the 'cc' module.
+
+use cc
+
+module-options {}
+
+# @cc-check-lfs
+#
+# The equivalent of the 'AC_SYS_LARGEFILE' macro.
+#
+# defines 'HAVE_LFS' if LFS is available,
+# and defines '_FILE_OFFSET_BITS=64' if necessary
+#
+# Returns 1 if 'LFS' is available or 0 otherwise
+#
+proc cc-check-lfs {} {
+ cc-check-includes sys/types.h
+ msg-checking "Checking if -D_FILE_OFFSET_BITS=64 is needed..."
+ set lfs 1
+ if {[msg-quiet cc-with {-includes sys/types.h} {cc-check-sizeof off_t}] == 8} {
+ msg-result no
+ } elseif {[msg-quiet cc-with {-includes sys/types.h -cflags -D_FILE_OFFSET_BITS=64} {cc-check-sizeof off_t}] == 8} {
+ define _FILE_OFFSET_BITS 64
+ msg-result yes
+ } else {
+ set lfs 0
+ msg-result none
+ }
+ define-feature lfs $lfs
+ return $lfs
+}
+
+# @cc-check-endian
+#
+# The equivalent of the 'AC_C_BIGENDIAN' macro.
+#
+# defines 'HAVE_BIG_ENDIAN' if endian is known to be big,
+# or 'HAVE_LITTLE_ENDIAN' if endian is known to be little.
+#
+# Returns 1 if determined, or 0 if not.
+#
+proc cc-check-endian {} {
+ cc-check-includes sys/types.h sys/param.h
+ set rc 0
+ msg-checking "Checking endian..."
+ cc-with {-includes {sys/types.h sys/param.h}} {
+ if {[cctest -code {
+ #if !defined(BIG_ENDIAN) || !defined(BYTE_ORDER)
+ #error unknown
+ #elif BYTE_ORDER != BIG_ENDIAN
+ #error little
+ #endif
+ }]} {
+ define-feature big-endian
+ msg-result "big"
+ set rc 1
+ } elseif {[cctest -code {
+ #if !defined(LITTLE_ENDIAN) || !defined(BYTE_ORDER)
+ #error unknown
+ #elif BYTE_ORDER != LITTLE_ENDIAN
+ #error big
+ #endif
+ }]} {
+ define-feature little-endian
+ msg-result "little"
+ set rc 1
+ } else {
+ msg-result "unknown"
+ }
+ }
+ return $rc
+}
+
+# @cc-check-flags flag ?...?
+#
+# Checks whether the given C/C++ compiler flags can be used. Defines feature
+# names prefixed with 'HAVE_CFLAG' and 'HAVE_CXXFLAG' respectively, and
+# appends working flags to '-cflags' and 'CFLAGS' or 'CXXFLAGS'.
+proc cc-check-flags {args} {
+ set result 1
+ array set opts [cc-get-settings]
+ switch -exact -- $opts(-lang) {
+ c++ {
+ set lang C++
+ set prefix CXXFLAG
+ }
+ c {
+ set lang C
+ set prefix CFLAG
+ }
+ default {
+ autosetup-error "cc-check-flags failed with unknown language: $opts(-lang)"
+ }
+ }
+ foreach flag $args {
+ msg-checking "Checking whether the $lang compiler accepts $flag..."
+ if {[cctest -cflags $flag]} {
+ msg-result yes
+ define-feature $prefix$flag
+ cc-with [list -cflags [list $flag]]
+ define-append ${prefix}S $flag
+ } else {
+ msg-result no
+ set result 0
+ }
+ }
+ return $result
+}
+
+# @cc-check-standards ver ?...?
+#
+# Checks whether the C/C++ compiler accepts one of the specified '-std=$ver'
+# options, and appends the first working one to '-cflags' and 'CFLAGS' or
+# 'CXXFLAGS'.
+proc cc-check-standards {args} {
+ array set opts [cc-get-settings]
+ foreach std $args {
+ if {[cc-check-flags -std=$std]} {
+ return $std
+ }
+ }
+ return ""
+}
+
+# Checks whether $keyword is usable as alignof
+proc cctest_alignof {keyword} {
+ msg-checking "Checking for $keyword..."
+ if {[cctest -code "int x = ${keyword}(char), y = ${keyword}('x');"]} then {
+ msg-result ok
+ define-feature $keyword
+ } else {
+ msg-result "not found"
+ }
+}
+
+# @cc-check-c11
+#
+# Checks for several C11/C++11 extensions and their alternatives. Currently
+# checks for '_Static_assert', '_Alignof', '__alignof__', '__alignof'.
+proc cc-check-c11 {} {
+ msg-checking "Checking for _Static_assert..."
+ if {[cctest -code {
+ _Static_assert(1, "static assertions are available");
+ }]} then {
+ msg-result ok
+ define-feature _Static_assert
+ } else {
+ msg-result "not found"
+ }
+
+ cctest_alignof _Alignof
+ cctest_alignof __alignof__
+ cctest_alignof __alignof
+}
+
+# @cc-check-alloca
+#
+# The equivalent of the 'AC_FUNC_ALLOCA' macro.
+#
+# Checks for the existence of 'alloca'
+# defines 'HAVE_ALLOCA' and returns 1 if it exists.
+proc cc-check-alloca {} {
+ cc-check-some-feature alloca {
+ cctest -includes alloca.h -code { alloca (2 * sizeof (int)); }
+ }
+}
+
+# @cc-signal-return-type
+#
+# The equivalent of the 'AC_TYPE_SIGNAL' macro.
+#
+# defines 'RETSIGTYPE' to 'int' or 'void'.
+proc cc-signal-return-type {} {
+ msg-checking "Checking return type of signal handlers..."
+ cc-with {-includes {sys/types.h signal.h}} {
+ if {[cctest -code {return *(signal (0, 0)) (0) == 1;}]} {
+ set type int
+ } else {
+ set type void
+ }
+ define RETSIGTYPE $type
+ msg-result $type
+ }
+}
ADDED autosetup/cc-shared.tcl
Index: autosetup/cc-shared.tcl
==================================================================
--- autosetup/cc-shared.tcl
+++ autosetup/cc-shared.tcl
@@ -0,0 +1,113 @@
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# @synopsis:
+#
+# The 'cc-shared' module provides support for shared libraries and shared objects.
+# It defines the following variables:
+#
+## SH_CFLAGS Flags to use compiling sources destined for a shared library
+## SH_LDFLAGS Flags to use linking (creating) a shared library
+## SH_SOPREFIX Prefix to use to set the soname when creating a shared library
+## SH_SOFULLPATH Set to 1 if the shared library soname should include the full install path
+## SH_SOEXT Extension for shared libs
+## SH_SOEXTVER Format for versioned shared libs - %s = version
+## SHOBJ_CFLAGS Flags to use compiling sources destined for a shared object
+## SHOBJ_LDFLAGS Flags to use linking a shared object, undefined symbols allowed
+## SHOBJ_LDFLAGS_R - as above, but all symbols must be resolved
+## SH_LINKRPATH Format for setting the rpath when linking an executable, %s = path
+## SH_LINKFLAGS Flags to use linking an executable which will load shared objects
+## LD_LIBRARY_PATH Environment variable which specifies path to shared libraries
+## STRIPLIBFLAGS Arguments to strip a dynamic library
+
+module-options {}
+
+# Defaults: gcc on unix
+define SHOBJ_CFLAGS -fPIC
+define SHOBJ_LDFLAGS -shared
+define SH_CFLAGS -fPIC
+define SH_LDFLAGS -shared
+define SH_LINKFLAGS -rdynamic
+define SH_LINKRPATH "-Wl,-rpath -Wl,%s"
+define SH_SOEXT .so
+define SH_SOEXTVER .so.%s
+define SH_SOPREFIX -Wl,-soname,
+define LD_LIBRARY_PATH LD_LIBRARY_PATH
+define STRIPLIBFLAGS --strip-unneeded
+
+# Note: This is a helpful reference for identifying the toolchain
+# http://sourceforge.net/apps/mediawiki/predef/index.php?title=Compilers
+
+switch -glob -- [get-define host] {
+ *-*-darwin* {
+ define SHOBJ_CFLAGS "-dynamic -fno-common"
+ define SHOBJ_LDFLAGS "-bundle -undefined dynamic_lookup"
+ define SHOBJ_LDFLAGS_R -bundle
+ define SH_CFLAGS -dynamic
+ define SH_LDFLAGS -dynamiclib
+ define SH_LINKFLAGS ""
+ define SH_SOEXT .dylib
+ define SH_SOEXTVER .%s.dylib
+ define SH_SOPREFIX -Wl,-install_name,
+ define SH_SOFULLPATH
+ define LD_LIBRARY_PATH DYLD_LIBRARY_PATH
+ define STRIPLIBFLAGS -x
+ }
+ *-*-ming* - *-*-cygwin - *-*-msys {
+ define SHOBJ_CFLAGS ""
+ define SHOBJ_LDFLAGS -shared
+ define SH_CFLAGS ""
+ define SH_LDFLAGS -shared
+ define SH_LINKRPATH ""
+ define SH_LINKFLAGS ""
+ define SH_SOEXT .dll
+ define SH_SOEXTVER .dll
+ define SH_SOPREFIX ""
+ define LD_LIBRARY_PATH PATH
+ }
+ sparc* {
+ if {[msg-quiet cc-check-decls __SUNPRO_C]} {
+ msg-result "Found sun stdio compiler"
+ # sun stdio compiler
+ # XXX: These haven't been fully tested.
+ define SHOBJ_CFLAGS -KPIC
+ define SHOBJ_LDFLAGS "-G"
+ define SH_CFLAGS -KPIC
+ define SH_LINKFLAGS -Wl,-export-dynamic
+ define SH_SOPREFIX -Wl,-h,
+ }
+ }
+ *-*-solaris* {
+ if {[msg-quiet cc-check-decls __SUNPRO_C]} {
+ msg-result "Found sun stdio compiler"
+ # sun stdio compiler
+ # XXX: These haven't been fully tested.
+ define SHOBJ_CFLAGS -KPIC
+ define SHOBJ_LDFLAGS "-G"
+ define SH_CFLAGS -KPIC
+ define SH_LINKFLAGS -Wl,-export-dynamic
+ define SH_SOPREFIX -Wl,-h,
+ }
+ }
+ *-*-hpux {
+ # XXX: These haven't been tested
+ define SHOBJ_CFLAGS "+O3 +z"
+ define SHOBJ_LDFLAGS -b
+ define SH_CFLAGS +z
+ define SH_LINKFLAGS -Wl,+s
+ define LD_LIBRARY_PATH SHLIB_PATH
+ }
+ *-*-haiku {
+ define SHOBJ_CFLAGS ""
+ define SHOBJ_LDFLAGS -shared
+ define SH_CFLAGS ""
+ define SH_LDFLAGS -shared
+ define SH_LINKFLAGS ""
+ define SH_SOPREFIX ""
+ define LD_LIBRARY_PATH LIBRARY_PATH
+ }
+}
+
+if {![is-defined SHOBJ_LDFLAGS_R]} {
+ define SHOBJ_LDFLAGS_R [get-define SHOBJ_LDFLAGS]
+}
ADDED autosetup/cc.tcl
Index: autosetup/cc.tcl
==================================================================
--- autosetup/cc.tcl
+++ autosetup/cc.tcl
@@ -0,0 +1,733 @@
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# @synopsis:
+#
+# The 'cc' module supports checking various 'features' of the C or C++
+# compiler/linker environment. Common commands are 'cc-check-includes',
+# 'cc-check-types', 'cc-check-functions', 'cc-with', 'make-config-header' and 'make-template'.
+#
+# The following environment variables are used if set:
+#
+## CC - C compiler
+## CXX - C++ compiler
+## CPP - C preprocessor
+## CCACHE - Set to "none" to disable automatic use of ccache
+## CFLAGS - Additional C compiler flags
+## CXXFLAGS - Additional C++ compiler flags
+## LDFLAGS - Additional compiler flags during linking
+## LIBS - Additional libraries to use (for all tests)
+## CROSS - Tool prefix for cross compilation
+#
+# The following variables are defined from the corresponding
+# environment variables if set.
+#
+## CPPFLAGS
+## LINKFLAGS
+## CC_FOR_BUILD
+## LD
+
+use system
+
+module-options {}
+
+# Checks for the existence of the given function by linking
+#
+proc cctest_function {function} {
+ cctest -link 1 -declare "extern void $function\(void);" -code "$function\();"
+}
+
+# Checks for the existence of the given type by compiling
+proc cctest_type {type} {
+ cctest -code "$type _x;"
+}
+
+# Checks for the existence of the given type/structure member.
+# e.g. "struct stat.st_mtime"
+proc cctest_member {struct_member} {
+ # split at the first dot
+ regexp {^([^.]+)[.](.*)$} $struct_member -> struct member
+ cctest -code "static $struct _s; return sizeof(_s.$member);"
+}
+
+# Checks for the existence of the given define by compiling
+#
+proc cctest_define {name} {
+ cctest -code "#ifndef $name\n#error not defined\n#endif"
+}
+
+# Checks for the existence of the given name either as
+# a macro (#define) or an rvalue (such as an enum)
+#
+proc cctest_decl {name} {
+ cctest -code "#ifndef $name\n(void)$name;\n#endif"
+}
+
+# @cc-check-sizeof type ...
+#
+# Checks the size of the given types (between 1 and 32, inclusive).
+# Defines a variable with the size determined, or 'unknown' otherwise.
+# e.g. for type 'long long', defines 'SIZEOF_LONG_LONG'.
+# Returns the size of the last type.
+#
+proc cc-check-sizeof {args} {
+ foreach type $args {
+ msg-checking "Checking for sizeof $type..."
+ set size unknown
+ # Try the most common sizes first
+ foreach i {4 8 1 2 16 32} {
+ if {[cctest -code "static int _x\[sizeof($type) == $i ? 1 : -1\] = { 1 };"]} {
+ set size $i
+ break
+ }
+ }
+ msg-result $size
+ set define [feature-define-name $type SIZEOF_]
+ define $define $size
+ }
+ # Return the last result
+ get-define $define
+}
+
+# Checks for each feature in $list by using the given script.
+#
+# When the script is evaluated, $each is set to the feature
+# being checked, and $extra is set to any additional cctest args.
+#
+# Returns 1 if all features were found, or 0 otherwise.
+proc cc-check-some-feature {list script} {
+ set ret 1
+ foreach each $list {
+ if {![check-feature $each $script]} {
+ set ret 0
+ }
+ }
+ return $ret
+}
+
+# @cc-check-includes includes ...
+#
+# Checks that the given include files can be used.
+proc cc-check-includes {args} {
+ cc-check-some-feature $args {
+ set with {}
+ if {[dict exists $::autosetup(cc-include-deps) $each]} {
+ set deps [dict keys [dict get $::autosetup(cc-include-deps) $each]]
+ msg-quiet cc-check-includes {*}$deps
+ foreach i $deps {
+ if {[have-feature $i]} {
+ lappend with $i
+ }
+ }
+ }
+ if {[llength $with]} {
+ cc-with [list -includes $with] {
+ cctest -includes $each
+ }
+ } else {
+ cctest -includes $each
+ }
+ }
+}
+
+# @cc-include-needs include required ...
+#
+# Ensures that when checking for '$include', a check is first
+# made for each '$required' file, and if found, it is included with '#include'.
+proc cc-include-needs {file args} {
+ foreach depfile $args {
+ dict set ::autosetup(cc-include-deps) $file $depfile 1
+ }
+}
+
+# @cc-check-types type ...
+#
+# Checks that the types exist.
+proc cc-check-types {args} {
+ cc-check-some-feature $args {
+ cctest_type $each
+ }
+}
+
+# @cc-check-defines define ...
+#
+# Checks that the given preprocessor symbols are defined.
+proc cc-check-defines {args} {
+ cc-check-some-feature $args {
+ cctest_define $each
+ }
+}
+
+# @cc-check-decls name ...
+#
+# Checks that each given name is either a preprocessor symbol or rvalue
+# such as an enum. Note that the define used is 'HAVE_DECL_xxx'
+# rather than 'HAVE_xxx'.
+proc cc-check-decls {args} {
+ set ret 1
+ foreach name $args {
+ msg-checking "Checking for $name..."
+ set r [cctest_decl $name]
+ define-feature "decl $name" $r
+ if {$r} {
+ msg-result "ok"
+ } else {
+ msg-result "not found"
+ set ret 0
+ }
+ }
+ return $ret
+}
+
+# @cc-check-functions function ...
+#
+# Checks that the given functions exist (can be linked).
+proc cc-check-functions {args} {
+ cc-check-some-feature $args {
+ cctest_function $each
+ }
+}
+
+# @cc-check-members type.member ...
+#
+# Checks that the given type/structure members exist.
+# A structure member is of the form 'struct stat.st_mtime'.
+proc cc-check-members {args} {
+ cc-check-some-feature $args {
+ cctest_member $each
+ }
+}
+
+# @cc-check-function-in-lib function libs ?otherlibs?
+#
+# Checks that the given function can be found in one of the libs.
+#
+# First checks for no library required, then checks each of the libraries
+# in turn.
+#
+# If the function is found, the feature is defined and 'lib_$function' is defined
+# to '-l$lib' where the function was found, or "" if no library required.
+# In addition, '-l$lib' is prepended to the 'LIBS' define.
+#
+# If additional libraries may be needed for linking, they should be specified
+# with '$extralibs' as '-lotherlib1 -lotherlib2'.
+# These libraries are not automatically added to 'LIBS'.
+#
+# Returns 1 if found or 0 if not.
+#
+proc cc-check-function-in-lib {function libs {otherlibs {}}} {
+ msg-checking "Checking libs for $function..."
+ set found 0
+ cc-with [list -libs $otherlibs] {
+ if {[cctest_function $function]} {
+ msg-result "none needed"
+ define lib_$function ""
+ incr found
+ } else {
+ foreach lib $libs {
+ cc-with [list -libs -l$lib] {
+ if {[cctest_function $function]} {
+ msg-result -l$lib
+ define lib_$function -l$lib
+ # prepend to LIBS
+ define LIBS "-l$lib [get-define LIBS]"
+ incr found
+ break
+ }
+ }
+ }
+ }
+ }
+ define-feature $function $found
+ if {!$found} {
+ msg-result "no"
+ }
+ return $found
+}
+
+# @cc-check-tools tool ...
+#
+# Checks for existence of the given compiler tools, taking
+# into account any cross compilation prefix.
+#
+# For example, when checking for 'ar', first 'AR' is checked on the command
+# line and then in the environment. If not found, '${host}-ar' or
+# simply 'ar' is assumed depending upon whether cross compiling.
+# The path is searched for this executable, and if found 'AR' is defined
+# to the executable name.
+# Note that even when cross compiling, the simple 'ar' is used as a fallback,
+# but a warning is generated. This is necessary for some toolchains.
+#
+# It is an error if the executable is not found.
+#
+proc cc-check-tools {args} {
+ foreach tool $args {
+ set TOOL [string toupper $tool]
+ set exe [get-env $TOOL [get-define cross]$tool]
+ if {[find-executable {*}$exe]} {
+ define $TOOL $exe
+ continue
+ }
+ if {[find-executable {*}$tool]} {
+ msg-result "Warning: Failed to find $exe, falling back to $tool which may be incorrect"
+ define $TOOL $tool
+ continue
+ }
+ user-error "Failed to find $exe"
+ }
+}
+
+# @cc-check-progs prog ...
+#
+# Checks for existence of the given executables on the path.
+#
+# For example, when checking for 'grep', the path is searched for
+# the executable, 'grep', and if found 'GREP' is defined as 'grep'.
+#
+# If the executable is not found, the variable is defined as 'false'.
+# Returns 1 if all programs were found, or 0 otherwise.
+#
+proc cc-check-progs {args} {
+ set failed 0
+ foreach prog $args {
+ set PROG [string toupper $prog]
+ msg-checking "Checking for $prog..."
+ if {![find-executable $prog]} {
+ msg-result no
+ define $PROG false
+ incr failed
+ } else {
+ msg-result ok
+ define $PROG $prog
+ }
+ }
+ expr {!$failed}
+}
+
+# @cc-path-progs prog ...
+#
+# Like cc-check-progs, but sets the define to the full path rather
+# than just the program name.
+#
+proc cc-path-progs {args} {
+ set failed 0
+ foreach prog $args {
+ set PROG [string toupper $prog]
+ msg-checking "Checking for $prog..."
+ set path [find-executable-path $prog]
+ if {$path eq ""} {
+ msg-result no
+ define $PROG false
+ incr failed
+ } else {
+ msg-result $path
+ define $PROG $path
+ }
+ }
+ expr {!$failed}
+}
+
+# Adds the given settings to $::autosetup(ccsettings) and
+# returns the old settings.
+#
+proc cc-add-settings {settings} {
+ if {[llength $settings] % 2} {
+ autosetup-error "settings list is missing a value: $settings"
+ }
+
+ set prev [cc-get-settings]
+ # workaround a bug in some versions of jimsh by forcing
+ # conversion of $prev to a list
+ llength $prev
+
+ array set new $prev
+
+ foreach {name value} $settings {
+ switch -exact -- $name {
+ -cflags - -includes {
+ # These are given as lists
+ lappend new($name) {*}[list-non-empty $value]
+ }
+ -declare {
+ lappend new($name) $value
+ }
+ -libs {
+ # Note that new libraries are added before previous libraries
+ set new($name) [list {*}[list-non-empty $value] {*}$new($name)]
+ }
+ -link - -lang - -nooutput {
+ set new($name) $value
+ }
+ -source - -sourcefile - -code {
+ # XXX: These probably are only valid directly from cctest
+ set new($name) $value
+ }
+ default {
+ autosetup-error "unknown cctest setting: $name"
+ }
+ }
+ }
+
+ cc-store-settings [array get new]
+
+ return $prev
+}
+
+proc cc-store-settings {new} {
+ set ::autosetup(ccsettings) $new
+}
+
+proc cc-get-settings {} {
+ return $::autosetup(ccsettings)
+}
+
+# Similar to cc-add-settings, but each given setting
+# simply replaces the existing value.
+#
+# Returns the previous settings
+proc cc-update-settings {args} {
+ set prev [cc-get-settings]
+ cc-store-settings [dict merge $prev $args]
+ return $prev
+}
+
+# @cc-with settings ?{ script }?
+#
+# Sets the given 'cctest' settings and then runs the tests in '$script'.
+# Note that settings such as '-lang' replace the current setting, while
+# those such as '-includes' are appended to the existing setting.
+#
+# If no script is given, the settings become the default for the remainder
+# of the 'auto.def' file.
+#
+## cc-with {-lang c++} {
+## # This will check with the C++ compiler
+## cc-check-types bool
+## cc-with {-includes signal.h} {
+## # This will check with the C++ compiler, signal.h and any existing includes.
+## ...
+## }
+## # back to just the C++ compiler
+## }
+#
+# The '-libs' setting is special in that newer values are added *before* earlier ones.
+#
+## cc-with {-libs {-lc -lm}} {
+## cc-with {-libs -ldl} {
+## cctest -libs -lsocket ...
+## # libs will be in this order: -lsocket -ldl -lc -lm
+## }
+## }
+proc cc-with {settings args} {
+ if {[llength $args] == 0} {
+ cc-add-settings $settings
+ } elseif {[llength $args] > 1} {
+ autosetup-error "usage: cc-with settings ?script?"
+ } else {
+ set save [cc-add-settings $settings]
+ set rc [catch {uplevel 1 [lindex $args 0]} result info]
+ cc-store-settings $save
+ if {$rc != 0} {
+ return -code [dict get $info -code] $result
+ }
+ return $result
+ }
+}
+
+# @cctest ?settings?
+#
+# Low level C/C++ compiler checker. Compiles and or links a small C program
+# according to the arguments and returns 1 if OK, or 0 if not.
+#
+# Supported settings are:
+#
+## -cflags cflags A list of flags to pass to the compiler
+## -includes list A list of includes, e.g. {stdlib.h stdio.h}
+## -declare code Code to declare before main()
+## -link 1 Don't just compile, link too
+## -lang c|c++ Use the C (default) or C++ compiler
+## -libs liblist List of libraries to link, e.g. {-ldl -lm}
+## -code code Code to compile in the body of main()
+## -source code Compile a complete program. Ignore -includes, -declare and -code
+## -sourcefile file Shorthand for -source [readfile [get-define srcdir]/$file]
+## -nooutput 1 Treat any compiler output (e.g. a warning) as an error
+#
+# Unless '-source' or '-sourcefile' is specified, the C program looks like:
+#
+## #include /* same for remaining includes in the list */
+##
+## declare-code /* any code in -declare, verbatim */
+##
+## int main(void) {
+## code /* any code in -code, verbatim */
+## return 0;
+## }
+#
+# Any failures are recorded in 'config.log'
+#
+proc cctest {args} {
+ set tmp conftest__
+
+ # Easiest way to merge in the settings
+ cc-with $args {
+ array set opts [cc-get-settings]
+ }
+
+ if {[info exists opts(-sourcefile)]} {
+ set opts(-source) [readfile [get-define srcdir]/$opts(-sourcefile) "#error can't find $opts(-sourcefile)"]
+ }
+ if {[info exists opts(-source)]} {
+ set lines $opts(-source)
+ } else {
+ foreach i $opts(-includes) {
+ if {$opts(-code) ne "" && ![feature-checked $i]} {
+ # Compiling real code with an unchecked header file
+ # Quickly (and silently) check for it now
+
+ # Remove all -includes from settings before checking
+ set saveopts [cc-update-settings -includes {}]
+ msg-quiet cc-check-includes $i
+ cc-store-settings $saveopts
+ }
+ if {$opts(-code) eq "" || [have-feature $i]} {
+ lappend source "#include <$i>"
+ }
+ }
+ lappend source {*}$opts(-declare)
+ lappend source "int main(void) {"
+ lappend source $opts(-code)
+ lappend source "return 0;"
+ lappend source "}"
+
+ set lines [join $source \n]
+ }
+
+ # Build the command line
+ set cmdline {}
+ lappend cmdline {*}[get-define CCACHE]
+ switch -exact -- $opts(-lang) {
+ c++ {
+ set src conftest__.cpp
+ lappend cmdline {*}[get-define CXX] {*}[get-define CXXFLAGS]
+ }
+ c {
+ set src conftest__.c
+ lappend cmdline {*}[get-define CC] {*}[get-define CFLAGS]
+ }
+ default {
+ autosetup-error "cctest called with unknown language: $opts(-lang)"
+ }
+ }
+
+ if {$opts(-link)} {
+ lappend cmdline {*}[get-define LDFLAGS]
+ } else {
+ set tmp conftest__.o
+ lappend cmdline -c
+ }
+ lappend cmdline {*}$opts(-cflags) {*}[get-define cc-default-debug ""]
+ lappend cmdline $src -o $tmp {*}$opts(-libs)
+ if {$opts(-link)} {
+ lappend cmdline {*}[get-define LIBS]
+ }
+
+ # At this point we have the complete command line and the
+ # complete source to be compiled. Get the result from cache if
+ # we can
+ if {[info exists ::cc_cache($cmdline,$lines)]} {
+ msg-checking "(cached) "
+ set ok $::cc_cache($cmdline,$lines)
+ if {$::autosetup(debug)} {
+ configlog "From cache (ok=$ok): [join $cmdline]"
+ configlog "============"
+ configlog $lines
+ configlog "============"
+ }
+ return $ok
+ }
+
+ writefile $src $lines\n
+
+ set ok 1
+ set err [catch {exec-with-stderr {*}$cmdline} result errinfo]
+ if {$err || ($opts(-nooutput) && [string length $result])} {
+ configlog "Failed: [join $cmdline]"
+ configlog $result
+ configlog "============"
+ configlog "The failed code was:"
+ configlog $lines
+ configlog "============"
+ set ok 0
+ } elseif {$::autosetup(debug)} {
+ configlog "Compiled OK: [join $cmdline]"
+ configlog "============"
+ configlog $lines
+ configlog "============"
+ }
+ file delete $src
+ file delete $tmp
+
+ # cache it
+ set ::cc_cache($cmdline,$lines) $ok
+
+ return $ok
+}
+
+# @make-autoconf-h outfile ?auto-patterns=HAVE_*? ?bare-patterns=SIZEOF_*?
+#
+# Deprecated - see 'make-config-header'
+proc make-autoconf-h {file {autopatterns {HAVE_*}} {barepatterns {SIZEOF_* HAVE_DECL_*}}} {
+ user-notice "*** make-autoconf-h is deprecated -- use make-config-header instead"
+ make-config-header $file -auto $autopatterns -bare $barepatterns
+}
+
+# @make-config-header outfile ?-auto patternlist? ?-bare patternlist? ?-none patternlist? ?-str patternlist? ...
+#
+# Examines all defined variables which match the given patterns
+# and writes an include file, '$file', which defines each of these.
+# Variables which match '-auto' are output as follows:
+# - defines which have the value '0' are ignored.
+# - defines which have integer values are defined as the integer value.
+# - any other value is defined as a string, e.g. '"value"'
+# Variables which match '-bare' are defined as-is.
+# Variables which match '-str' are defined as a string, e.g. '"value"'
+# Variables which match '-none' are omitted.
+#
+# Note that order is important. The first pattern that matches is selected.
+# Default behaviour is:
+#
+## -bare {SIZEOF_* HAVE_DECL_*} -auto HAVE_* -none *
+#
+# If the file would be unchanged, it is not written.
+proc make-config-header {file args} {
+ set guard _[string toupper [regsub -all {[^a-zA-Z0-9]} [file tail $file] _]]
+ file mkdir [file dirname $file]
+ set lines {}
+ lappend lines "#ifndef $guard"
+ lappend lines "#define $guard"
+
+ # Add some defaults
+ lappend args -bare {SIZEOF_* HAVE_DECL_*} -auto HAVE_*
+
+ foreach n [lsort [dict keys [all-defines]]] {
+ set value [get-define $n]
+ set type [calc-define-output-type $n $args]
+ switch -exact -- $type {
+ -bare {
+ # Just output the value unchanged
+ }
+ -none {
+ continue
+ }
+ -str {
+ set value \"[string map [list \\ \\\\ \" \\\"] $value]\"
+ }
+ -auto {
+ # Automatically determine the type
+ if {$value eq "0"} {
+ lappend lines "/* #undef $n */"
+ continue
+ }
+ if {![string is integer -strict $value]} {
+ set value \"[string map [list \\ \\\\ \" \\\"] $value]\"
+ }
+ }
+ "" {
+ continue
+ }
+ default {
+ autosetup-error "Unknown type in make-config-header: $type"
+ }
+ }
+ lappend lines "#define $n $value"
+ }
+ lappend lines "#endif"
+ set buf [join $lines \n]
+ write-if-changed $file $buf {
+ msg-result "Created $file"
+ }
+}
+
+proc calc-define-output-type {name spec} {
+ foreach {type patterns} $spec {
+ foreach pattern $patterns {
+ if {[string match $pattern $name]} {
+ return $type
+ }
+ }
+ }
+ return ""
+}
+
+# Initialise some values from the environment or commandline or default settings
+foreach i {LDFLAGS LIBS CPPFLAGS LINKFLAGS {CFLAGS "-g -O2"}} {
+ lassign $i var default
+ define $var [get-env $var $default]
+}
+
+if {[env-is-set CC]} {
+ # Set by the user, so don't try anything else
+ set try [list [get-env CC ""]]
+} else {
+ # Try some reasonable options
+ set try [list [get-define cross]cc [get-define cross]gcc]
+}
+define CC [find-an-executable {*}$try]
+if {[get-define CC] eq ""} {
+ user-error "Could not find a C compiler. Tried: [join $try ", "]"
+}
+
+define CPP [get-env CPP "[get-define CC] -E"]
+
+# XXX: Could avoid looking for a C++ compiler until requested
+# Note that if CXX isn't found, we just set it to "false". It might not be needed.
+if {[env-is-set CXX]} {
+ define CXX [find-an-executable -required [get-env CXX ""]]
+} else {
+ define CXX [find-an-executable [get-define cross]c++ [get-define cross]g++ false]
+}
+
+# CXXFLAGS default to CFLAGS if not specified
+define CXXFLAGS [get-env CXXFLAGS [get-define CFLAGS]]
+
+# May need a CC_FOR_BUILD, so look for one
+define CC_FOR_BUILD [find-an-executable [get-env CC_FOR_BUILD ""] cc gcc false]
+
+if {[get-define CC] eq ""} {
+ user-error "Could not find a C compiler. Tried: [join $try ", "]"
+}
+
+define CCACHE [find-an-executable [get-env CCACHE ccache]]
+
+# If any of these are set in the environment, propagate them to the AUTOREMAKE commandline
+foreach i {CC CXX CCACHE CPP CFLAGS CXXFLAGS CXXFLAGS LDFLAGS LIBS CROSS CPPFLAGS LINKFLAGS CC_FOR_BUILD LD} {
+ if {[env-is-set $i]} {
+ # Note: If the variable is set on the command line, get-env will return that value
+ # so the command line will continue to override the environment
+ define-append AUTOREMAKE [quote-if-needed $i=[get-env $i ""]]
+ }
+}
+
+# Initial cctest settings
+cc-store-settings {-cflags {} -includes {} -declare {} -link 0 -lang c -libs {} -code {} -nooutput 0}
+set autosetup(cc-include-deps) {}
+
+msg-result "C compiler...[get-define CCACHE] [get-define CC] [get-define CFLAGS]"
+if {[get-define CXX] ne "false"} {
+ msg-result "C++ compiler...[get-define CCACHE] [get-define CXX] [get-define CXXFLAGS]"
+}
+msg-result "Build C compiler...[get-define CC_FOR_BUILD]"
+
+# On Darwin, we prefer to use -g0 to avoid creating .dSYM directories
+# but some compilers may not support it, so test here.
+switch -glob -- [get-define host] {
+ *-*-darwin* {
+ if {[cctest -cflags {-g0}]} {
+ define cc-default-debug -g0
+ }
+ }
+}
+
+if {![cc-check-includes stdlib.h]} {
+ user-error "Compiler does not work. See config.log"
+}
ADDED autosetup/default.auto
Index: autosetup/default.auto
==================================================================
--- autosetup/default.auto
+++ autosetup/default.auto
@@ -0,0 +1,25 @@
+# Copyright (c) 2012 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Auto-load module for 'make' build system integration
+
+use init
+
+autosetup_add_init_type make {Simple "make" build system} {
+ autosetup_check_create auto.def \
+{# Initial auto.def created by 'autosetup --init=make'
+
+use cc
+
+# Add any user options here
+options {
+}
+
+make-config-header config.h
+make-template Makefile.in
+}
+
+ if {![file exists Makefile.in]} {
+ puts "Note: I don't see Makefile.in. You will probably need to create one."
+ }
+}
ADDED autosetup/jimsh0.c
Index: autosetup/jimsh0.c
==================================================================
--- autosetup/jimsh0.c
+++ autosetup/jimsh0.c
@@ -0,0 +1,22509 @@
+/* This is single source file, bootstrap version of Jim Tcl. See http://jim.tcl.tk/ */
+#define JIM_TCL_COMPAT
+#define JIM_ANSIC
+#define JIM_REGEXP
+#define HAVE_NO_AUTOCONF
+#define _JIMAUTOCONF_H
+#define TCL_LIBRARY "."
+#define jim_ext_bootstrap
+#define jim_ext_aio
+#define jim_ext_readdir
+#define jim_ext_regexp
+#define jim_ext_file
+#define jim_ext_glob
+#define jim_ext_exec
+#define jim_ext_clock
+#define jim_ext_array
+#define jim_ext_stdlib
+#define jim_ext_tclcompat
+#if defined(_MSC_VER)
+#define TCL_PLATFORM_OS "windows"
+#define TCL_PLATFORM_PLATFORM "windows"
+#define TCL_PLATFORM_PATH_SEPARATOR ";"
+#define HAVE_MKDIR_ONE_ARG
+#define HAVE_SYSTEM
+#elif defined(__MINGW32__)
+#define TCL_PLATFORM_OS "mingw"
+#define TCL_PLATFORM_PLATFORM "windows"
+#define TCL_PLATFORM_PATH_SEPARATOR ";"
+#define HAVE_MKDIR_ONE_ARG
+#define HAVE_SYSTEM
+#define HAVE_SYS_TIME_H
+#define HAVE_DIRENT_H
+#define HAVE_UNISTD_H
+#define HAVE_UMASK
+#include
+#ifndef S_IRWXG
+#define S_IRWXG 0
+#endif
+#ifndef S_IRWXO
+#define S_IRWXO 0
+#endif
+#else
+#define TCL_PLATFORM_OS "unknown"
+#define TCL_PLATFORM_PLATFORM "unix"
+#define TCL_PLATFORM_PATH_SEPARATOR ":"
+#ifdef _MINIX
+#define vfork fork
+#define _POSIX_SOURCE
+#else
+#define _GNU_SOURCE
+#endif
+#define HAVE_VFORK
+#define HAVE_WAITPID
+#define HAVE_ISATTY
+#define HAVE_MKSTEMP
+#define HAVE_LINK
+#define HAVE_SYS_TIME_H
+#define HAVE_DIRENT_H
+#define HAVE_UNISTD_H
+#define HAVE_UMASK
+#endif
+#define JIM_VERSION 78
+#ifndef JIM_WIN32COMPAT_H
+#define JIM_WIN32COMPAT_H
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#if defined(_WIN32) || defined(WIN32)
+
+#define HAVE_DLOPEN
+void *dlopen(const char *path, int mode);
+int dlclose(void *handle);
+void *dlsym(void *handle, const char *symbol);
+char *dlerror(void);
+
+
+#if defined(__MINGW32__)
+ #define JIM_SPRINTF_DOUBLE_NEEDS_FIX
+#endif
+
+#ifdef _MSC_VER
+
+
+#if _MSC_VER >= 1000
+ #pragma warning(disable:4146)
+#endif
+
+#include
+#define jim_wide _int64
+#ifndef LLONG_MAX
+ #define LLONG_MAX 9223372036854775807I64
+#endif
+#ifndef LLONG_MIN
+ #define LLONG_MIN (-LLONG_MAX - 1I64)
+#endif
+#define JIM_WIDE_MIN LLONG_MIN
+#define JIM_WIDE_MAX LLONG_MAX
+#define JIM_WIDE_MODIFIER "I64d"
+#define strcasecmp _stricmp
+#define strtoull _strtoui64
+
+#include
+
+struct timeval {
+ long tv_sec;
+ long tv_usec;
+};
+
+int gettimeofday(struct timeval *tv, void *unused);
+
+#define HAVE_OPENDIR
+struct dirent {
+ char *d_name;
+};
+
+typedef struct DIR {
+ long handle;
+ struct _finddata_t info;
+ struct dirent result;
+ char *name;
+} DIR;
+
+DIR *opendir(const char *name);
+int closedir(DIR *dir);
+struct dirent *readdir(DIR *dir);
+
+#endif
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+#ifndef UTF8_UTIL_H
+#define UTF8_UTIL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+#define MAX_UTF8_LEN 4
+
+int utf8_fromunicode(char *p, unsigned uc);
+
+#ifndef JIM_UTF8
+#include
+
+
+#define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B))
+#define utf8_strwidth(S, B) utf8_strlen((S), (B))
+#define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1)
+#define utf8_getchars(CP, C) (*(CP) = (C), 1)
+#define utf8_upper(C) toupper(C)
+#define utf8_title(C) toupper(C)
+#define utf8_lower(C) tolower(C)
+#define utf8_index(C, I) (I)
+#define utf8_charlen(C) 1
+#define utf8_prev_len(S, L) 1
+#define utf8_width(C) 1
+
+#else
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+#ifndef __JIM__H
+#define __JIM__H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include
+#include
+#include
+#include
+#include
+
+
+#ifndef HAVE_NO_AUTOCONF
+#endif
+
+
+
+#ifndef jim_wide
+# ifdef HAVE_LONG_LONG
+# define jim_wide long long
+# ifndef LLONG_MAX
+# define LLONG_MAX 9223372036854775807LL
+# endif
+# ifndef LLONG_MIN
+# define LLONG_MIN (-LLONG_MAX - 1LL)
+# endif
+# define JIM_WIDE_MIN LLONG_MIN
+# define JIM_WIDE_MAX LLONG_MAX
+# else
+# define jim_wide long
+# define JIM_WIDE_MIN LONG_MIN
+# define JIM_WIDE_MAX LONG_MAX
+# endif
+
+
+# ifdef HAVE_LONG_LONG
+# define JIM_WIDE_MODIFIER "lld"
+# else
+# define JIM_WIDE_MODIFIER "ld"
+# define strtoull strtoul
+# endif
+#endif
+
+#define UCHAR(c) ((unsigned char)(c))
+
+
+#define JIM_OK 0
+#define JIM_ERR 1
+#define JIM_RETURN 2
+#define JIM_BREAK 3
+#define JIM_CONTINUE 4
+#define JIM_SIGNAL 5
+#define JIM_EXIT 6
+
+#define JIM_EVAL 7
+
+#define JIM_MAX_CALLFRAME_DEPTH 1000
+#define JIM_MAX_EVAL_DEPTH 2000
+
+
+#define JIM_PRIV_FLAG_SHIFT 20
+
+#define JIM_NONE 0
+#define JIM_ERRMSG 1
+#define JIM_ENUM_ABBREV 2
+#define JIM_UNSHARED 4
+#define JIM_MUSTEXIST 8
+
+
+#define JIM_SUBST_NOVAR 1
+#define JIM_SUBST_NOCMD 2
+#define JIM_SUBST_NOESC 4
+#define JIM_SUBST_FLAG 128
+
+
+#define JIM_CASESENS 0
+#define JIM_NOCASE 1
+
+
+#define JIM_PATH_LEN 1024
+
+
+#define JIM_NOTUSED(V) ((void) V)
+
+#define JIM_LIBPATH "auto_path"
+#define JIM_INTERACTIVE "tcl_interactive"
+
+
+typedef struct Jim_Stack {
+ int len;
+ int maxlen;
+ void **vector;
+} Jim_Stack;
+
+
+typedef struct Jim_HashEntry {
+ void *key;
+ union {
+ void *val;
+ int intval;
+ } u;
+ struct Jim_HashEntry *next;
+} Jim_HashEntry;
+
+typedef struct Jim_HashTableType {
+ unsigned int (*hashFunction)(const void *key);
+ void *(*keyDup)(void *privdata, const void *key);
+ void *(*valDup)(void *privdata, const void *obj);
+ int (*keyCompare)(void *privdata, const void *key1, const void *key2);
+ void (*keyDestructor)(void *privdata, void *key);
+ void (*valDestructor)(void *privdata, void *obj);
+} Jim_HashTableType;
+
+typedef struct Jim_HashTable {
+ Jim_HashEntry **table;
+ const Jim_HashTableType *type;
+ void *privdata;
+ unsigned int size;
+ unsigned int sizemask;
+ unsigned int used;
+ unsigned int collisions;
+ unsigned int uniq;
+} Jim_HashTable;
+
+typedef struct Jim_HashTableIterator {
+ Jim_HashTable *ht;
+ Jim_HashEntry *entry, *nextEntry;
+ int index;
+} Jim_HashTableIterator;
+
+
+#define JIM_HT_INITIAL_SIZE 16
+
+
+#define Jim_FreeEntryVal(ht, entry) \
+ if ((ht)->type->valDestructor) \
+ (ht)->type->valDestructor((ht)->privdata, (entry)->u.val)
+
+#define Jim_SetHashVal(ht, entry, _val_) do { \
+ if ((ht)->type->valDup) \
+ (entry)->u.val = (ht)->type->valDup((ht)->privdata, (_val_)); \
+ else \
+ (entry)->u.val = (_val_); \
+} while(0)
+
+#define Jim_FreeEntryKey(ht, entry) \
+ if ((ht)->type->keyDestructor) \
+ (ht)->type->keyDestructor((ht)->privdata, (entry)->key)
+
+#define Jim_SetHashKey(ht, entry, _key_) do { \
+ if ((ht)->type->keyDup) \
+ (entry)->key = (ht)->type->keyDup((ht)->privdata, (_key_)); \
+ else \
+ (entry)->key = (void *)(_key_); \
+} while(0)
+
+#define Jim_CompareHashKeys(ht, key1, key2) \
+ (((ht)->type->keyCompare) ? \
+ (ht)->type->keyCompare((ht)->privdata, (key1), (key2)) : \
+ (key1) == (key2))
+
+#define Jim_HashKey(ht, key) ((ht)->type->hashFunction(key) + (ht)->uniq)
+
+#define Jim_GetHashEntryKey(he) ((he)->key)
+#define Jim_GetHashEntryVal(he) ((he)->u.val)
+#define Jim_GetHashTableCollisions(ht) ((ht)->collisions)
+#define Jim_GetHashTableSize(ht) ((ht)->size)
+#define Jim_GetHashTableUsed(ht) ((ht)->used)
+
+
+typedef struct Jim_Obj {
+ char *bytes;
+ const struct Jim_ObjType *typePtr;
+ int refCount;
+ int length;
+
+ union {
+
+ jim_wide wideValue;
+
+ int intValue;
+
+ double doubleValue;
+
+ void *ptr;
+
+ struct {
+ void *ptr1;
+ void *ptr2;
+ } twoPtrValue;
+
+ struct {
+ void *ptr;
+ int int1;
+ int int2;
+ } ptrIntValue;
+
+ struct {
+ struct Jim_Var *varPtr;
+ unsigned long callFrameId;
+ int global;
+ } varValue;
+
+ struct {
+ struct Jim_Obj *nsObj;
+ struct Jim_Cmd *cmdPtr;
+ unsigned long procEpoch;
+ } cmdValue;
+
+ struct {
+ struct Jim_Obj **ele;
+ int len;
+ int maxLen;
+ } listValue;
+
+ struct {
+ int maxLength;
+ int charLength;
+ } strValue;
+
+ struct {
+ unsigned long id;
+ struct Jim_Reference *refPtr;
+ } refValue;
+
+ struct {
+ struct Jim_Obj *fileNameObj;
+ int lineNumber;
+ } sourceValue;
+
+ struct {
+ struct Jim_Obj *varNameObjPtr;
+ struct Jim_Obj *indexObjPtr;
+ } dictSubstValue;
+ struct {
+ int line;
+ int argc;
+ } scriptLineValue;
+ } internalRep;
+ struct Jim_Obj *prevObjPtr;
+ struct Jim_Obj *nextObjPtr;
+} Jim_Obj;
+
+
+#define Jim_IncrRefCount(objPtr) \
+ ++(objPtr)->refCount
+#define Jim_DecrRefCount(interp, objPtr) \
+ if (--(objPtr)->refCount <= 0) Jim_FreeObj(interp, objPtr)
+#define Jim_IsShared(objPtr) \
+ ((objPtr)->refCount > 1)
+
+#define Jim_FreeNewObj Jim_FreeObj
+
+
+#define Jim_FreeIntRep(i,o) \
+ if ((o)->typePtr && (o)->typePtr->freeIntRepProc) \
+ (o)->typePtr->freeIntRepProc(i, o)
+
+
+#define Jim_GetIntRepPtr(o) (o)->internalRep.ptr
+
+
+#define Jim_SetIntRepPtr(o, p) \
+ (o)->internalRep.ptr = (p)
+
+
+struct Jim_Interp;
+
+typedef void (Jim_FreeInternalRepProc)(struct Jim_Interp *interp,
+ struct Jim_Obj *objPtr);
+typedef void (Jim_DupInternalRepProc)(struct Jim_Interp *interp,
+ struct Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+typedef void (Jim_UpdateStringProc)(struct Jim_Obj *objPtr);
+
+typedef struct Jim_ObjType {
+ const char *name;
+ Jim_FreeInternalRepProc *freeIntRepProc;
+ Jim_DupInternalRepProc *dupIntRepProc;
+ Jim_UpdateStringProc *updateStringProc;
+ int flags;
+} Jim_ObjType;
+
+
+#define JIM_TYPE_NONE 0
+#define JIM_TYPE_REFERENCES 1
+
+
+
+typedef struct Jim_CallFrame {
+ unsigned long id;
+ int level;
+ struct Jim_HashTable vars;
+ struct Jim_HashTable *staticVars;
+ struct Jim_CallFrame *parent;
+ Jim_Obj *const *argv;
+ int argc;
+ Jim_Obj *procArgsObjPtr;
+ Jim_Obj *procBodyObjPtr;
+ struct Jim_CallFrame *next;
+ Jim_Obj *nsObj;
+ Jim_Obj *fileNameObj;
+ int line;
+ Jim_Stack *localCommands;
+ struct Jim_Obj *tailcallObj;
+ struct Jim_Cmd *tailcallCmd;
+} Jim_CallFrame;
+
+typedef struct Jim_Var {
+ Jim_Obj *objPtr;
+ struct Jim_CallFrame *linkFramePtr;
+} Jim_Var;
+
+
+typedef int Jim_CmdProc(struct Jim_Interp *interp, int argc,
+ Jim_Obj *const *argv);
+typedef void Jim_DelCmdProc(struct Jim_Interp *interp, void *privData);
+
+
+
+typedef struct Jim_Cmd {
+ int inUse;
+ int isproc;
+ struct Jim_Cmd *prevCmd;
+ union {
+ struct {
+
+ Jim_CmdProc *cmdProc;
+ Jim_DelCmdProc *delProc;
+ void *privData;
+ } native;
+ struct {
+
+ Jim_Obj *argListObjPtr;
+ Jim_Obj *bodyObjPtr;
+ Jim_HashTable *staticVars;
+ int argListLen;
+ int reqArity;
+ int optArity;
+ int argsPos;
+ int upcall;
+ struct Jim_ProcArg {
+ Jim_Obj *nameObjPtr;
+ Jim_Obj *defaultObjPtr;
+ } *arglist;
+ Jim_Obj *nsObj;
+ } proc;
+ } u;
+} Jim_Cmd;
+
+
+typedef struct Jim_PrngState {
+ unsigned char sbox[256];
+ unsigned int i, j;
+} Jim_PrngState;
+
+typedef struct Jim_Interp {
+ Jim_Obj *result;
+ int errorLine;
+ Jim_Obj *errorFileNameObj;
+ int addStackTrace;
+ int maxCallFrameDepth;
+ int maxEvalDepth;
+ int evalDepth;
+ int returnCode;
+ int returnLevel;
+ int exitCode;
+ long id;
+ int signal_level;
+ jim_wide sigmask;
+ int (*signal_set_result)(struct Jim_Interp *interp, jim_wide sigmask);
+ Jim_CallFrame *framePtr;
+ Jim_CallFrame *topFramePtr;
+ struct Jim_HashTable commands;
+ unsigned long procEpoch; /* Incremented every time the result
+ of procedures names lookup caching
+ may no longer be valid. */
+ unsigned long callFrameEpoch; /* Incremented every time a new
+ callframe is created. This id is used for the
+ 'ID' field contained in the Jim_CallFrame
+ structure. */
+ int local;
+ Jim_Obj *liveList;
+ Jim_Obj *freeList;
+ Jim_Obj *currentScriptObj;
+ Jim_Obj *nullScriptObj;
+ Jim_Obj *emptyObj;
+ Jim_Obj *trueObj;
+ Jim_Obj *falseObj;
+ unsigned long referenceNextId;
+ struct Jim_HashTable references;
+ unsigned long lastCollectId; /* reference max Id of the last GC
+ execution. It's set to ~0 while the collection
+ is running as sentinel to avoid to recursive
+ calls via the [collect] command inside
+ finalizers. */
+ time_t lastCollectTime;
+ Jim_Obj *stackTrace;
+ Jim_Obj *errorProc;
+ Jim_Obj *unknown;
+ int unknown_called;
+ int errorFlag;
+ void *cmdPrivData; /* Used to pass the private data pointer to
+ a command. It is set to what the user specified
+ via Jim_CreateCommand(). */
+
+ struct Jim_CallFrame *freeFramesList;
+ struct Jim_HashTable assocData;
+ Jim_PrngState *prngState;
+ struct Jim_HashTable packages;
+ Jim_Stack *loadHandles;
+} Jim_Interp;
+
+#define Jim_InterpIncrProcEpoch(i) (i)->procEpoch++
+#define Jim_SetResultString(i,s,l) Jim_SetResult(i, Jim_NewStringObj(i,s,l))
+#define Jim_SetResultInt(i,intval) Jim_SetResult(i, Jim_NewIntObj(i,intval))
+
+#define Jim_SetResultBool(i,b) Jim_SetResultInt(i, b)
+#define Jim_SetEmptyResult(i) Jim_SetResult(i, (i)->emptyObj)
+#define Jim_GetResult(i) ((i)->result)
+#define Jim_CmdPrivData(i) ((i)->cmdPrivData)
+
+#define Jim_SetResult(i,o) do { \
+ Jim_Obj *_resultObjPtr_ = (o); \
+ Jim_IncrRefCount(_resultObjPtr_); \
+ Jim_DecrRefCount(i,(i)->result); \
+ (i)->result = _resultObjPtr_; \
+} while(0)
+
+
+#define Jim_GetId(i) (++(i)->id)
+
+
+#define JIM_REFERENCE_TAGLEN 7 /* The tag is fixed-length, because the reference
+ string representation must be fixed length. */
+typedef struct Jim_Reference {
+ Jim_Obj *objPtr;
+ Jim_Obj *finalizerCmdNamePtr;
+ char tag[JIM_REFERENCE_TAGLEN+1];
+} Jim_Reference;
+
+
+#define Jim_NewEmptyStringObj(i) Jim_NewStringObj(i, "", 0)
+#define Jim_FreeHashTableIterator(iter) Jim_Free(iter)
+
+#define JIM_EXPORT
+
+
+JIM_EXPORT void *Jim_Alloc (int size);
+JIM_EXPORT void *Jim_Realloc(void *ptr, int size);
+JIM_EXPORT void Jim_Free (void *ptr);
+JIM_EXPORT char * Jim_StrDup (const char *s);
+JIM_EXPORT char *Jim_StrDupLen(const char *s, int l);
+
+
+JIM_EXPORT char **Jim_GetEnviron(void);
+JIM_EXPORT void Jim_SetEnviron(char **env);
+JIM_EXPORT int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file);
+
+
+JIM_EXPORT int Jim_Eval(Jim_Interp *interp, const char *script);
+
+
+JIM_EXPORT int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script);
+
+#define Jim_Eval_Named(I, S, F, L) Jim_EvalSource((I), (F), (L), (S))
+
+JIM_EXPORT int Jim_EvalGlobal(Jim_Interp *interp, const char *script);
+JIM_EXPORT int Jim_EvalFile(Jim_Interp *interp, const char *filename);
+JIM_EXPORT int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename);
+JIM_EXPORT int Jim_EvalObj (Jim_Interp *interp, Jim_Obj *scriptObjPtr);
+JIM_EXPORT int Jim_EvalObjVector (Jim_Interp *interp, int objc,
+ Jim_Obj *const *objv);
+JIM_EXPORT int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listObj);
+JIM_EXPORT int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix,
+ int objc, Jim_Obj *const *objv);
+#define Jim_EvalPrefix(i, p, oc, ov) Jim_EvalObjPrefix((i), Jim_NewStringObj((i), (p), -1), (oc), (ov))
+JIM_EXPORT int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj);
+JIM_EXPORT int Jim_SubstObj (Jim_Interp *interp, Jim_Obj *substObjPtr,
+ Jim_Obj **resObjPtrPtr, int flags);
+
+
+JIM_EXPORT void Jim_InitStack(Jim_Stack *stack);
+JIM_EXPORT void Jim_FreeStack(Jim_Stack *stack);
+JIM_EXPORT int Jim_StackLen(Jim_Stack *stack);
+JIM_EXPORT void Jim_StackPush(Jim_Stack *stack, void *element);
+JIM_EXPORT void * Jim_StackPop(Jim_Stack *stack);
+JIM_EXPORT void * Jim_StackPeek(Jim_Stack *stack);
+JIM_EXPORT void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr));
+
+
+JIM_EXPORT int Jim_InitHashTable (Jim_HashTable *ht,
+ const Jim_HashTableType *type, void *privdata);
+JIM_EXPORT void Jim_ExpandHashTable (Jim_HashTable *ht,
+ unsigned int size);
+JIM_EXPORT int Jim_AddHashEntry (Jim_HashTable *ht, const void *key,
+ void *val);
+JIM_EXPORT int Jim_ReplaceHashEntry (Jim_HashTable *ht,
+ const void *key, void *val);
+JIM_EXPORT int Jim_DeleteHashEntry (Jim_HashTable *ht,
+ const void *key);
+JIM_EXPORT int Jim_FreeHashTable (Jim_HashTable *ht);
+JIM_EXPORT Jim_HashEntry * Jim_FindHashEntry (Jim_HashTable *ht,
+ const void *key);
+JIM_EXPORT void Jim_ResizeHashTable (Jim_HashTable *ht);
+JIM_EXPORT Jim_HashTableIterator *Jim_GetHashTableIterator
+ (Jim_HashTable *ht);
+JIM_EXPORT Jim_HashEntry * Jim_NextHashEntry
+ (Jim_HashTableIterator *iter);
+
+
+JIM_EXPORT Jim_Obj * Jim_NewObj (Jim_Interp *interp);
+JIM_EXPORT void Jim_FreeObj (Jim_Interp *interp, Jim_Obj *objPtr);
+JIM_EXPORT void Jim_InvalidateStringRep (Jim_Obj *objPtr);
+JIM_EXPORT Jim_Obj * Jim_DuplicateObj (Jim_Interp *interp,
+ Jim_Obj *objPtr);
+JIM_EXPORT const char * Jim_GetString(Jim_Obj *objPtr,
+ int *lenPtr);
+JIM_EXPORT const char *Jim_String(Jim_Obj *objPtr);
+JIM_EXPORT int Jim_Length(Jim_Obj *objPtr);
+
+
+JIM_EXPORT Jim_Obj * Jim_NewStringObj (Jim_Interp *interp,
+ const char *s, int len);
+JIM_EXPORT Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp,
+ const char *s, int charlen);
+JIM_EXPORT Jim_Obj * Jim_NewStringObjNoAlloc (Jim_Interp *interp,
+ char *s, int len);
+JIM_EXPORT void Jim_AppendString (Jim_Interp *interp, Jim_Obj *objPtr,
+ const char *str, int len);
+JIM_EXPORT void Jim_AppendObj (Jim_Interp *interp, Jim_Obj *objPtr,
+ Jim_Obj *appendObjPtr);
+JIM_EXPORT void Jim_AppendStrings (Jim_Interp *interp,
+ Jim_Obj *objPtr, ...);
+JIM_EXPORT int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr);
+JIM_EXPORT int Jim_StringMatchObj (Jim_Interp *interp, Jim_Obj *patternObjPtr,
+ Jim_Obj *objPtr, int nocase);
+JIM_EXPORT Jim_Obj * Jim_StringRangeObj (Jim_Interp *interp,
+ Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr,
+ Jim_Obj *lastObjPtr);
+JIM_EXPORT Jim_Obj * Jim_FormatString (Jim_Interp *interp,
+ Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv);
+JIM_EXPORT Jim_Obj * Jim_ScanString (Jim_Interp *interp, Jim_Obj *strObjPtr,
+ Jim_Obj *fmtObjPtr, int flags);
+JIM_EXPORT int Jim_CompareStringImmediate (Jim_Interp *interp,
+ Jim_Obj *objPtr, const char *str);
+JIM_EXPORT int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr,
+ Jim_Obj *secondObjPtr, int nocase);
+JIM_EXPORT int Jim_StringCompareLenObj(Jim_Interp *interp, Jim_Obj *firstObjPtr,
+ Jim_Obj *secondObjPtr, int nocase);
+JIM_EXPORT int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr);
+
+
+JIM_EXPORT Jim_Obj * Jim_NewReference (Jim_Interp *interp,
+ Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr);
+JIM_EXPORT Jim_Reference * Jim_GetReference (Jim_Interp *interp,
+ Jim_Obj *objPtr);
+JIM_EXPORT int Jim_SetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr);
+JIM_EXPORT int Jim_GetFinalizer (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr);
+
+
+JIM_EXPORT Jim_Interp * Jim_CreateInterp (void);
+JIM_EXPORT void Jim_FreeInterp (Jim_Interp *i);
+JIM_EXPORT int Jim_GetExitCode (Jim_Interp *interp);
+JIM_EXPORT const char *Jim_ReturnCode(int code);
+JIM_EXPORT void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...);
+
+
+JIM_EXPORT void Jim_RegisterCoreCommands (Jim_Interp *interp);
+JIM_EXPORT int Jim_CreateCommand (Jim_Interp *interp,
+ const char *cmdName, Jim_CmdProc *cmdProc, void *privData,
+ Jim_DelCmdProc *delProc);
+JIM_EXPORT int Jim_DeleteCommand (Jim_Interp *interp,
+ const char *cmdName);
+JIM_EXPORT int Jim_RenameCommand (Jim_Interp *interp,
+ const char *oldName, const char *newName);
+JIM_EXPORT Jim_Cmd * Jim_GetCommand (Jim_Interp *interp,
+ Jim_Obj *objPtr, int flags);
+JIM_EXPORT int Jim_SetVariable (Jim_Interp *interp,
+ Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr);
+JIM_EXPORT int Jim_SetVariableStr (Jim_Interp *interp,
+ const char *name, Jim_Obj *objPtr);
+JIM_EXPORT int Jim_SetGlobalVariableStr (Jim_Interp *interp,
+ const char *name, Jim_Obj *objPtr);
+JIM_EXPORT int Jim_SetVariableStrWithStr (Jim_Interp *interp,
+ const char *name, const char *val);
+JIM_EXPORT int Jim_SetVariableLink (Jim_Interp *interp,
+ Jim_Obj *nameObjPtr, Jim_Obj *targetNameObjPtr,
+ Jim_CallFrame *targetCallFrame);
+JIM_EXPORT Jim_Obj * Jim_MakeGlobalNamespaceName(Jim_Interp *interp,
+ Jim_Obj *nameObjPtr);
+JIM_EXPORT Jim_Obj * Jim_GetVariable (Jim_Interp *interp,
+ Jim_Obj *nameObjPtr, int flags);
+JIM_EXPORT Jim_Obj * Jim_GetGlobalVariable (Jim_Interp *interp,
+ Jim_Obj *nameObjPtr, int flags);
+JIM_EXPORT Jim_Obj * Jim_GetVariableStr (Jim_Interp *interp,
+ const char *name, int flags);
+JIM_EXPORT Jim_Obj * Jim_GetGlobalVariableStr (Jim_Interp *interp,
+ const char *name, int flags);
+JIM_EXPORT int Jim_UnsetVariable (Jim_Interp *interp,
+ Jim_Obj *nameObjPtr, int flags);
+
+
+JIM_EXPORT Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp,
+ Jim_Obj *levelObjPtr);
+
+
+JIM_EXPORT int Jim_Collect (Jim_Interp *interp);
+JIM_EXPORT void Jim_CollectIfNeeded (Jim_Interp *interp);
+
+
+JIM_EXPORT int Jim_GetIndex (Jim_Interp *interp, Jim_Obj *objPtr,
+ int *indexPtr);
+
+
+JIM_EXPORT Jim_Obj * Jim_NewListObj (Jim_Interp *interp,
+ Jim_Obj *const *elements, int len);
+JIM_EXPORT void Jim_ListInsertElements (Jim_Interp *interp,
+ Jim_Obj *listPtr, int listindex, int objc, Jim_Obj *const *objVec);
+JIM_EXPORT void Jim_ListAppendElement (Jim_Interp *interp,
+ Jim_Obj *listPtr, Jim_Obj *objPtr);
+JIM_EXPORT void Jim_ListAppendList (Jim_Interp *interp,
+ Jim_Obj *listPtr, Jim_Obj *appendListPtr);
+JIM_EXPORT int Jim_ListLength (Jim_Interp *interp, Jim_Obj *objPtr);
+JIM_EXPORT int Jim_ListIndex (Jim_Interp *interp, Jim_Obj *listPrt,
+ int listindex, Jim_Obj **objPtrPtr, int seterr);
+JIM_EXPORT Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx);
+JIM_EXPORT int Jim_SetListIndex (Jim_Interp *interp,
+ Jim_Obj *varNamePtr, Jim_Obj *const *indexv, int indexc,
+ Jim_Obj *newObjPtr);
+JIM_EXPORT Jim_Obj * Jim_ConcatObj (Jim_Interp *interp, int objc,
+ Jim_Obj *const *objv);
+JIM_EXPORT Jim_Obj *Jim_ListJoin(Jim_Interp *interp,
+ Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen);
+
+
+JIM_EXPORT Jim_Obj * Jim_NewDictObj (Jim_Interp *interp,
+ Jim_Obj *const *elements, int len);
+JIM_EXPORT int Jim_DictKey (Jim_Interp *interp, Jim_Obj *dictPtr,
+ Jim_Obj *keyPtr, Jim_Obj **objPtrPtr, int flags);
+JIM_EXPORT int Jim_DictKeysVector (Jim_Interp *interp,
+ Jim_Obj *dictPtr, Jim_Obj *const *keyv, int keyc,
+ Jim_Obj **objPtrPtr, int flags);
+JIM_EXPORT int Jim_SetDictKeysVector (Jim_Interp *interp,
+ Jim_Obj *varNamePtr, Jim_Obj *const *keyv, int keyc,
+ Jim_Obj *newObjPtr, int flags);
+JIM_EXPORT int Jim_DictPairs(Jim_Interp *interp,
+ Jim_Obj *dictPtr, Jim_Obj ***objPtrPtr, int *len);
+JIM_EXPORT int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+ Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr);
+
+#define JIM_DICTMATCH_KEYS 0x0001
+#define JIM_DICTMATCH_VALUES 0x002
+
+JIM_EXPORT int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types);
+JIM_EXPORT int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr);
+JIM_EXPORT int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr);
+JIM_EXPORT Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv);
+
+
+JIM_EXPORT int Jim_GetReturnCode (Jim_Interp *interp, Jim_Obj *objPtr,
+ int *intPtr);
+
+
+JIM_EXPORT int Jim_EvalExpression (Jim_Interp *interp,
+ Jim_Obj *exprObjPtr);
+JIM_EXPORT int Jim_GetBoolFromExpr (Jim_Interp *interp,
+ Jim_Obj *exprObjPtr, int *boolPtr);
+
+
+JIM_EXPORT int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr,
+ int *booleanPtr);
+
+
+JIM_EXPORT int Jim_GetWide (Jim_Interp *interp, Jim_Obj *objPtr,
+ jim_wide *widePtr);
+JIM_EXPORT int Jim_GetLong (Jim_Interp *interp, Jim_Obj *objPtr,
+ long *longPtr);
+#define Jim_NewWideObj Jim_NewIntObj
+JIM_EXPORT Jim_Obj * Jim_NewIntObj (Jim_Interp *interp,
+ jim_wide wideValue);
+
+
+JIM_EXPORT int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
+ double *doublePtr);
+JIM_EXPORT void Jim_SetDouble(Jim_Interp *interp, Jim_Obj *objPtr,
+ double doubleValue);
+JIM_EXPORT Jim_Obj * Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue);
+
+
+JIM_EXPORT void Jim_WrongNumArgs (Jim_Interp *interp, int argc,
+ Jim_Obj *const *argv, const char *msg);
+JIM_EXPORT int Jim_GetEnum (Jim_Interp *interp, Jim_Obj *objPtr,
+ const char * const *tablePtr, int *indexPtr, const char *name, int flags);
+JIM_EXPORT int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr,
+ const char *const *tablePtr);
+JIM_EXPORT int Jim_ScriptIsComplete(Jim_Interp *interp,
+ Jim_Obj *scriptObj, char *stateCharPtr);
+
+JIM_EXPORT int Jim_FindByName(const char *name, const char * const array[], size_t len);
+
+
+typedef void (Jim_InterpDeleteProc)(Jim_Interp *interp, void *data);
+JIM_EXPORT void * Jim_GetAssocData(Jim_Interp *interp, const char *key);
+JIM_EXPORT int Jim_SetAssocData(Jim_Interp *interp, const char *key,
+ Jim_InterpDeleteProc *delProc, void *data);
+JIM_EXPORT int Jim_DeleteAssocData(Jim_Interp *interp, const char *key);
+
+
+
+JIM_EXPORT int Jim_PackageProvide (Jim_Interp *interp,
+ const char *name, const char *ver, int flags);
+JIM_EXPORT int Jim_PackageRequire (Jim_Interp *interp,
+ const char *name, int flags);
+
+
+JIM_EXPORT void Jim_MakeErrorMessage (Jim_Interp *interp);
+
+
+JIM_EXPORT int Jim_InteractivePrompt (Jim_Interp *interp);
+JIM_EXPORT void Jim_HistoryLoad(const char *filename);
+JIM_EXPORT void Jim_HistorySave(const char *filename);
+JIM_EXPORT char *Jim_HistoryGetline(Jim_Interp *interp, const char *prompt);
+JIM_EXPORT void Jim_HistorySetCompletion(Jim_Interp *interp, Jim_Obj *commandObj);
+JIM_EXPORT void Jim_HistoryAdd(const char *line);
+JIM_EXPORT void Jim_HistoryShow(void);
+
+
+JIM_EXPORT int Jim_InitStaticExtensions(Jim_Interp *interp);
+JIM_EXPORT int Jim_StringToWide(const char *str, jim_wide *widePtr, int base);
+JIM_EXPORT int Jim_IsBigEndian(void);
+
+#define Jim_CheckSignal(i) ((i)->signal_level && (i)->sigmask)
+
+
+JIM_EXPORT int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName);
+JIM_EXPORT void Jim_FreeLoadHandles(Jim_Interp *interp);
+
+
+JIM_EXPORT FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command);
+
+
+JIM_EXPORT int Jim_IsDict(Jim_Obj *objPtr);
+JIM_EXPORT int Jim_IsList(Jim_Obj *objPtr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+#ifndef JIM_SUBCMD_H
+#define JIM_SUBCMD_H
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define JIM_MODFLAG_HIDDEN 0x0001
+#define JIM_MODFLAG_FULLARGV 0x0002
+
+
+
+typedef int jim_subcmd_function(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
+
+typedef struct {
+ const char *cmd;
+ const char *args;
+ jim_subcmd_function *function;
+ short minargs;
+ short maxargs;
+ unsigned short flags;
+} jim_subcmd_type;
+
+const jim_subcmd_type *
+Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type *command_table, int argc, Jim_Obj *const *argv);
+
+int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
+
+int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type *ct, int argc, Jim_Obj *const *argv);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+#ifndef JIMREGEXP_H
+#define JIMREGEXP_H
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include
+
+typedef struct {
+ int rm_so;
+ int rm_eo;
+} regmatch_t;
+
+
+typedef struct regexp {
+
+ int re_nsub;
+
+
+ int cflags;
+ int err;
+ int regstart;
+ int reganch;
+ int regmust;
+ int regmlen;
+ int *program;
+
+
+ const char *regparse;
+ int p;
+ int proglen;
+
+
+ int eflags;
+ const char *start;
+ const char *reginput;
+ const char *regbol;
+
+
+ regmatch_t *pmatch;
+ int nmatch;
+} regexp;
+
+typedef regexp regex_t;
+
+#define REG_EXTENDED 0
+#define REG_NEWLINE 1
+#define REG_ICASE 2
+
+#define REG_NOTBOL 16
+
+enum {
+ REG_NOERROR,
+ REG_NOMATCH,
+ REG_BADPAT,
+ REG_ERR_NULL_ARGUMENT,
+ REG_ERR_UNKNOWN,
+ REG_ERR_TOO_BIG,
+ REG_ERR_NOMEM,
+ REG_ERR_TOO_MANY_PAREN,
+ REG_ERR_UNMATCHED_PAREN,
+ REG_ERR_UNMATCHED_BRACES,
+ REG_ERR_BAD_COUNT,
+ REG_ERR_JUNK_ON_END,
+ REG_ERR_OPERAND_COULD_BE_EMPTY,
+ REG_ERR_NESTED_COUNT,
+ REG_ERR_INTERNAL,
+ REG_ERR_COUNT_FOLLOWS_NOTHING,
+ REG_ERR_TRAILING_BACKSLASH,
+ REG_ERR_CORRUPTED,
+ REG_ERR_NULL_CHAR,
+ REG_ERR_NUM
+};
+
+int regcomp(regex_t *preg, const char *regex, int cflags);
+int regexec(regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
+size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);
+void regfree(regex_t *preg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+#ifndef JIM_SIGNAL_H
+#define JIM_SIGNAL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+const char *Jim_SignalId(int sig);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+#ifndef JIMIOCOMPAT_H
+#define JIMIOCOMPAT_H
+
+
+#include
+#include
+
+
+void Jim_SetResultErrno(Jim_Interp *interp, const char *msg);
+
+int Jim_OpenForWrite(const char *filename, int append);
+
+int Jim_OpenForRead(const char *filename);
+
+#if defined(__MINGW32__)
+ #ifndef STRICT
+ #define STRICT
+ #endif
+ #define WIN32_LEAN_AND_MEAN
+ #include
+ #include
+ #include
+ #include
+
+ typedef HANDLE pidtype;
+ #define JIM_BAD_PID INVALID_HANDLE_VALUE
+
+ #define JIM_NO_PID INVALID_HANDLE_VALUE
+
+
+ #define WIFEXITED(STATUS) (((STATUS) & 0xff00) == 0)
+ #define WEXITSTATUS(STATUS) ((STATUS) & 0x00ff)
+ #define WIFSIGNALED(STATUS) (((STATUS) & 0xff00) != 0)
+ #define WTERMSIG(STATUS) (((STATUS) >> 8) & 0xff)
+ #define WNOHANG 1
+
+ int Jim_Errno(void);
+ pidtype waitpid(pidtype pid, int *status, int nohang);
+
+ #define HAVE_PIPE
+ #define pipe(P) _pipe((P), 0, O_NOINHERIT)
+
+#elif defined(HAVE_UNISTD_H)
+ #include
+ #include
+ #include
+ #include
+
+ typedef int pidtype;
+ #define Jim_Errno() errno
+ #define JIM_BAD_PID -1
+ #define JIM_NO_PID 0
+
+ #ifndef HAVE_EXECVPE
+ #define execvpe(ARG0, ARGV, ENV) execvp(ARG0, ARGV)
+ #endif
+#endif
+
+#endif
+int Jim_bootstrapInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "bootstrap", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ return Jim_EvalSource(interp, "bootstrap.tcl", 1,
+"\n"
+"\n"
+"proc package {cmd pkg args} {\n"
+" if {$cmd eq \"require\"} {\n"
+" foreach path $::auto_path {\n"
+" set pkgpath $path/$pkg.tcl\n"
+" if {$path eq \".\"} {\n"
+" set pkgpath $pkg.tcl\n"
+" }\n"
+" if {[file exists $pkgpath]} {\n"
+" uplevel #0 [list source $pkgpath]\n"
+" return\n"
+" }\n"
+" }\n"
+" }\n"
+"}\n"
+);
+}
+int Jim_initjimshInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "initjimsh", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ return Jim_EvalSource(interp, "initjimsh.tcl", 1,
+"\n"
+"\n"
+"\n"
+"proc _jimsh_init {} {\n"
+" rename _jimsh_init {}\n"
+" global jim::exe jim::argv0 tcl_interactive auto_path tcl_platform\n"
+"\n"
+"\n"
+" if {[exists jim::argv0]} {\n"
+" if {[string match \"*/*\" $jim::argv0]} {\n"
+" set jim::exe [file join [pwd] $jim::argv0]\n"
+" } else {\n"
+" foreach path [split [env PATH \"\"] $tcl_platform(pathSeparator)] {\n"
+" set exec [file join [pwd] [string map {\\\\ /} $path] $jim::argv0]\n"
+" if {[file executable $exec]} {\n"
+" set jim::exe $exec\n"
+" break\n"
+" }\n"
+" }\n"
+" }\n"
+" }\n"
+"\n"
+"\n"
+" lappend p {*}[split [env JIMLIB {}] $tcl_platform(pathSeparator)]\n"
+" if {[exists jim::exe]} {\n"
+" lappend p [file dirname $jim::exe]\n"
+" }\n"
+" lappend p {*}$auto_path\n"
+" set auto_path $p\n"
+"\n"
+" if {$tcl_interactive && [env HOME {}] ne \"\"} {\n"
+" foreach src {.jimrc jimrc.tcl} {\n"
+" if {[file exists [env HOME]/$src]} {\n"
+" uplevel #0 source [env HOME]/$src\n"
+" break\n"
+" }\n"
+" }\n"
+" }\n"
+" return \"\"\n"
+"}\n"
+"\n"
+"if {$tcl_platform(platform) eq \"windows\"} {\n"
+" set jim::argv0 [string map {\\\\ /} $jim::argv0]\n"
+"}\n"
+"\n"
+"\n"
+"set tcl::autocomplete_commands {info tcl::prefix socket namespace array clock file package string dict signal history}\n"
+"\n"
+"\n"
+"\n"
+"proc tcl::autocomplete {prefix} {\n"
+" if {[set space [string first \" \" $prefix]] != -1} {\n"
+" set cmd [string range $prefix 0 $space-1]\n"
+" if {$cmd in $::tcl::autocomplete_commands || [info channel $cmd] ne \"\"} {\n"
+" set arg [string range $prefix $space+1 end]\n"
+"\n"
+" return [lmap p [$cmd -commands] {\n"
+" if {![string match \"${arg}*\" $p]} continue\n"
+" function \"$cmd $p\"\n"
+" }]\n"
+" }\n"
+" }\n"
+"\n"
+" if {[string match \"source *\" $prefix]} {\n"
+" set path [string range $prefix 7 end]\n"
+" return [lmap p [glob -nocomplain \"${path}*\"] {\n"
+" function \"source $p\"\n"
+" }]\n"
+" }\n"
+"\n"
+" return [lmap p [lsort [info commands $prefix*]] {\n"
+" if {[string match \"* *\" $p]} {\n"
+" continue\n"
+" }\n"
+" function $p\n"
+" }]\n"
+"}\n"
+"\n"
+"_jimsh_init\n"
+);
+}
+int Jim_globInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "glob", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ return Jim_EvalSource(interp, "glob.tcl", 1,
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"package require readdir\n"
+"\n"
+"\n"
+"proc glob.globdir {dir pattern} {\n"
+" if {[file exists $dir/$pattern]} {\n"
+"\n"
+" return [list $pattern]\n"
+" }\n"
+"\n"
+" set result {}\n"
+" set files [readdir $dir]\n"
+" lappend files . ..\n"
+"\n"
+" foreach name $files {\n"
+" if {[string match $pattern $name]} {\n"
+"\n"
+" if {[string index $name 0] eq \".\" && [string index $pattern 0] ne \".\"} {\n"
+" continue\n"
+" }\n"
+" lappend result $name\n"
+" }\n"
+" }\n"
+"\n"
+" return $result\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"proc glob.explode {pattern} {\n"
+" set oldexp {}\n"
+" set newexp {\"\"}\n"
+"\n"
+" while 1 {\n"
+" set oldexp $newexp\n"
+" set newexp {}\n"
+" set ob [string first \\{ $pattern]\n"
+" set cb [string first \\} $pattern]\n"
+"\n"
+" if {$ob < $cb && $ob != -1} {\n"
+" set mid [string range $pattern 0 $ob-1]\n"
+" set subexp [lassign [glob.explode [string range $pattern $ob+1 end]] pattern]\n"
+" if {$pattern eq \"\"} {\n"
+" error \"unmatched open brace in glob pattern\"\n"
+" }\n"
+" set pattern [string range $pattern 1 end]\n"
+"\n"
+" foreach subs $subexp {\n"
+" foreach sub [split $subs ,] {\n"
+" foreach old $oldexp {\n"
+" lappend newexp $old$mid$sub\n"
+" }\n"
+" }\n"
+" }\n"
+" } elseif {$cb != -1} {\n"
+" set suf [string range $pattern 0 $cb-1]\n"
+" set rest [string range $pattern $cb end]\n"
+" break\n"
+" } else {\n"
+" set suf $pattern\n"
+" set rest \"\"\n"
+" break\n"
+" }\n"
+" }\n"
+"\n"
+" foreach old $oldexp {\n"
+" lappend newexp $old$suf\n"
+" }\n"
+" list $rest {*}$newexp\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"proc glob.glob {base pattern} {\n"
+" set dir [file dirname $pattern]\n"
+" if {$pattern eq $dir || $pattern eq \"\"} {\n"
+" return [list [file join $base $dir] $pattern]\n"
+" } elseif {$pattern eq [file tail $pattern]} {\n"
+" set dir \"\"\n"
+" }\n"
+"\n"
+"\n"
+" set dirlist [glob.glob $base $dir]\n"
+" set pattern [file tail $pattern]\n"
+"\n"
+"\n"
+" set result {}\n"
+" foreach {realdir dir} $dirlist {\n"
+" if {![file isdir $realdir]} {\n"
+" continue\n"
+" }\n"
+" if {[string index $dir end] ne \"/\" && $dir ne \"\"} {\n"
+" append dir /\n"
+" }\n"
+" foreach name [glob.globdir $realdir $pattern] {\n"
+" lappend result [file join $realdir $name] $dir$name\n"
+" }\n"
+" }\n"
+" return $result\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"proc glob {args} {\n"
+" set nocomplain 0\n"
+" set base \"\"\n"
+" set tails 0\n"
+"\n"
+" set n 0\n"
+" foreach arg $args {\n"
+" if {[info exists param]} {\n"
+" set $param $arg\n"
+" unset param\n"
+" incr n\n"
+" continue\n"
+" }\n"
+" switch -glob -- $arg {\n"
+" -d* {\n"
+" set switch $arg\n"
+" set param base\n"
+" }\n"
+" -n* {\n"
+" set nocomplain 1\n"
+" }\n"
+" -ta* {\n"
+" set tails 1\n"
+" }\n"
+" -- {\n"
+" incr n\n"
+" break\n"
+" }\n"
+" -* {\n"
+" return -code error \"bad option \\\"$arg\\\": must be -directory, -nocomplain, -tails, or --\"\n"
+" }\n"
+" * {\n"
+" break\n"
+" }\n"
+" }\n"
+" incr n\n"
+" }\n"
+" if {[info exists param]} {\n"
+" return -code error \"missing argument to \\\"$switch\\\"\"\n"
+" }\n"
+" if {[llength $args] <= $n} {\n"
+" return -code error \"wrong # args: should be \\\"glob ?options? pattern ?pattern ...?\\\"\"\n"
+" }\n"
+"\n"
+" set args [lrange $args $n end]\n"
+"\n"
+" set result {}\n"
+" foreach pattern $args {\n"
+" set escpattern [string map {\n"
+" \\\\\\\\ \\x01 \\\\\\{ \\x02 \\\\\\} \\x03 \\\\, \\x04\n"
+" } $pattern]\n"
+" set patexps [lassign [glob.explode $escpattern] rest]\n"
+" if {$rest ne \"\"} {\n"
+" return -code error \"unmatched close brace in glob pattern\"\n"
+" }\n"
+" foreach patexp $patexps {\n"
+" set patexp [string map {\n"
+" \\x01 \\\\\\\\ \\x02 \\{ \\x03 \\} \\x04 ,\n"
+" } $patexp]\n"
+" foreach {realname name} [glob.glob $base $patexp] {\n"
+" incr n\n"
+" if {$tails} {\n"
+" lappend result $name\n"
+" } else {\n"
+" lappend result [file join $base $name]\n"
+" }\n"
+" }\n"
+" }\n"
+" }\n"
+"\n"
+" if {!$nocomplain && [llength $result] == 0} {\n"
+" set s $(([llength $args] > 1) ? \"s\" : \"\")\n"
+" return -code error \"no files matched glob pattern$s \\\"[join $args]\\\"\"\n"
+" }\n"
+"\n"
+" return $result\n"
+"}\n"
+);
+}
+int Jim_stdlibInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "stdlib", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ return Jim_EvalSource(interp, "stdlib.tcl", 1,
+"\n"
+"\n"
+"if {![exists -command ref]} {\n"
+"\n"
+" proc ref {args} {{count 0}} {\n"
+" format %08x [incr count]\n"
+" }\n"
+"}\n"
+"\n"
+"\n"
+"proc lambda {arglist args} {\n"
+" tailcall proc [ref {} function lambda.finalizer] $arglist {*}$args\n"
+"}\n"
+"\n"
+"proc lambda.finalizer {name val} {\n"
+" rename $name {}\n"
+"}\n"
+"\n"
+"\n"
+"proc curry {args} {\n"
+" alias [ref {} function lambda.finalizer] {*}$args\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"proc function {value} {\n"
+" return $value\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"proc stacktrace {{skip 0}} {\n"
+" set trace {}\n"
+" incr skip\n"
+" foreach level [range $skip [info level]] {\n"
+" lappend trace {*}[info frame -$level]\n"
+" }\n"
+" return $trace\n"
+"}\n"
+"\n"
+"\n"
+"proc stackdump {stacktrace} {\n"
+" set lines {}\n"
+" foreach {l f p} [lreverse $stacktrace] {\n"
+" set line {}\n"
+" if {$p ne \"\"} {\n"
+" append line \"in procedure '$p' \"\n"
+" if {$f ne \"\"} {\n"
+" append line \"called \"\n"
+" }\n"
+" }\n"
+" if {$f ne \"\"} {\n"
+" append line \"at file \\\"$f\\\", line $l\"\n"
+" }\n"
+" if {$line ne \"\"} {\n"
+" lappend lines $line\n"
+" }\n"
+" }\n"
+" join $lines \\n\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"proc defer {script} {\n"
+" upvar jim::defer v\n"
+" lappend v $script\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"proc errorInfo {msg {stacktrace \"\"}} {\n"
+" if {$stacktrace eq \"\"} {\n"
+"\n"
+" set stacktrace [info stacktrace]\n"
+"\n"
+" lappend stacktrace {*}[stacktrace 1]\n"
+" }\n"
+" lassign $stacktrace p f l\n"
+" if {$f ne \"\"} {\n"
+" set result \"$f:$l: Error: \"\n"
+" }\n"
+" append result \"$msg\\n\"\n"
+" append result [stackdump $stacktrace]\n"
+"\n"
+"\n"
+" string trim $result\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"proc {info nameofexecutable} {} {\n"
+" if {[exists ::jim::exe]} {\n"
+" return $::jim::exe\n"
+" }\n"
+"}\n"
+"\n"
+"\n"
+"proc {dict update} {&varName args script} {\n"
+" set keys {}\n"
+" foreach {n v} $args {\n"
+" upvar $v var_$v\n"
+" if {[dict exists $varName $n]} {\n"
+" set var_$v [dict get $varName $n]\n"
+" }\n"
+" }\n"
+" catch {uplevel 1 $script} msg opts\n"
+" if {[info exists varName]} {\n"
+" foreach {n v} $args {\n"
+" if {[info exists var_$v]} {\n"
+" dict set varName $n [set var_$v]\n"
+" } else {\n"
+" dict unset varName $n\n"
+" }\n"
+" }\n"
+" }\n"
+" return {*}$opts $msg\n"
+"}\n"
+"\n"
+"proc {dict replace} {dictionary {args {key value}}} {\n"
+" if {[llength ${key value}] % 2} {\n"
+" tailcall {dict replace}\n"
+" }\n"
+" tailcall dict merge $dictionary ${key value}\n"
+"}\n"
+"\n"
+"\n"
+"proc {dict lappend} {varName key {args value}} {\n"
+" upvar $varName dict\n"
+" if {[exists dict] && [dict exists $dict $key]} {\n"
+" set list [dict get $dict $key]\n"
+" }\n"
+" lappend list {*}$value\n"
+" dict set dict $key $list\n"
+"}\n"
+"\n"
+"\n"
+"proc {dict append} {varName key {args value}} {\n"
+" upvar $varName dict\n"
+" if {[exists dict] && [dict exists $dict $key]} {\n"
+" set str [dict get $dict $key]\n"
+" }\n"
+" append str {*}$value\n"
+" dict set dict $key $str\n"
+"}\n"
+"\n"
+"\n"
+"proc {dict incr} {varName key {increment 1}} {\n"
+" upvar $varName dict\n"
+" if {[exists dict] && [dict exists $dict $key]} {\n"
+" set value [dict get $dict $key]\n"
+" }\n"
+" incr value $increment\n"
+" dict set dict $key $value\n"
+"}\n"
+"\n"
+"\n"
+"proc {dict remove} {dictionary {args key}} {\n"
+" foreach k $key {\n"
+" dict unset dictionary $k\n"
+" }\n"
+" return $dictionary\n"
+"}\n"
+"\n"
+"\n"
+"proc {dict for} {vars dictionary script} {\n"
+" if {[llength $vars] != 2} {\n"
+" return -code error \"must have exactly two variable names\"\n"
+" }\n"
+" dict size $dictionary\n"
+" tailcall foreach $vars $dictionary $script\n"
+"}\n"
+);
+}
+int Jim_tclcompatInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "tclcompat", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ return Jim_EvalSource(interp, "tclcompat.tcl", 1,
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"set env [env]\n"
+"\n"
+"\n"
+"if {[info commands stdout] ne \"\"} {\n"
+"\n"
+" foreach p {gets flush close eof seek tell} {\n"
+" proc $p {chan args} {p} {\n"
+" tailcall $chan $p {*}$args\n"
+" }\n"
+" }\n"
+" unset p\n"
+"\n"
+"\n"
+"\n"
+" proc puts {{-nonewline {}} {chan stdout} msg} {\n"
+" if {${-nonewline} ni {-nonewline {}}} {\n"
+" tailcall ${-nonewline} puts $msg\n"
+" }\n"
+" tailcall $chan puts {*}${-nonewline} $msg\n"
+" }\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+" proc read {{-nonewline {}} chan} {\n"
+" if {${-nonewline} ni {-nonewline {}}} {\n"
+" tailcall ${-nonewline} read {*}${chan}\n"
+" }\n"
+" tailcall $chan read {*}${-nonewline}\n"
+" }\n"
+"\n"
+" proc fconfigure {f args} {\n"
+" foreach {n v} $args {\n"
+" switch -glob -- $n {\n"
+" -bl* {\n"
+" $f ndelay $(!$v)\n"
+" }\n"
+" -bu* {\n"
+" $f buffering $v\n"
+" }\n"
+" -tr* {\n"
+"\n"
+" }\n"
+" default {\n"
+" return -code error \"fconfigure: unknown option $n\"\n"
+" }\n"
+" }\n"
+" }\n"
+" }\n"
+"}\n"
+"\n"
+"\n"
+"proc fileevent {args} {\n"
+" tailcall {*}$args\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"proc parray {arrayname {pattern *} {puts puts}} {\n"
+" upvar $arrayname a\n"
+"\n"
+" set max 0\n"
+" foreach name [array names a $pattern]] {\n"
+" if {[string length $name] > $max} {\n"
+" set max [string length $name]\n"
+" }\n"
+" }\n"
+" incr max [string length $arrayname]\n"
+" incr max 2\n"
+" foreach name [lsort [array names a $pattern]] {\n"
+" $puts [format \"%-${max}s = %s\" $arrayname\\($name\\) $a($name)]\n"
+" }\n"
+"}\n"
+"\n"
+"\n"
+"proc {file copy} {{force {}} source target} {\n"
+" try {\n"
+" if {$force ni {{} -force}} {\n"
+" error \"bad option \\\"$force\\\": should be -force\"\n"
+" }\n"
+"\n"
+" set in [open $source rb]\n"
+"\n"
+" if {[file exists $target]} {\n"
+" if {$force eq \"\"} {\n"
+" error \"error copying \\\"$source\\\" to \\\"$target\\\": file already exists\"\n"
+" }\n"
+"\n"
+" if {$source eq $target} {\n"
+" return\n"
+" }\n"
+"\n"
+"\n"
+" file stat $source ss\n"
+" file stat $target ts\n"
+" if {$ss(dev) == $ts(dev) && $ss(ino) == $ts(ino) && $ss(ino)} {\n"
+" return\n"
+" }\n"
+" }\n"
+" set out [open $target wb]\n"
+" $in copyto $out\n"
+" $out close\n"
+" } on error {msg opts} {\n"
+" incr opts(-level)\n"
+" return {*}$opts $msg\n"
+" } finally {\n"
+" catch {$in close}\n"
+" }\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"proc popen {cmd {mode r}} {\n"
+" lassign [pipe] r w\n"
+" try {\n"
+" if {[string match \"w*\" $mode]} {\n"
+" lappend cmd <@$r &\n"
+" set pids [exec {*}$cmd]\n"
+" $r close\n"
+" set f $w\n"
+" } else {\n"
+" lappend cmd >@$w &\n"
+" set pids [exec {*}$cmd]\n"
+" $w close\n"
+" set f $r\n"
+" }\n"
+" lambda {cmd args} {f pids} {\n"
+" if {$cmd eq \"pid\"} {\n"
+" return $pids\n"
+" }\n"
+" if {$cmd eq \"getfd\"} {\n"
+" $f getfd\n"
+" }\n"
+" if {$cmd eq \"close\"} {\n"
+" $f close\n"
+"\n"
+" set retopts {}\n"
+" foreach p $pids {\n"
+" lassign [wait $p] status - rc\n"
+" if {$status eq \"CHILDSTATUS\"} {\n"
+" if {$rc == 0} {\n"
+" continue\n"
+" }\n"
+" set msg \"child process exited abnormally\"\n"
+" } else {\n"
+" set msg \"child killed: received signal\"\n"
+" }\n"
+" set retopts [list -code error -errorcode [list $status $p $rc] $msg]\n"
+" }\n"
+" return {*}$retopts\n"
+" }\n"
+" tailcall $f $cmd {*}$args\n"
+" }\n"
+" } on error {error opts} {\n"
+" $r close\n"
+" $w close\n"
+" error $error\n"
+" }\n"
+"}\n"
+"\n"
+"\n"
+"local proc pid {{channelId {}}} {\n"
+" if {$channelId eq \"\"} {\n"
+" tailcall upcall pid\n"
+" }\n"
+" if {[catch {$channelId tell}]} {\n"
+" return -code error \"can not find channel named \\\"$channelId\\\"\"\n"
+" }\n"
+" if {[catch {$channelId pid} pids]} {\n"
+" return \"\"\n"
+" }\n"
+" return $pids\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"\n"
+"proc try {args} {\n"
+" set catchopts {}\n"
+" while {[string match -* [lindex $args 0]]} {\n"
+" set args [lassign $args opt]\n"
+" if {$opt eq \"--\"} {\n"
+" break\n"
+" }\n"
+" lappend catchopts $opt\n"
+" }\n"
+" if {[llength $args] == 0} {\n"
+" return -code error {wrong # args: should be \"try ?options? script ?argument ...?\"}\n"
+" }\n"
+" set args [lassign $args script]\n"
+" set code [catch -eval {*}$catchopts {uplevel 1 $script} msg opts]\n"
+"\n"
+" set handled 0\n"
+"\n"
+" foreach {on codes vars script} $args {\n"
+" switch -- $on \\\n"
+" on {\n"
+" if {!$handled && ($codes eq \"*\" || [info returncode $code] in $codes)} {\n"
+" lassign $vars msgvar optsvar\n"
+" if {$msgvar ne \"\"} {\n"
+" upvar $msgvar hmsg\n"
+" set hmsg $msg\n"
+" }\n"
+" if {$optsvar ne \"\"} {\n"
+" upvar $optsvar hopts\n"
+" set hopts $opts\n"
+" }\n"
+"\n"
+" set code [catch {uplevel 1 $script} msg opts]\n"
+" incr handled\n"
+" }\n"
+" } \\\n"
+" finally {\n"
+" set finalcode [catch {uplevel 1 $codes} finalmsg finalopts]\n"
+" if {$finalcode} {\n"
+"\n"
+" set code $finalcode\n"
+" set msg $finalmsg\n"
+" set opts $finalopts\n"
+" }\n"
+" break\n"
+" } \\\n"
+" default {\n"
+" return -code error \"try: expected 'on' or 'finally', got '$on'\"\n"
+" }\n"
+" }\n"
+"\n"
+" if {$code} {\n"
+" incr opts(-level)\n"
+" return {*}$opts $msg\n"
+" }\n"
+" return $msg\n"
+"}\n"
+"\n"
+"\n"
+"\n"
+"proc throw {code {msg \"\"}} {\n"
+" return -code $code $msg\n"
+"}\n"
+"\n"
+"\n"
+"proc {file delete force} {path} {\n"
+" foreach e [readdir $path] {\n"
+" file delete -force $path/$e\n"
+" }\n"
+" file delete $path\n"
+"}\n"
+);
+}
+
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include
+#include
+#include
+#include
+#ifdef HAVE_UNISTD_H
+#include
+#include
+#endif
+
+
+#if defined(HAVE_SYS_SOCKET_H) && defined(HAVE_SELECT) && defined(HAVE_NETINET_IN_H) && defined(HAVE_NETDB_H) && defined(HAVE_ARPA_INET_H)
+#include
+#include
+#include
+#include
+#include
+#ifdef HAVE_SYS_UN_H
+#include
+#endif
+#define HAVE_SOCKETS
+#elif defined (__MINGW32__)
+
+#else
+#define JIM_ANSIC
+#endif
+
+#if defined(JIM_SSL)
+#include
+#include
+#endif
+
+#ifdef HAVE_TERMIOS_H
+#endif
+
+
+#define AIO_CMD_LEN 32
+#define AIO_BUF_LEN 256
+
+#ifndef HAVE_FTELLO
+ #define ftello ftell
+#endif
+#ifndef HAVE_FSEEKO
+ #define fseeko fseek
+#endif
+
+#define AIO_KEEPOPEN 1
+
+#if defined(JIM_IPV6)
+#define IPV6 1
+#else
+#define IPV6 0
+#ifndef PF_INET6
+#define PF_INET6 0
+#endif
+#endif
+
+#ifdef JIM_ANSIC
+
+#undef HAVE_PIPE
+#undef HAVE_SOCKETPAIR
+#endif
+
+
+struct AioFile;
+
+typedef struct {
+ int (*writer)(struct AioFile *af, const char *buf, int len);
+ int (*reader)(struct AioFile *af, char *buf, int len);
+ const char *(*getline)(struct AioFile *af, char *buf, int len);
+ int (*error)(const struct AioFile *af);
+ const char *(*strerror)(struct AioFile *af);
+ int (*verify)(struct AioFile *af);
+} JimAioFopsType;
+
+typedef struct AioFile
+{
+ FILE *fp;
+ Jim_Obj *filename;
+ int type;
+ int openFlags;
+ int fd;
+ Jim_Obj *rEvent;
+ Jim_Obj *wEvent;
+ Jim_Obj *eEvent;
+ int addr_family;
+ void *ssl;
+ const JimAioFopsType *fops;
+} AioFile;
+
+static int stdio_writer(struct AioFile *af, const char *buf, int len)
+{
+ return fwrite(buf, 1, len, af->fp);
+}
+
+static int stdio_reader(struct AioFile *af, char *buf, int len)
+{
+ return fread(buf, 1, len, af->fp);
+}
+
+static const char *stdio_getline(struct AioFile *af, char *buf, int len)
+{
+ return fgets(buf, len, af->fp);
+}
+
+static int stdio_error(const AioFile *af)
+{
+ if (!ferror(af->fp)) {
+ return JIM_OK;
+ }
+ clearerr(af->fp);
+
+ if (feof(af->fp) || errno == EAGAIN || errno == EINTR) {
+ return JIM_OK;
+ }
+#ifdef ECONNRESET
+ if (errno == ECONNRESET) {
+ return JIM_OK;
+ }
+#endif
+#ifdef ECONNABORTED
+ if (errno == ECONNABORTED) {
+ return JIM_OK;
+ }
+#endif
+ return JIM_ERR;
+}
+
+static const char *stdio_strerror(struct AioFile *af)
+{
+ return strerror(errno);
+}
+
+static const JimAioFopsType stdio_fops = {
+ stdio_writer,
+ stdio_reader,
+ stdio_getline,
+ stdio_error,
+ stdio_strerror,
+ NULL
+};
+
+
+static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
+static AioFile *JimMakeChannel(Jim_Interp *interp, FILE *fh, int fd, Jim_Obj *filename,
+ const char *hdlfmt, int family, const char *mode);
+
+
+static const char *JimAioErrorString(AioFile *af)
+{
+ if (af && af->fops)
+ return af->fops->strerror(af);
+
+ return strerror(errno);
+}
+
+static void JimAioSetError(Jim_Interp *interp, Jim_Obj *name)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ if (name) {
+ Jim_SetResultFormatted(interp, "%#s: %s", name, JimAioErrorString(af));
+ }
+ else {
+ Jim_SetResultString(interp, JimAioErrorString(af), -1);
+ }
+}
+
+static int JimCheckStreamError(Jim_Interp *interp, AioFile *af)
+{
+ int ret = af->fops->error(af);
+ if (ret) {
+ JimAioSetError(interp, af->filename);
+ }
+ return ret;
+}
+
+static void JimAioDelProc(Jim_Interp *interp, void *privData)
+{
+ AioFile *af = privData;
+
+ JIM_NOTUSED(interp);
+
+ Jim_DecrRefCount(interp, af->filename);
+
+#ifdef jim_ext_eventloop
+
+ Jim_DeleteFileHandler(interp, af->fd, JIM_EVENT_READABLE | JIM_EVENT_WRITABLE | JIM_EVENT_EXCEPTION);
+#endif
+
+#if defined(JIM_SSL)
+ if (af->ssl != NULL) {
+ SSL_free(af->ssl);
+ }
+#endif
+ if (!(af->openFlags & AIO_KEEPOPEN)) {
+ fclose(af->fp);
+ }
+
+ Jim_Free(af);
+}
+
+static int aio_cmd_read(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+ char buf[AIO_BUF_LEN];
+ Jim_Obj *objPtr;
+ int nonewline = 0;
+ jim_wide neededLen = -1;
+
+ if (argc && Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
+ nonewline = 1;
+ argv++;
+ argc--;
+ }
+ if (argc == 1) {
+ if (Jim_GetWide(interp, argv[0], &neededLen) != JIM_OK)
+ return JIM_ERR;
+ if (neededLen < 0) {
+ Jim_SetResultString(interp, "invalid parameter: negative len", -1);
+ return JIM_ERR;
+ }
+ }
+ else if (argc) {
+ return -1;
+ }
+ objPtr = Jim_NewStringObj(interp, NULL, 0);
+ while (neededLen != 0) {
+ int retval;
+ int readlen;
+
+ if (neededLen == -1) {
+ readlen = AIO_BUF_LEN;
+ }
+ else {
+ readlen = (neededLen > AIO_BUF_LEN ? AIO_BUF_LEN : neededLen);
+ }
+ retval = af->fops->reader(af, buf, readlen);
+ if (retval > 0) {
+ Jim_AppendString(interp, objPtr, buf, retval);
+ if (neededLen != -1) {
+ neededLen -= retval;
+ }
+ }
+ if (retval != readlen)
+ break;
+ }
+
+ if (JimCheckStreamError(interp, af)) {
+ Jim_FreeNewObj(interp, objPtr);
+ return JIM_ERR;
+ }
+ if (nonewline) {
+ int len;
+ const char *s = Jim_GetString(objPtr, &len);
+
+ if (len > 0 && s[len - 1] == '\n') {
+ objPtr->length--;
+ objPtr->bytes[objPtr->length] = '\0';
+ }
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+}
+
+AioFile *Jim_AioFile(Jim_Interp *interp, Jim_Obj *command)
+{
+ Jim_Cmd *cmdPtr = Jim_GetCommand(interp, command, JIM_ERRMSG);
+
+
+ if (cmdPtr && !cmdPtr->isproc && cmdPtr->u.native.cmdProc == JimAioSubCmdProc) {
+ return (AioFile *) cmdPtr->u.native.privData;
+ }
+ Jim_SetResultFormatted(interp, "Not a filehandle: \"%#s\"", command);
+ return NULL;
+}
+
+FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *command)
+{
+ AioFile *af;
+
+ af = Jim_AioFile(interp, command);
+ if (af == NULL) {
+ return NULL;
+ }
+
+ return af->fp;
+}
+
+static int aio_cmd_getfd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ fflush(af->fp);
+ Jim_SetResultInt(interp, fileno(af->fp));
+
+ return JIM_OK;
+}
+
+static int aio_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+ jim_wide count = 0;
+ jim_wide maxlen = JIM_WIDE_MAX;
+ AioFile *outf = Jim_AioFile(interp, argv[0]);
+
+ if (outf == NULL) {
+ return JIM_ERR;
+ }
+
+ if (argc == 2) {
+ if (Jim_GetWide(interp, argv[1], &maxlen) != JIM_OK) {
+ return JIM_ERR;
+ }
+ }
+
+ while (count < maxlen) {
+ char ch;
+
+ if (af->fops->reader(af, &ch, 1) != 1) {
+ break;
+ }
+ if (outf->fops->writer(outf, &ch, 1) != 1) {
+ break;
+ }
+ count++;
+ }
+
+ if (JimCheckStreamError(interp, af) || JimCheckStreamError(interp, outf)) {
+ return JIM_ERR;
+ }
+
+ Jim_SetResultInt(interp, count);
+
+ return JIM_OK;
+}
+
+static int aio_cmd_gets(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+ char buf[AIO_BUF_LEN];
+ Jim_Obj *objPtr;
+ int len;
+
+ errno = 0;
+
+ objPtr = Jim_NewStringObj(interp, NULL, 0);
+ while (1) {
+ buf[AIO_BUF_LEN - 1] = '_';
+
+ if (af->fops->getline(af, buf, AIO_BUF_LEN) == NULL)
+ break;
+
+ if (buf[AIO_BUF_LEN - 1] == '\0' && buf[AIO_BUF_LEN - 2] != '\n') {
+ Jim_AppendString(interp, objPtr, buf, AIO_BUF_LEN - 1);
+ }
+ else {
+ len = strlen(buf);
+
+ if (len && (buf[len - 1] == '\n')) {
+
+ len--;
+ }
+
+ Jim_AppendString(interp, objPtr, buf, len);
+ break;
+ }
+ }
+
+ if (JimCheckStreamError(interp, af)) {
+
+ Jim_FreeNewObj(interp, objPtr);
+ return JIM_ERR;
+ }
+
+ if (argc) {
+ if (Jim_SetVariable(interp, argv[0], objPtr) != JIM_OK) {
+ Jim_FreeNewObj(interp, objPtr);
+ return JIM_ERR;
+ }
+
+ len = Jim_Length(objPtr);
+
+ if (len == 0 && feof(af->fp)) {
+
+ len = -1;
+ }
+ Jim_SetResultInt(interp, len);
+ }
+ else {
+ Jim_SetResult(interp, objPtr);
+ }
+ return JIM_OK;
+}
+
+static int aio_cmd_puts(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+ int wlen;
+ const char *wdata;
+ Jim_Obj *strObj;
+
+ if (argc == 2) {
+ if (!Jim_CompareStringImmediate(interp, argv[0], "-nonewline")) {
+ return -1;
+ }
+ strObj = argv[1];
+ }
+ else {
+ strObj = argv[0];
+ }
+
+ wdata = Jim_GetString(strObj, &wlen);
+ if (af->fops->writer(af, wdata, wlen) == wlen) {
+ if (argc == 2 || af->fops->writer(af, "\n", 1) == 1) {
+ return JIM_OK;
+ }
+ }
+ JimAioSetError(interp, af->filename);
+ return JIM_ERR;
+}
+
+static int aio_cmd_isatty(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+#ifdef HAVE_ISATTY
+ AioFile *af = Jim_CmdPrivData(interp);
+ Jim_SetResultInt(interp, isatty(fileno(af->fp)));
+#else
+ Jim_SetResultInt(interp, 0);
+#endif
+
+ return JIM_OK;
+}
+
+
+static int aio_cmd_flush(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ if (fflush(af->fp) == EOF) {
+ JimAioSetError(interp, af->filename);
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+static int aio_cmd_eof(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ Jim_SetResultInt(interp, feof(af->fp));
+ return JIM_OK;
+}
+
+static int aio_cmd_close(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc == 3) {
+#if defined(HAVE_SOCKETS) && defined(HAVE_SHUTDOWN)
+ static const char * const options[] = { "r", "w", NULL };
+ enum { OPT_R, OPT_W, };
+ int option;
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ if (Jim_GetEnum(interp, argv[2], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (shutdown(af->fd, option == OPT_R ? SHUT_RD : SHUT_WR) == 0) {
+ return JIM_OK;
+ }
+ JimAioSetError(interp, NULL);
+#else
+ Jim_SetResultString(interp, "async close not supported", -1);
+#endif
+ return JIM_ERR;
+ }
+
+ return Jim_DeleteCommand(interp, Jim_String(argv[0]));
+}
+
+static int aio_cmd_seek(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+ int orig = SEEK_SET;
+ jim_wide offset;
+
+ if (argc == 2) {
+ if (Jim_CompareStringImmediate(interp, argv[1], "start"))
+ orig = SEEK_SET;
+ else if (Jim_CompareStringImmediate(interp, argv[1], "current"))
+ orig = SEEK_CUR;
+ else if (Jim_CompareStringImmediate(interp, argv[1], "end"))
+ orig = SEEK_END;
+ else {
+ return -1;
+ }
+ }
+ if (Jim_GetWide(interp, argv[0], &offset) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (fseeko(af->fp, offset, orig) == -1) {
+ JimAioSetError(interp, af->filename);
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+static int aio_cmd_tell(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ Jim_SetResultInt(interp, ftello(af->fp));
+ return JIM_OK;
+}
+
+static int aio_cmd_filename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ Jim_SetResult(interp, af->filename);
+ return JIM_OK;
+}
+
+#ifdef O_NDELAY
+static int aio_cmd_ndelay(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ int fmode = fcntl(af->fd, F_GETFL);
+
+ if (argc) {
+ long nb;
+
+ if (Jim_GetLong(interp, argv[0], &nb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (nb) {
+ fmode |= O_NDELAY;
+ }
+ else {
+ fmode &= ~O_NDELAY;
+ }
+ (void)fcntl(af->fd, F_SETFL, fmode);
+ }
+ Jim_SetResultInt(interp, (fmode & O_NONBLOCK) ? 1 : 0);
+ return JIM_OK;
+}
+#endif
+
+
+#ifdef HAVE_FSYNC
+static int aio_cmd_sync(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ fflush(af->fp);
+ fsync(af->fd);
+ return JIM_OK;
+}
+#endif
+
+static int aio_cmd_buffering(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ static const char * const options[] = {
+ "none",
+ "line",
+ "full",
+ NULL
+ };
+ enum
+ {
+ OPT_NONE,
+ OPT_LINE,
+ OPT_FULL,
+ };
+ int option;
+
+ if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
+ return JIM_ERR;
+ }
+ switch (option) {
+ case OPT_NONE:
+ setvbuf(af->fp, NULL, _IONBF, 0);
+ break;
+ case OPT_LINE:
+ setvbuf(af->fp, NULL, _IOLBF, BUFSIZ);
+ break;
+ case OPT_FULL:
+ setvbuf(af->fp, NULL, _IOFBF, BUFSIZ);
+ break;
+ }
+ return JIM_OK;
+}
+
+#ifdef jim_ext_eventloop
+static void JimAioFileEventFinalizer(Jim_Interp *interp, void *clientData)
+{
+ Jim_Obj **objPtrPtr = clientData;
+
+ Jim_DecrRefCount(interp, *objPtrPtr);
+ *objPtrPtr = NULL;
+}
+
+static int JimAioFileEventHandler(Jim_Interp *interp, void *clientData, int mask)
+{
+ Jim_Obj **objPtrPtr = clientData;
+
+ return Jim_EvalObjBackground(interp, *objPtrPtr);
+}
+
+static int aio_eventinfo(Jim_Interp *interp, AioFile * af, unsigned mask, Jim_Obj **scriptHandlerObj,
+ int argc, Jim_Obj * const *argv)
+{
+ if (argc == 0) {
+
+ if (*scriptHandlerObj) {
+ Jim_SetResult(interp, *scriptHandlerObj);
+ }
+ return JIM_OK;
+ }
+
+ if (*scriptHandlerObj) {
+
+ Jim_DeleteFileHandler(interp, af->fd, mask);
+ }
+
+
+ if (Jim_Length(argv[0]) == 0) {
+
+ return JIM_OK;
+ }
+
+
+ Jim_IncrRefCount(argv[0]);
+ *scriptHandlerObj = argv[0];
+
+ Jim_CreateFileHandler(interp, af->fd, mask,
+ JimAioFileEventHandler, scriptHandlerObj, JimAioFileEventFinalizer);
+
+ return JIM_OK;
+}
+
+static int aio_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ return aio_eventinfo(interp, af, JIM_EVENT_READABLE, &af->rEvent, argc, argv);
+}
+
+static int aio_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ return aio_eventinfo(interp, af, JIM_EVENT_WRITABLE, &af->wEvent, argc, argv);
+}
+
+static int aio_cmd_onexception(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ AioFile *af = Jim_CmdPrivData(interp);
+
+ return aio_eventinfo(interp, af, JIM_EVENT_EXCEPTION, &af->eEvent, argc, argv);
+}
+#endif
+
+
+
+
+static const jim_subcmd_type aio_command_table[] = {
+ { "read",
+ "?-nonewline? ?len?",
+ aio_cmd_read,
+ 0,
+ 2,
+
+ },
+ { "copyto",
+ "handle ?size?",
+ aio_cmd_copy,
+ 1,
+ 2,
+
+ },
+ { "getfd",
+ NULL,
+ aio_cmd_getfd,
+ 0,
+ 0,
+
+ },
+ { "gets",
+ "?var?",
+ aio_cmd_gets,
+ 0,
+ 1,
+
+ },
+ { "puts",
+ "?-nonewline? str",
+ aio_cmd_puts,
+ 1,
+ 2,
+
+ },
+ { "isatty",
+ NULL,
+ aio_cmd_isatty,
+ 0,
+ 0,
+
+ },
+ { "flush",
+ NULL,
+ aio_cmd_flush,
+ 0,
+ 0,
+
+ },
+ { "eof",
+ NULL,
+ aio_cmd_eof,
+ 0,
+ 0,
+
+ },
+ { "close",
+ "?r(ead)|w(rite)?",
+ aio_cmd_close,
+ 0,
+ 1,
+ JIM_MODFLAG_FULLARGV,
+
+ },
+ { "seek",
+ "offset ?start|current|end",
+ aio_cmd_seek,
+ 1,
+ 2,
+
+ },
+ { "tell",
+ NULL,
+ aio_cmd_tell,
+ 0,
+ 0,
+
+ },
+ { "filename",
+ NULL,
+ aio_cmd_filename,
+ 0,
+ 0,
+
+ },
+#ifdef O_NDELAY
+ { "ndelay",
+ "?0|1?",
+ aio_cmd_ndelay,
+ 0,
+ 1,
+
+ },
+#endif
+#ifdef HAVE_FSYNC
+ { "sync",
+ NULL,
+ aio_cmd_sync,
+ 0,
+ 0,
+
+ },
+#endif
+ { "buffering",
+ "none|line|full",
+ aio_cmd_buffering,
+ 1,
+ 1,
+
+ },
+#ifdef jim_ext_eventloop
+ { "readable",
+ "?readable-script?",
+ aio_cmd_readable,
+ 0,
+ 1,
+
+ },
+ { "writable",
+ "?writable-script?",
+ aio_cmd_writable,
+ 0,
+ 1,
+
+ },
+ { "onexception",
+ "?exception-script?",
+ aio_cmd_onexception,
+ 0,
+ 1,
+
+ },
+#endif
+ { NULL }
+};
+
+static int JimAioSubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return Jim_CallSubCmd(interp, Jim_ParseSubCmd(interp, aio_command_table, argc, argv), argc, argv);
+}
+
+static int JimAioOpenCommand(Jim_Interp *interp, int argc,
+ Jim_Obj *const *argv)
+{
+ const char *mode;
+
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "filename ?mode?");
+ return JIM_ERR;
+ }
+
+ mode = (argc == 3) ? Jim_String(argv[2]) : "r";
+
+#ifdef jim_ext_tclcompat
+ {
+ const char *filename = Jim_String(argv[1]);
+
+
+ if (*filename == '|') {
+ Jim_Obj *evalObj[3];
+
+ evalObj[0] = Jim_NewStringObj(interp, "::popen", -1);
+ evalObj[1] = Jim_NewStringObj(interp, filename + 1, -1);
+ evalObj[2] = Jim_NewStringObj(interp, mode, -1);
+
+ return Jim_EvalObjVector(interp, 3, evalObj);
+ }
+ }
+#endif
+ return JimMakeChannel(interp, NULL, -1, argv[1], "aio.handle%ld", 0, mode) ? JIM_OK : JIM_ERR;
+}
+
+
+static AioFile *JimMakeChannel(Jim_Interp *interp, FILE *fh, int fd, Jim_Obj *filename,
+ const char *hdlfmt, int family, const char *mode)
+{
+ AioFile *af;
+ char buf[AIO_CMD_LEN];
+ int openFlags = 0;
+
+ snprintf(buf, sizeof(buf), hdlfmt, Jim_GetId(interp));
+
+ if (fh) {
+ openFlags = AIO_KEEPOPEN;
+ }
+
+ snprintf(buf, sizeof(buf), hdlfmt, Jim_GetId(interp));
+ if (!filename) {
+ filename = Jim_NewStringObj(interp, buf, -1);
+ }
+
+ Jim_IncrRefCount(filename);
+
+ if (fh == NULL) {
+ if (fd >= 0) {
+#ifndef JIM_ANSIC
+ fh = fdopen(fd, mode);
+#endif
+ }
+ else
+ fh = fopen(Jim_String(filename), mode);
+
+ if (fh == NULL) {
+ JimAioSetError(interp, filename);
+#ifndef JIM_ANSIC
+ if (fd >= 0) {
+ close(fd);
+ }
+#endif
+ Jim_DecrRefCount(interp, filename);
+ return NULL;
+ }
+ }
+
+
+ af = Jim_Alloc(sizeof(*af));
+ memset(af, 0, sizeof(*af));
+ af->fp = fh;
+ af->filename = filename;
+ af->openFlags = openFlags;
+#ifndef JIM_ANSIC
+ af->fd = fileno(fh);
+#ifdef FD_CLOEXEC
+ if ((openFlags & AIO_KEEPOPEN) == 0) {
+ (void)fcntl(af->fd, F_SETFD, FD_CLOEXEC);
+ }
+#endif
+#endif
+ af->addr_family = family;
+ af->fops = &stdio_fops;
+ af->ssl = NULL;
+
+ Jim_CreateCommand(interp, buf, JimAioSubCmdProc, af, JimAioDelProc);
+
+ Jim_SetResult(interp, Jim_MakeGlobalNamespaceName(interp, Jim_NewStringObj(interp, buf, -1)));
+
+ return af;
+}
+
+#if defined(HAVE_PIPE) || (defined(HAVE_SOCKETPAIR) && defined(HAVE_SYS_UN_H))
+static int JimMakeChannelPair(Jim_Interp *interp, int p[2], Jim_Obj *filename,
+ const char *hdlfmt, int family, const char *mode[2])
+{
+ if (JimMakeChannel(interp, NULL, p[0], filename, hdlfmt, family, mode[0])) {
+ Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
+ Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
+ if (JimMakeChannel(interp, NULL, p[1], filename, hdlfmt, family, mode[1])) {
+ Jim_ListAppendElement(interp, objPtr, Jim_GetResult(interp));
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+ }
+
+
+ close(p[0]);
+ close(p[1]);
+ JimAioSetError(interp, NULL);
+ return JIM_ERR;
+}
+#endif
+
+#ifdef HAVE_PIPE
+static int JimAioPipeCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int p[2];
+ static const char *mode[2] = { "r", "w" };
+
+ if (argc != 1) {
+ Jim_WrongNumArgs(interp, 1, argv, "");
+ return JIM_ERR;
+ }
+
+ if (pipe(p) != 0) {
+ JimAioSetError(interp, NULL);
+ return JIM_ERR;
+ }
+
+ return JimMakeChannelPair(interp, p, argv[0], "aio.pipe%ld", 0, mode);
+}
+#endif
+
+
+
+int Jim_aioInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "aio", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+#if defined(JIM_SSL)
+ Jim_CreateCommand(interp, "load_ssl_certs", JimAioLoadSSLCertsCommand, NULL, NULL);
+#endif
+
+ Jim_CreateCommand(interp, "open", JimAioOpenCommand, NULL, NULL);
+#ifdef HAVE_SOCKETS
+ Jim_CreateCommand(interp, "socket", JimAioSockCommand, NULL, NULL);
+#endif
+#ifdef HAVE_PIPE
+ Jim_CreateCommand(interp, "pipe", JimAioPipeCommand, NULL, NULL);
+#endif
+
+
+ JimMakeChannel(interp, stdin, -1, NULL, "stdin", 0, "r");
+ JimMakeChannel(interp, stdout, -1, NULL, "stdout", 0, "w");
+ JimMakeChannel(interp, stderr, -1, NULL, "stderr", 0, "w");
+
+ return JIM_OK;
+}
+
+#include
+#include
+#include
+
+
+#ifdef HAVE_DIRENT_H
+#include
+#endif
+
+int Jim_ReaddirCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *dirPath;
+ DIR *dirPtr;
+ struct dirent *entryPtr;
+ int nocomplain = 0;
+
+ if (argc == 3 && Jim_CompareStringImmediate(interp, argv[1], "-nocomplain")) {
+ nocomplain = 1;
+ }
+ if (argc != 2 && !nocomplain) {
+ Jim_WrongNumArgs(interp, 1, argv, "?-nocomplain? dirPath");
+ return JIM_ERR;
+ }
+
+ dirPath = Jim_String(argv[1 + nocomplain]);
+
+ dirPtr = opendir(dirPath);
+ if (dirPtr == NULL) {
+ if (nocomplain) {
+ return JIM_OK;
+ }
+ Jim_SetResultString(interp, strerror(errno), -1);
+ return JIM_ERR;
+ }
+ else {
+ Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+
+ while ((entryPtr = readdir(dirPtr)) != NULL) {
+ if (entryPtr->d_name[0] == '.') {
+ if (entryPtr->d_name[1] == '\0') {
+ continue;
+ }
+ if ((entryPtr->d_name[1] == '.') && (entryPtr->d_name[2] == '\0'))
+ continue;
+ }
+ Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, entryPtr->d_name, -1));
+ }
+ closedir(dirPtr);
+
+ Jim_SetResult(interp, listObj);
+
+ return JIM_OK;
+ }
+}
+
+int Jim_readdirInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "readdir", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ Jim_CreateCommand(interp, "readdir", Jim_ReaddirCmd, NULL, NULL);
+ return JIM_OK;
+}
+
+#include
+#include
+
+#if defined(JIM_REGEXP)
+#else
+ #include
+#endif
+
+static void FreeRegexpInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ regfree(objPtr->internalRep.ptrIntValue.ptr);
+ Jim_Free(objPtr->internalRep.ptrIntValue.ptr);
+}
+
+static const Jim_ObjType regexpObjType = {
+ "regexp",
+ FreeRegexpInternalRep,
+ NULL,
+ NULL,
+ JIM_TYPE_NONE
+};
+
+static regex_t *SetRegexpFromAny(Jim_Interp *interp, Jim_Obj *objPtr, unsigned flags)
+{
+ regex_t *compre;
+ const char *pattern;
+ int ret;
+
+
+ if (objPtr->typePtr == ®expObjType &&
+ objPtr->internalRep.ptrIntValue.ptr && objPtr->internalRep.ptrIntValue.int1 == flags) {
+
+ return objPtr->internalRep.ptrIntValue.ptr;
+ }
+
+
+
+
+ pattern = Jim_String(objPtr);
+ compre = Jim_Alloc(sizeof(regex_t));
+
+ if ((ret = regcomp(compre, pattern, REG_EXTENDED | flags)) != 0) {
+ char buf[100];
+
+ regerror(ret, compre, buf, sizeof(buf));
+ Jim_SetResultFormatted(interp, "couldn't compile regular expression pattern: %s", buf);
+ regfree(compre);
+ Jim_Free(compre);
+ return NULL;
+ }
+
+ Jim_FreeIntRep(interp, objPtr);
+
+ objPtr->typePtr = ®expObjType;
+ objPtr->internalRep.ptrIntValue.int1 = flags;
+ objPtr->internalRep.ptrIntValue.ptr = compre;
+
+ return compre;
+}
+
+int Jim_RegexpCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int opt_indices = 0;
+ int opt_all = 0;
+ int opt_inline = 0;
+ regex_t *regex;
+ int match, i, j;
+ int offset = 0;
+ regmatch_t *pmatch = NULL;
+ int source_len;
+ int result = JIM_OK;
+ const char *pattern;
+ const char *source_str;
+ int num_matches = 0;
+ int num_vars;
+ Jim_Obj *resultListObj = NULL;
+ int regcomp_flags = 0;
+ int eflags = 0;
+ int option;
+ enum {
+ OPT_INDICES, OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_INLINE, OPT_START, OPT_END
+ };
+ static const char * const options[] = {
+ "-indices", "-nocase", "-line", "-all", "-inline", "-start", "--", NULL
+ };
+
+ if (argc < 3) {
+ wrongNumArgs:
+ Jim_WrongNumArgs(interp, 1, argv,
+ "?-switch ...? exp string ?matchVar? ?subMatchVar ...?");
+ return JIM_ERR;
+ }
+
+ for (i = 1; i < argc; i++) {
+ const char *opt = Jim_String(argv[i]);
+
+ if (*opt != '-') {
+ break;
+ }
+ if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (option == OPT_END) {
+ i++;
+ break;
+ }
+ switch (option) {
+ case OPT_INDICES:
+ opt_indices = 1;
+ break;
+
+ case OPT_NOCASE:
+ regcomp_flags |= REG_ICASE;
+ break;
+
+ case OPT_LINE:
+ regcomp_flags |= REG_NEWLINE;
+ break;
+
+ case OPT_ALL:
+ opt_all = 1;
+ break;
+
+ case OPT_INLINE:
+ opt_inline = 1;
+ break;
+
+ case OPT_START:
+ if (++i == argc) {
+ goto wrongNumArgs;
+ }
+ if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
+ return JIM_ERR;
+ }
+ break;
+ }
+ }
+ if (argc - i < 2) {
+ goto wrongNumArgs;
+ }
+
+ regex = SetRegexpFromAny(interp, argv[i], regcomp_flags);
+ if (!regex) {
+ return JIM_ERR;
+ }
+
+ pattern = Jim_String(argv[i]);
+ source_str = Jim_GetString(argv[i + 1], &source_len);
+
+ num_vars = argc - i - 2;
+
+ if (opt_inline) {
+ if (num_vars) {
+ Jim_SetResultString(interp, "regexp match variables not allowed when using -inline",
+ -1);
+ result = JIM_ERR;
+ goto done;
+ }
+ num_vars = regex->re_nsub + 1;
+ }
+
+ pmatch = Jim_Alloc((num_vars + 1) * sizeof(*pmatch));
+
+ if (offset) {
+ if (offset < 0) {
+ offset += source_len + 1;
+ }
+ if (offset > source_len) {
+ source_str += source_len;
+ }
+ else if (offset > 0) {
+ source_str += offset;
+ }
+ eflags |= REG_NOTBOL;
+ }
+
+ if (opt_inline) {
+ resultListObj = Jim_NewListObj(interp, NULL, 0);
+ }
+
+ next_match:
+ match = regexec(regex, source_str, num_vars + 1, pmatch, eflags);
+ if (match >= REG_BADPAT) {
+ char buf[100];
+
+ regerror(match, regex, buf, sizeof(buf));
+ Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
+ result = JIM_ERR;
+ goto done;
+ }
+
+ if (match == REG_NOMATCH) {
+ goto done;
+ }
+
+ num_matches++;
+
+ if (opt_all && !opt_inline) {
+
+ goto try_next_match;
+ }
+
+
+ j = 0;
+ for (i += 2; opt_inline ? j < num_vars : i < argc; i++, j++) {
+ Jim_Obj *resultObj;
+
+ if (opt_indices) {
+ resultObj = Jim_NewListObj(interp, NULL, 0);
+ }
+ else {
+ resultObj = Jim_NewStringObj(interp, "", 0);
+ }
+
+ if (pmatch[j].rm_so == -1) {
+ if (opt_indices) {
+ Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
+ Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp, -1));
+ }
+ }
+ else {
+ int len = pmatch[j].rm_eo - pmatch[j].rm_so;
+
+ if (opt_indices) {
+ Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp,
+ offset + pmatch[j].rm_so));
+ Jim_ListAppendElement(interp, resultObj, Jim_NewIntObj(interp,
+ offset + pmatch[j].rm_so + len - 1));
+ }
+ else {
+ Jim_AppendString(interp, resultObj, source_str + pmatch[j].rm_so, len);
+ }
+ }
+
+ if (opt_inline) {
+ Jim_ListAppendElement(interp, resultListObj, resultObj);
+ }
+ else {
+
+ result = Jim_SetVariable(interp, argv[i], resultObj);
+
+ if (result != JIM_OK) {
+ Jim_FreeObj(interp, resultObj);
+ break;
+ }
+ }
+ }
+
+ try_next_match:
+ if (opt_all && (pattern[0] != '^' || (regcomp_flags & REG_NEWLINE)) && *source_str) {
+ if (pmatch[0].rm_eo) {
+ offset += pmatch[0].rm_eo;
+ source_str += pmatch[0].rm_eo;
+ }
+ else {
+ source_str++;
+ offset++;
+ }
+ if (*source_str) {
+ eflags = REG_NOTBOL;
+ goto next_match;
+ }
+ }
+
+ done:
+ if (result == JIM_OK) {
+ if (opt_inline) {
+ Jim_SetResult(interp, resultListObj);
+ }
+ else {
+ Jim_SetResultInt(interp, num_matches);
+ }
+ }
+
+ Jim_Free(pmatch);
+ return result;
+}
+
+#define MAX_SUB_MATCHES 50
+
+int Jim_RegsubCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int regcomp_flags = 0;
+ int regexec_flags = 0;
+ int opt_all = 0;
+ int offset = 0;
+ regex_t *regex;
+ const char *p;
+ int result;
+ regmatch_t pmatch[MAX_SUB_MATCHES + 1];
+ int num_matches = 0;
+
+ int i, j, n;
+ Jim_Obj *varname;
+ Jim_Obj *resultObj;
+ const char *source_str;
+ int source_len;
+ const char *replace_str;
+ int replace_len;
+ const char *pattern;
+ int option;
+ enum {
+ OPT_NOCASE, OPT_LINE, OPT_ALL, OPT_START, OPT_END
+ };
+ static const char * const options[] = {
+ "-nocase", "-line", "-all", "-start", "--", NULL
+ };
+
+ if (argc < 4) {
+ wrongNumArgs:
+ Jim_WrongNumArgs(interp, 1, argv,
+ "?-switch ...? exp string subSpec ?varName?");
+ return JIM_ERR;
+ }
+
+ for (i = 1; i < argc; i++) {
+ const char *opt = Jim_String(argv[i]);
+
+ if (*opt != '-') {
+ break;
+ }
+ if (Jim_GetEnum(interp, argv[i], options, &option, "switch", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (option == OPT_END) {
+ i++;
+ break;
+ }
+ switch (option) {
+ case OPT_NOCASE:
+ regcomp_flags |= REG_ICASE;
+ break;
+
+ case OPT_LINE:
+ regcomp_flags |= REG_NEWLINE;
+ break;
+
+ case OPT_ALL:
+ opt_all = 1;
+ break;
+
+ case OPT_START:
+ if (++i == argc) {
+ goto wrongNumArgs;
+ }
+ if (Jim_GetIndex(interp, argv[i], &offset) != JIM_OK) {
+ return JIM_ERR;
+ }
+ break;
+ }
+ }
+ if (argc - i != 3 && argc - i != 4) {
+ goto wrongNumArgs;
+ }
+
+ regex = SetRegexpFromAny(interp, argv[i], regcomp_flags);
+ if (!regex) {
+ return JIM_ERR;
+ }
+ pattern = Jim_String(argv[i]);
+
+ source_str = Jim_GetString(argv[i + 1], &source_len);
+ replace_str = Jim_GetString(argv[i + 2], &replace_len);
+ varname = argv[i + 3];
+
+
+ resultObj = Jim_NewStringObj(interp, "", 0);
+
+ if (offset) {
+ if (offset < 0) {
+ offset += source_len + 1;
+ }
+ if (offset > source_len) {
+ offset = source_len;
+ }
+ else if (offset < 0) {
+ offset = 0;
+ }
+ }
+
+
+ Jim_AppendString(interp, resultObj, source_str, offset);
+
+
+ n = source_len - offset;
+ p = source_str + offset;
+ do {
+ int match = regexec(regex, p, MAX_SUB_MATCHES, pmatch, regexec_flags);
+
+ if (match >= REG_BADPAT) {
+ char buf[100];
+
+ regerror(match, regex, buf, sizeof(buf));
+ Jim_SetResultFormatted(interp, "error while matching pattern: %s", buf);
+ return JIM_ERR;
+ }
+ if (match == REG_NOMATCH) {
+ break;
+ }
+
+ num_matches++;
+
+ Jim_AppendString(interp, resultObj, p, pmatch[0].rm_so);
+
+
+ for (j = 0; j < replace_len; j++) {
+ int idx;
+ int c = replace_str[j];
+
+ if (c == '&') {
+ idx = 0;
+ }
+ else if (c == '\\' && j < replace_len) {
+ c = replace_str[++j];
+ if ((c >= '0') && (c <= '9')) {
+ idx = c - '0';
+ }
+ else if ((c == '\\') || (c == '&')) {
+ Jim_AppendString(interp, resultObj, replace_str + j, 1);
+ continue;
+ }
+ else {
+ Jim_AppendString(interp, resultObj, replace_str + j - 1, (j == replace_len) ? 1 : 2);
+ continue;
+ }
+ }
+ else {
+ Jim_AppendString(interp, resultObj, replace_str + j, 1);
+ continue;
+ }
+ if ((idx < MAX_SUB_MATCHES) && pmatch[idx].rm_so != -1 && pmatch[idx].rm_eo != -1) {
+ Jim_AppendString(interp, resultObj, p + pmatch[idx].rm_so,
+ pmatch[idx].rm_eo - pmatch[idx].rm_so);
+ }
+ }
+
+ p += pmatch[0].rm_eo;
+ n -= pmatch[0].rm_eo;
+
+
+ if (!opt_all || n == 0) {
+ break;
+ }
+
+
+ if ((regcomp_flags & REG_NEWLINE) == 0 && pattern[0] == '^') {
+ break;
+ }
+
+
+ if (pattern[0] == '\0' && n) {
+
+ Jim_AppendString(interp, resultObj, p, 1);
+ p++;
+ n--;
+ }
+
+ regexec_flags |= REG_NOTBOL;
+ } while (n);
+
+ Jim_AppendString(interp, resultObj, p, -1);
+
+
+ if (argc - i == 4) {
+ result = Jim_SetVariable(interp, varname, resultObj);
+
+ if (result == JIM_OK) {
+ Jim_SetResultInt(interp, num_matches);
+ }
+ else {
+ Jim_FreeObj(interp, resultObj);
+ }
+ }
+ else {
+ Jim_SetResult(interp, resultObj);
+ result = JIM_OK;
+ }
+
+ return result;
+}
+
+int Jim_regexpInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "regexp", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ Jim_CreateCommand(interp, "regexp", Jim_RegexpCmd, NULL, NULL);
+ Jim_CreateCommand(interp, "regsub", Jim_RegsubCmd, NULL, NULL);
+ return JIM_OK;
+}
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+
+#ifdef HAVE_UTIMES
+#include
+#endif
+#ifdef HAVE_UNISTD_H
+#include
+#elif defined(_MSC_VER)
+#include
+#define F_OK 0
+#define W_OK 2
+#define R_OK 4
+#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
+#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
+#endif
+
+# ifndef MAXPATHLEN
+# define MAXPATHLEN JIM_PATH_LEN
+# endif
+
+#if defined(__MINGW32__) || defined(__MSYS__) || defined(_MSC_VER)
+#define ISWINDOWS 1
+#else
+#define ISWINDOWS 0
+#endif
+
+
+#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
+ #define STAT_MTIME_US(STAT) ((STAT).st_mtimespec.tv_sec * 1000000ll + (STAT).st_mtimespec.tv_nsec / 1000)
+#elif defined(HAVE_STRUCT_STAT_ST_MTIM)
+ #define STAT_MTIME_US(STAT) ((STAT).st_mtim.tv_sec * 1000000ll + (STAT).st_mtim.tv_nsec / 1000)
+#endif
+
+
+static const char *JimGetFileType(int mode)
+{
+ if (S_ISREG(mode)) {
+ return "file";
+ }
+ else if (S_ISDIR(mode)) {
+ return "directory";
+ }
+#ifdef S_ISCHR
+ else if (S_ISCHR(mode)) {
+ return "characterSpecial";
+ }
+#endif
+#ifdef S_ISBLK
+ else if (S_ISBLK(mode)) {
+ return "blockSpecial";
+ }
+#endif
+#ifdef S_ISFIFO
+ else if (S_ISFIFO(mode)) {
+ return "fifo";
+ }
+#endif
+#ifdef S_ISLNK
+ else if (S_ISLNK(mode)) {
+ return "link";
+ }
+#endif
+#ifdef S_ISSOCK
+ else if (S_ISSOCK(mode)) {
+ return "socket";
+ }
+#endif
+ return "unknown";
+}
+
+static void AppendStatElement(Jim_Interp *interp, Jim_Obj *listObj, const char *key, jim_wide value)
+{
+ Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, key, -1));
+ Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, value));
+}
+
+static int StoreStatData(Jim_Interp *interp, Jim_Obj *varName, const struct stat *sb)
+{
+
+ Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+
+ AppendStatElement(interp, listObj, "dev", sb->st_dev);
+ AppendStatElement(interp, listObj, "ino", sb->st_ino);
+ AppendStatElement(interp, listObj, "mode", sb->st_mode);
+ AppendStatElement(interp, listObj, "nlink", sb->st_nlink);
+ AppendStatElement(interp, listObj, "uid", sb->st_uid);
+ AppendStatElement(interp, listObj, "gid", sb->st_gid);
+ AppendStatElement(interp, listObj, "size", sb->st_size);
+ AppendStatElement(interp, listObj, "atime", sb->st_atime);
+ AppendStatElement(interp, listObj, "mtime", sb->st_mtime);
+ AppendStatElement(interp, listObj, "ctime", sb->st_ctime);
+#ifdef STAT_MTIME_US
+ AppendStatElement(interp, listObj, "mtimeus", STAT_MTIME_US(*sb));
+#endif
+ Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, "type", -1));
+ Jim_ListAppendElement(interp, listObj, Jim_NewStringObj(interp, JimGetFileType((int)sb->st_mode), -1));
+
+
+ if (varName) {
+ Jim_Obj *objPtr;
+ objPtr = Jim_GetVariable(interp, varName, JIM_NONE);
+
+ if (objPtr) {
+ Jim_Obj *objv[2];
+
+ objv[0] = objPtr;
+ objv[1] = listObj;
+
+ objPtr = Jim_DictMerge(interp, 2, objv);
+ if (objPtr == NULL) {
+
+ Jim_SetResultFormatted(interp, "can't set \"%#s(dev)\": variable isn't array", varName);
+ Jim_FreeNewObj(interp, listObj);
+ return JIM_ERR;
+ }
+
+ Jim_InvalidateStringRep(objPtr);
+
+ Jim_FreeNewObj(interp, listObj);
+ listObj = objPtr;
+ }
+ Jim_SetVariable(interp, varName, listObj);
+ }
+
+
+ Jim_SetResult(interp, listObj);
+
+ return JIM_OK;
+}
+
+static int file_cmd_dirname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *path = Jim_String(argv[0]);
+ const char *p = strrchr(path, '/');
+
+ if (!p && path[0] == '.' && path[1] == '.' && path[2] == '\0') {
+ Jim_SetResultString(interp, "..", -1);
+ } else if (!p) {
+ Jim_SetResultString(interp, ".", -1);
+ }
+ else if (p == path) {
+ Jim_SetResultString(interp, "/", -1);
+ }
+ else if (ISWINDOWS && p[-1] == ':') {
+
+ Jim_SetResultString(interp, path, p - path + 1);
+ }
+ else {
+ Jim_SetResultString(interp, path, p - path);
+ }
+ return JIM_OK;
+}
+
+static int file_cmd_rootname(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *path = Jim_String(argv[0]);
+ const char *lastSlash = strrchr(path, '/');
+ const char *p = strrchr(path, '.');
+
+ if (p == NULL || (lastSlash != NULL && lastSlash > p)) {
+ Jim_SetResult(interp, argv[0]);
+ }
+ else {
+ Jim_SetResultString(interp, path, p - path);
+ }
+ return JIM_OK;
+}
+
+static int file_cmd_extension(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *path = Jim_String(argv[0]);
+ const char *lastSlash = strrchr(path, '/');
+ const char *p = strrchr(path, '.');
+
+ if (p == NULL || (lastSlash != NULL && lastSlash >= p)) {
+ p = "";
+ }
+ Jim_SetResultString(interp, p, -1);
+ return JIM_OK;
+}
+
+static int file_cmd_tail(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *path = Jim_String(argv[0]);
+ const char *lastSlash = strrchr(path, '/');
+
+ if (lastSlash) {
+ Jim_SetResultString(interp, lastSlash + 1, -1);
+ }
+ else {
+ Jim_SetResult(interp, argv[0]);
+ }
+ return JIM_OK;
+}
+
+static int file_cmd_normalize(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+#ifdef HAVE_REALPATH
+ const char *path = Jim_String(argv[0]);
+ char *newname = Jim_Alloc(MAXPATHLEN + 1);
+
+ if (realpath(path, newname)) {
+ Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, -1));
+ return JIM_OK;
+ }
+ else {
+ Jim_Free(newname);
+ Jim_SetResultFormatted(interp, "can't normalize \"%#s\": %s", argv[0], strerror(errno));
+ return JIM_ERR;
+ }
+#else
+ Jim_SetResultString(interp, "Not implemented", -1);
+ return JIM_ERR;
+#endif
+}
+
+static int file_cmd_join(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int i;
+ char *newname = Jim_Alloc(MAXPATHLEN + 1);
+ char *last = newname;
+
+ *newname = 0;
+
+
+ for (i = 0; i < argc; i++) {
+ int len;
+ const char *part = Jim_GetString(argv[i], &len);
+
+ if (*part == '/') {
+
+ last = newname;
+ }
+ else if (ISWINDOWS && strchr(part, ':')) {
+
+ last = newname;
+ }
+ else if (part[0] == '.') {
+ if (part[1] == '/') {
+ part += 2;
+ len -= 2;
+ }
+ else if (part[1] == 0 && last != newname) {
+
+ continue;
+ }
+ }
+
+
+ if (last != newname && last[-1] != '/') {
+ *last++ = '/';
+ }
+
+ if (len) {
+ if (last + len - newname >= MAXPATHLEN) {
+ Jim_Free(newname);
+ Jim_SetResultString(interp, "Path too long", -1);
+ return JIM_ERR;
+ }
+ memcpy(last, part, len);
+ last += len;
+ }
+
+
+ if (last > newname + 1 && last[-1] == '/') {
+
+ if (!ISWINDOWS || !(last > newname + 2 && last[-2] == ':')) {
+ *--last = 0;
+ }
+ }
+ }
+
+ *last = 0;
+
+
+
+ Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, newname, last - newname));
+
+ return JIM_OK;
+}
+
+static int file_access(Jim_Interp *interp, Jim_Obj *filename, int mode)
+{
+ Jim_SetResultBool(interp, access(Jim_String(filename), mode) != -1);
+
+ return JIM_OK;
+}
+
+static int file_cmd_readable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return file_access(interp, argv[0], R_OK);
+}
+
+static int file_cmd_writable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return file_access(interp, argv[0], W_OK);
+}
+
+static int file_cmd_executable(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+#ifdef X_OK
+ return file_access(interp, argv[0], X_OK);
+#else
+
+ Jim_SetResultBool(interp, 1);
+ return JIM_OK;
+#endif
+}
+
+static int file_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return file_access(interp, argv[0], F_OK);
+}
+
+static int file_cmd_delete(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int force = Jim_CompareStringImmediate(interp, argv[0], "-force");
+
+ if (force || Jim_CompareStringImmediate(interp, argv[0], "--")) {
+ argc++;
+ argv--;
+ }
+
+ while (argc--) {
+ const char *path = Jim_String(argv[0]);
+
+ if (unlink(path) == -1 && errno != ENOENT) {
+ if (rmdir(path) == -1) {
+
+ if (!force || Jim_EvalPrefix(interp, "file delete force", 1, argv) != JIM_OK) {
+ Jim_SetResultFormatted(interp, "couldn't delete file \"%s\": %s", path,
+ strerror(errno));
+ return JIM_ERR;
+ }
+ }
+ }
+ argv++;
+ }
+ return JIM_OK;
+}
+
+#ifdef HAVE_MKDIR_ONE_ARG
+#define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
+#else
+#define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
+#endif
+
+static int mkdir_all(char *path)
+{
+ int ok = 1;
+
+
+ goto first;
+
+ while (ok--) {
+
+ {
+ char *slash = strrchr(path, '/');
+
+ if (slash && slash != path) {
+ *slash = 0;
+ if (mkdir_all(path) != 0) {
+ return -1;
+ }
+ *slash = '/';
+ }
+ }
+ first:
+ if (MKDIR_DEFAULT(path) == 0) {
+ return 0;
+ }
+ if (errno == ENOENT) {
+
+ continue;
+ }
+
+ if (errno == EEXIST) {
+ struct stat sb;
+
+ if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
+ return 0;
+ }
+
+ errno = EEXIST;
+ }
+
+ break;
+ }
+ return -1;
+}
+
+static int file_cmd_mkdir(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ while (argc--) {
+ char *path = Jim_StrDup(Jim_String(argv[0]));
+ int rc = mkdir_all(path);
+
+ Jim_Free(path);
+ if (rc != 0) {
+ Jim_SetResultFormatted(interp, "can't create directory \"%#s\": %s", argv[0],
+ strerror(errno));
+ return JIM_ERR;
+ }
+ argv++;
+ }
+ return JIM_OK;
+}
+
+static int file_cmd_tempfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int fd = Jim_MakeTempFile(interp, (argc >= 1) ? Jim_String(argv[0]) : NULL, 0);
+
+ if (fd < 0) {
+ return JIM_ERR;
+ }
+ close(fd);
+
+ return JIM_OK;
+}
+
+static int file_cmd_rename(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *source;
+ const char *dest;
+ int force = 0;
+
+ if (argc == 3) {
+ if (!Jim_CompareStringImmediate(interp, argv[0], "-force")) {
+ return -1;
+ }
+ force++;
+ argv++;
+ argc--;
+ }
+
+ source = Jim_String(argv[0]);
+ dest = Jim_String(argv[1]);
+
+ if (!force && access(dest, F_OK) == 0) {
+ Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": target exists", argv[0],
+ argv[1]);
+ return JIM_ERR;
+ }
+
+ if (rename(source, dest) != 0) {
+ Jim_SetResultFormatted(interp, "error renaming \"%#s\" to \"%#s\": %s", argv[0], argv[1],
+ strerror(errno));
+ return JIM_ERR;
+ }
+
+ return JIM_OK;
+}
+
+#if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
+static int file_cmd_link(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int ret;
+ const char *source;
+ const char *dest;
+ static const char * const options[] = { "-hard", "-symbolic", NULL };
+ enum { OPT_HARD, OPT_SYMBOLIC, };
+ int option = OPT_HARD;
+
+ if (argc == 3) {
+ if (Jim_GetEnum(interp, argv[0], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG) != JIM_OK) {
+ return JIM_ERR;
+ }
+ argv++;
+ argc--;
+ }
+
+ dest = Jim_String(argv[0]);
+ source = Jim_String(argv[1]);
+
+ if (option == OPT_HARD) {
+ ret = link(source, dest);
+ }
+ else {
+ ret = symlink(source, dest);
+ }
+
+ if (ret != 0) {
+ Jim_SetResultFormatted(interp, "error linking \"%#s\" to \"%#s\": %s", argv[0], argv[1],
+ strerror(errno));
+ return JIM_ERR;
+ }
+
+ return JIM_OK;
+}
+#endif
+
+static int file_stat(Jim_Interp *interp, Jim_Obj *filename, struct stat *sb)
+{
+ const char *path = Jim_String(filename);
+
+ if (stat(path, sb) == -1) {
+ Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+#ifdef HAVE_LSTAT
+static int file_lstat(Jim_Interp *interp, Jim_Obj *filename, struct stat *sb)
+{
+ const char *path = Jim_String(filename);
+
+ if (lstat(path, sb) == -1) {
+ Jim_SetResultFormatted(interp, "could not read \"%#s\": %s", filename, strerror(errno));
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+#else
+#define file_lstat file_stat
+#endif
+
+static int file_cmd_atime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+
+ if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, sb.st_atime);
+ return JIM_OK;
+}
+
+static int JimSetFileTimes(Jim_Interp *interp, const char *filename, jim_wide us)
+{
+#ifdef HAVE_UTIMES
+ struct timeval times[2];
+
+ times[1].tv_sec = times[0].tv_sec = us / 1000000;
+ times[1].tv_usec = times[0].tv_usec = us % 1000000;
+
+ if (utimes(filename, times) != 0) {
+ Jim_SetResultFormatted(interp, "can't set time on \"%s\": %s", filename, strerror(errno));
+ return JIM_ERR;
+ }
+ return JIM_OK;
+#else
+ Jim_SetResultString(interp, "Not implemented", -1);
+ return JIM_ERR;
+#endif
+}
+
+static int file_cmd_mtime(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+
+ if (argc == 2) {
+ jim_wide secs;
+ if (Jim_GetWide(interp, argv[1], &secs) != JIM_OK) {
+ return JIM_ERR;
+ }
+ return JimSetFileTimes(interp, Jim_String(argv[0]), secs * 1000000);
+ }
+ if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, sb.st_mtime);
+ return JIM_OK;
+}
+
+#ifdef STAT_MTIME_US
+static int file_cmd_mtimeus(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+
+ if (argc == 2) {
+ jim_wide us;
+ if (Jim_GetWide(interp, argv[1], &us) != JIM_OK) {
+ return JIM_ERR;
+ }
+ return JimSetFileTimes(interp, Jim_String(argv[0]), us);
+ }
+ if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, STAT_MTIME_US(sb));
+ return JIM_OK;
+}
+#endif
+
+static int file_cmd_copy(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return Jim_EvalPrefix(interp, "file copy", argc, argv);
+}
+
+static int file_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+
+ if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, sb.st_size);
+ return JIM_OK;
+}
+
+static int file_cmd_isdirectory(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+ int ret = 0;
+
+ if (file_stat(interp, argv[0], &sb) == JIM_OK) {
+ ret = S_ISDIR(sb.st_mode);
+ }
+ Jim_SetResultInt(interp, ret);
+ return JIM_OK;
+}
+
+static int file_cmd_isfile(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+ int ret = 0;
+
+ if (file_stat(interp, argv[0], &sb) == JIM_OK) {
+ ret = S_ISREG(sb.st_mode);
+ }
+ Jim_SetResultInt(interp, ret);
+ return JIM_OK;
+}
+
+#ifdef HAVE_GETEUID
+static int file_cmd_owned(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+ int ret = 0;
+
+ if (file_stat(interp, argv[0], &sb) == JIM_OK) {
+ ret = (geteuid() == sb.st_uid);
+ }
+ Jim_SetResultInt(interp, ret);
+ return JIM_OK;
+}
+#endif
+
+#if defined(HAVE_READLINK)
+static int file_cmd_readlink(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *path = Jim_String(argv[0]);
+ char *linkValue = Jim_Alloc(MAXPATHLEN + 1);
+
+ int linkLength = readlink(path, linkValue, MAXPATHLEN);
+
+ if (linkLength == -1) {
+ Jim_Free(linkValue);
+ Jim_SetResultFormatted(interp, "couldn't readlink \"%#s\": %s", argv[0], strerror(errno));
+ return JIM_ERR;
+ }
+ linkValue[linkLength] = 0;
+ Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, linkValue, linkLength));
+ return JIM_OK;
+}
+#endif
+
+static int file_cmd_type(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+
+ if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResultString(interp, JimGetFileType((int)sb.st_mode), -1);
+ return JIM_OK;
+}
+
+#ifdef HAVE_LSTAT
+static int file_cmd_lstat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+
+ if (file_lstat(interp, argv[0], &sb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ return StoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
+}
+#else
+#define file_cmd_lstat file_cmd_stat
+#endif
+
+static int file_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct stat sb;
+
+ if (file_stat(interp, argv[0], &sb) != JIM_OK) {
+ return JIM_ERR;
+ }
+ return StoreStatData(interp, argc == 2 ? argv[1] : NULL, &sb);
+}
+
+static const jim_subcmd_type file_command_table[] = {
+ { "atime",
+ "name",
+ file_cmd_atime,
+ 1,
+ 1,
+
+ },
+ { "mtime",
+ "name ?time?",
+ file_cmd_mtime,
+ 1,
+ 2,
+
+ },
+#ifdef STAT_MTIME_US
+ { "mtimeus",
+ "name ?time?",
+ file_cmd_mtimeus,
+ 1,
+ 2,
+
+ },
+#endif
+ { "copy",
+ "?-force? source dest",
+ file_cmd_copy,
+ 2,
+ 3,
+
+ },
+ { "dirname",
+ "name",
+ file_cmd_dirname,
+ 1,
+ 1,
+
+ },
+ { "rootname",
+ "name",
+ file_cmd_rootname,
+ 1,
+ 1,
+
+ },
+ { "extension",
+ "name",
+ file_cmd_extension,
+ 1,
+ 1,
+
+ },
+ { "tail",
+ "name",
+ file_cmd_tail,
+ 1,
+ 1,
+
+ },
+ { "normalize",
+ "name",
+ file_cmd_normalize,
+ 1,
+ 1,
+
+ },
+ { "join",
+ "name ?name ...?",
+ file_cmd_join,
+ 1,
+ -1,
+
+ },
+ { "readable",
+ "name",
+ file_cmd_readable,
+ 1,
+ 1,
+
+ },
+ { "writable",
+ "name",
+ file_cmd_writable,
+ 1,
+ 1,
+
+ },
+ { "executable",
+ "name",
+ file_cmd_executable,
+ 1,
+ 1,
+
+ },
+ { "exists",
+ "name",
+ file_cmd_exists,
+ 1,
+ 1,
+
+ },
+ { "delete",
+ "?-force|--? name ...",
+ file_cmd_delete,
+ 1,
+ -1,
+
+ },
+ { "mkdir",
+ "dir ...",
+ file_cmd_mkdir,
+ 1,
+ -1,
+
+ },
+ { "tempfile",
+ "?template?",
+ file_cmd_tempfile,
+ 0,
+ 1,
+
+ },
+ { "rename",
+ "?-force? source dest",
+ file_cmd_rename,
+ 2,
+ 3,
+
+ },
+#if defined(HAVE_LINK) && defined(HAVE_SYMLINK)
+ { "link",
+ "?-symbolic|-hard? newname target",
+ file_cmd_link,
+ 2,
+ 3,
+
+ },
+#endif
+#if defined(HAVE_READLINK)
+ { "readlink",
+ "name",
+ file_cmd_readlink,
+ 1,
+ 1,
+
+ },
+#endif
+ { "size",
+ "name",
+ file_cmd_size,
+ 1,
+ 1,
+
+ },
+ { "stat",
+ "name ?var?",
+ file_cmd_stat,
+ 1,
+ 2,
+
+ },
+ { "lstat",
+ "name ?var?",
+ file_cmd_lstat,
+ 1,
+ 2,
+
+ },
+ { "type",
+ "name",
+ file_cmd_type,
+ 1,
+ 1,
+
+ },
+#ifdef HAVE_GETEUID
+ { "owned",
+ "name",
+ file_cmd_owned,
+ 1,
+ 1,
+
+ },
+#endif
+ { "isdirectory",
+ "name",
+ file_cmd_isdirectory,
+ 1,
+ 1,
+
+ },
+ { "isfile",
+ "name",
+ file_cmd_isfile,
+ 1,
+ 1,
+
+ },
+ {
+ NULL
+ }
+};
+
+static int Jim_CdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *path;
+
+ if (argc != 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "dirname");
+ return JIM_ERR;
+ }
+
+ path = Jim_String(argv[1]);
+
+ if (chdir(path) != 0) {
+ Jim_SetResultFormatted(interp, "couldn't change working directory to \"%s\": %s", path,
+ strerror(errno));
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+static int Jim_PwdCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ char *cwd = Jim_Alloc(MAXPATHLEN);
+
+ if (getcwd(cwd, MAXPATHLEN) == NULL) {
+ Jim_SetResultString(interp, "Failed to get pwd", -1);
+ Jim_Free(cwd);
+ return JIM_ERR;
+ }
+ else if (ISWINDOWS) {
+
+ char *p = cwd;
+ while ((p = strchr(p, '\\')) != NULL) {
+ *p++ = '/';
+ }
+ }
+
+ Jim_SetResultString(interp, cwd, -1);
+
+ Jim_Free(cwd);
+ return JIM_OK;
+}
+
+int Jim_fileInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "file", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ Jim_CreateCommand(interp, "file", Jim_SubCmdProc, (void *)file_command_table, NULL);
+ Jim_CreateCommand(interp, "pwd", Jim_PwdCmd, NULL, NULL);
+ Jim_CreateCommand(interp, "cd", Jim_CdCmd, NULL, NULL);
+ return JIM_OK;
+}
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include
+#include
+
+
+#if (!defined(HAVE_VFORK) || !defined(HAVE_WAITPID)) && !defined(__MINGW32__)
+static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *cmdlineObj = Jim_NewEmptyStringObj(interp);
+ int i, j;
+ int rc;
+
+
+ for (i = 1; i < argc; i++) {
+ int len;
+ const char *arg = Jim_GetString(argv[i], &len);
+
+ if (i > 1) {
+ Jim_AppendString(interp, cmdlineObj, " ", 1);
+ }
+ if (strpbrk(arg, "\\\" ") == NULL) {
+
+ Jim_AppendString(interp, cmdlineObj, arg, len);
+ continue;
+ }
+
+ Jim_AppendString(interp, cmdlineObj, "\"", 1);
+ for (j = 0; j < len; j++) {
+ if (arg[j] == '\\' || arg[j] == '"') {
+ Jim_AppendString(interp, cmdlineObj, "\\", 1);
+ }
+ Jim_AppendString(interp, cmdlineObj, &arg[j], 1);
+ }
+ Jim_AppendString(interp, cmdlineObj, "\"", 1);
+ }
+ rc = system(Jim_String(cmdlineObj));
+
+ Jim_FreeNewObj(interp, cmdlineObj);
+
+ if (rc) {
+ Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
+ Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
+ Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, 0));
+ Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, rc));
+ Jim_SetGlobalVariableStr(interp, "errorCode", errorCode);
+ return JIM_ERR;
+ }
+
+ return JIM_OK;
+}
+
+int Jim_execInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ Jim_CreateCommand(interp, "exec", Jim_ExecCmd, NULL, NULL);
+ return JIM_OK;
+}
+#else
+
+
+#include
+#include
+#include
+
+struct WaitInfoTable;
+
+static char **JimOriginalEnviron(void);
+static char **JimSaveEnv(char **env);
+static void JimRestoreEnv(char **env);
+static int JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv,
+ pidtype **pidArrayPtr, int *inPipePtr, int *outPipePtr, int *errFilePtr);
+static void JimDetachPids(struct WaitInfoTable *table, int numPids, const pidtype *pidPtr);
+static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj);
+static int Jim_WaitCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv);
+
+#if defined(__MINGW32__)
+static pidtype JimStartWinProcess(Jim_Interp *interp, char **argv, char **env, int inputId, int outputId, int errorId);
+#endif
+
+static void Jim_RemoveTrailingNewline(Jim_Obj *objPtr)
+{
+ int len;
+ const char *s = Jim_GetString(objPtr, &len);
+
+ if (len > 0 && s[len - 1] == '\n') {
+ objPtr->length--;
+ objPtr->bytes[objPtr->length] = '\0';
+ }
+}
+
+static int JimAppendStreamToString(Jim_Interp *interp, int fd, Jim_Obj *strObj)
+{
+ char buf[256];
+ FILE *fh = fdopen(fd, "r");
+ int ret = 0;
+
+ if (fh == NULL) {
+ return -1;
+ }
+
+ while (1) {
+ int retval = fread(buf, 1, sizeof(buf), fh);
+ if (retval > 0) {
+ ret = 1;
+ Jim_AppendString(interp, strObj, buf, retval);
+ }
+ if (retval != sizeof(buf)) {
+ break;
+ }
+ }
+ fclose(fh);
+ return ret;
+}
+
+static char **JimBuildEnv(Jim_Interp *interp)
+{
+ int i;
+ int size;
+ int num;
+ int n;
+ char **envptr;
+ char *envdata;
+
+ Jim_Obj *objPtr = Jim_GetGlobalVariableStr(interp, "env", JIM_NONE);
+
+ if (!objPtr) {
+ return JimOriginalEnviron();
+ }
+
+
+
+ num = Jim_ListLength(interp, objPtr);
+ if (num % 2) {
+
+ num--;
+ }
+ size = Jim_Length(objPtr) + 2;
+
+ envptr = Jim_Alloc(sizeof(*envptr) * (num / 2 + 1) + size);
+ envdata = (char *)&envptr[num / 2 + 1];
+
+ n = 0;
+ for (i = 0; i < num; i += 2) {
+ const char *s1, *s2;
+ Jim_Obj *elemObj;
+
+ Jim_ListIndex(interp, objPtr, i, &elemObj, JIM_NONE);
+ s1 = Jim_String(elemObj);
+ Jim_ListIndex(interp, objPtr, i + 1, &elemObj, JIM_NONE);
+ s2 = Jim_String(elemObj);
+
+ envptr[n] = envdata;
+ envdata += sprintf(envdata, "%s=%s", s1, s2);
+ envdata++;
+ n++;
+ }
+ envptr[n] = NULL;
+ *envdata = 0;
+
+ return envptr;
+}
+
+static void JimFreeEnv(char **env, char **original_environ)
+{
+ if (env != original_environ) {
+ Jim_Free(env);
+ }
+}
+
+static Jim_Obj *JimMakeErrorCode(Jim_Interp *interp, pidtype pid, int waitStatus, Jim_Obj *errStrObj)
+{
+ Jim_Obj *errorCode = Jim_NewListObj(interp, NULL, 0);
+
+ if (pid == JIM_BAD_PID || pid == JIM_NO_PID) {
+ Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "NONE", -1));
+ Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
+ Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, -1));
+ }
+ else if (WIFEXITED(waitStatus)) {
+ Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, "CHILDSTATUS", -1));
+ Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
+ Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, WEXITSTATUS(waitStatus)));
+ }
+ else {
+ const char *type;
+ const char *action;
+ const char *signame;
+
+ if (WIFSIGNALED(waitStatus)) {
+ type = "CHILDKILLED";
+ action = "killed";
+ signame = Jim_SignalId(WTERMSIG(waitStatus));
+ }
+ else {
+ type = "CHILDSUSP";
+ action = "suspended";
+ signame = "none";
+ }
+
+ Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, type, -1));
+
+ if (errStrObj) {
+ Jim_AppendStrings(interp, errStrObj, "child ", action, " by signal ", Jim_SignalId(WTERMSIG(waitStatus)), "\n", NULL);
+ }
+
+ Jim_ListAppendElement(interp, errorCode, Jim_NewIntObj(interp, (long)pid));
+ Jim_ListAppendElement(interp, errorCode, Jim_NewStringObj(interp, signame, -1));
+ }
+ return errorCode;
+}
+
+static int JimCheckWaitStatus(Jim_Interp *interp, pidtype pid, int waitStatus, Jim_Obj *errStrObj)
+{
+ if (WIFEXITED(waitStatus) && WEXITSTATUS(waitStatus) == 0) {
+ return JIM_OK;
+ }
+ Jim_SetGlobalVariableStr(interp, "errorCode", JimMakeErrorCode(interp, pid, waitStatus, errStrObj));
+
+ return JIM_ERR;
+}
+
+
+struct WaitInfo
+{
+ pidtype pid;
+ int status;
+ int flags;
+};
+
+
+struct WaitInfoTable {
+ struct WaitInfo *info;
+ int size;
+ int used;
+ int refcount;
+};
+
+
+#define WI_DETACHED 2
+
+#define WAIT_TABLE_GROW_BY 4
+
+static void JimFreeWaitInfoTable(struct Jim_Interp *interp, void *privData)
+{
+ struct WaitInfoTable *table = privData;
+
+ if (--table->refcount == 0) {
+ Jim_Free(table->info);
+ Jim_Free(table);
+ }
+}
+
+static struct WaitInfoTable *JimAllocWaitInfoTable(void)
+{
+ struct WaitInfoTable *table = Jim_Alloc(sizeof(*table));
+ table->info = NULL;
+ table->size = table->used = 0;
+ table->refcount = 1;
+
+ return table;
+}
+
+static int JimWaitRemove(struct WaitInfoTable *table, pidtype pid)
+{
+ int i;
+
+
+ for (i = 0; i < table->used; i++) {
+ if (pid == table->info[i].pid) {
+ if (i != table->used - 1) {
+ table->info[i] = table->info[table->used - 1];
+ }
+ table->used--;
+ return 0;
+ }
+ }
+ return -1;
+}
+
+static int Jim_ExecCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int outputId;
+ int errorId;
+ pidtype *pidPtr;
+ int numPids, result;
+ int child_siginfo = 1;
+ Jim_Obj *childErrObj;
+ Jim_Obj *errStrObj;
+ struct WaitInfoTable *table = Jim_CmdPrivData(interp);
+
+ if (argc > 1 && Jim_CompareStringImmediate(interp, argv[argc - 1], "&")) {
+ Jim_Obj *listObj;
+ int i;
+
+ argc--;
+ numPids = JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, NULL, NULL);
+ if (numPids < 0) {
+ return JIM_ERR;
+ }
+
+ listObj = Jim_NewListObj(interp, NULL, 0);
+ for (i = 0; i < numPids; i++) {
+ Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, (long)pidPtr[i]));
+ }
+ Jim_SetResult(interp, listObj);
+ JimDetachPids(table, numPids, pidPtr);
+ Jim_Free(pidPtr);
+ return JIM_OK;
+ }
+
+ numPids =
+ JimCreatePipeline(interp, argc - 1, argv + 1, &pidPtr, NULL, &outputId, &errorId);
+
+ if (numPids < 0) {
+ return JIM_ERR;
+ }
+
+ result = JIM_OK;
+
+ errStrObj = Jim_NewStringObj(interp, "", 0);
+
+
+ if (outputId != -1) {
+ if (JimAppendStreamToString(interp, outputId, errStrObj) < 0) {
+ result = JIM_ERR;
+ Jim_SetResultErrno(interp, "error reading from output pipe");
+ }
+ }
+
+
+ childErrObj = Jim_NewStringObj(interp, "", 0);
+ Jim_IncrRefCount(childErrObj);
+
+ if (JimCleanupChildren(interp, numPids, pidPtr, childErrObj) != JIM_OK) {
+ result = JIM_ERR;
+ }
+
+ if (errorId != -1) {
+ int ret;
+ lseek(errorId, 0, SEEK_SET);
+ ret = JimAppendStreamToString(interp, errorId, errStrObj);
+ if (ret < 0) {
+ Jim_SetResultErrno(interp, "error reading from error pipe");
+ result = JIM_ERR;
+ }
+ else if (ret > 0) {
+
+ child_siginfo = 0;
+ }
+ }
+
+ if (child_siginfo) {
+
+ Jim_AppendObj(interp, errStrObj, childErrObj);
+ }
+ Jim_DecrRefCount(interp, childErrObj);
+
+
+ Jim_RemoveTrailingNewline(errStrObj);
+
+
+ Jim_SetResult(interp, errStrObj);
+
+ return result;
+}
+
+static pidtype JimWaitForProcess(struct WaitInfoTable *table, pidtype pid, int *statusPtr)
+{
+ if (JimWaitRemove(table, pid) == 0) {
+
+ waitpid(pid, statusPtr, 0);
+ return pid;
+ }
+
+
+ return JIM_BAD_PID;
+}
+
+static void JimDetachPids(struct WaitInfoTable *table, int numPids, const pidtype *pidPtr)
+{
+ int j;
+
+ for (j = 0; j < numPids; j++) {
+
+ int i;
+ for (i = 0; i < table->used; i++) {
+ if (pidPtr[j] == table->info[i].pid) {
+ table->info[i].flags |= WI_DETACHED;
+ break;
+ }
+ }
+ }
+}
+
+static int JimGetChannelFd(Jim_Interp *interp, const char *name)
+{
+ Jim_Obj *objv[2];
+
+ objv[0] = Jim_NewStringObj(interp, name, -1);
+ objv[1] = Jim_NewStringObj(interp, "getfd", -1);
+
+ if (Jim_EvalObjVector(interp, 2, objv) == JIM_OK) {
+ jim_wide fd;
+ if (Jim_GetWide(interp, Jim_GetResult(interp), &fd) == JIM_OK) {
+ return fd;
+ }
+ }
+ return -1;
+}
+
+static void JimReapDetachedPids(struct WaitInfoTable *table)
+{
+ struct WaitInfo *waitPtr;
+ int count;
+ int dest;
+
+ if (!table) {
+ return;
+ }
+
+ waitPtr = table->info;
+ dest = 0;
+ for (count = table->used; count > 0; waitPtr++, count--) {
+ if (waitPtr->flags & WI_DETACHED) {
+ int status;
+ pidtype pid = waitpid(waitPtr->pid, &status, WNOHANG);
+ if (pid == waitPtr->pid) {
+
+ table->used--;
+ continue;
+ }
+ }
+ if (waitPtr != &table->info[dest]) {
+ table->info[dest] = *waitPtr;
+ }
+ dest++;
+ }
+}
+
+static int Jim_WaitCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct WaitInfoTable *table = Jim_CmdPrivData(interp);
+ int nohang = 0;
+ pidtype pid;
+ long pidarg;
+ int status;
+ Jim_Obj *errCodeObj;
+
+
+ if (argc == 1) {
+ JimReapDetachedPids(table);
+ return JIM_OK;
+ }
+
+ if (argc > 1 && Jim_CompareStringImmediate(interp, argv[1], "-nohang")) {
+ nohang = 1;
+ }
+ if (argc != nohang + 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "?-nohang? ?pid?");
+ return JIM_ERR;
+ }
+ if (Jim_GetLong(interp, argv[nohang + 1], &pidarg) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ pid = waitpid((pidtype)pidarg, &status, nohang ? WNOHANG : 0);
+
+ errCodeObj = JimMakeErrorCode(interp, pid, status, NULL);
+
+ if (pid != JIM_BAD_PID && (WIFEXITED(status) || WIFSIGNALED(status))) {
+
+ JimWaitRemove(table, pid);
+ }
+ Jim_SetResult(interp, errCodeObj);
+ return JIM_OK;
+}
+
+static int Jim_PidCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 1) {
+ Jim_WrongNumArgs(interp, 1, argv, "");
+ return JIM_ERR;
+ }
+
+ Jim_SetResultInt(interp, (jim_wide)getpid());
+ return JIM_OK;
+}
+
+static int
+JimCreatePipeline(Jim_Interp *interp, int argc, Jim_Obj *const *argv, pidtype **pidArrayPtr,
+ int *inPipePtr, int *outPipePtr, int *errFilePtr)
+{
+ pidtype *pidPtr = NULL; /* Points to malloc-ed array holding all
+ * the pids of child processes. */
+ int numPids = 0; /* Actual number of processes that exist
+ * at *pidPtr right now. */
+ int cmdCount; /* Count of number of distinct commands
+ * found in argc/argv. */
+ const char *input = NULL; /* Describes input for pipeline, depending
+ * on "inputFile". NULL means take input
+ * from stdin/pipe. */
+ int input_len = 0;
+
+#define FILE_NAME 0
+#define FILE_APPEND 1
+#define FILE_HANDLE 2
+#define FILE_TEXT 3
+
+ int inputFile = FILE_NAME; /* 1 means input is name of input file.
+ * 2 means input is filehandle name.
+ * 0 means input holds actual
+ * text to be input to command. */
+
+ int outputFile = FILE_NAME; /* 0 means output is the name of output file.
+ * 1 means output is the name of output file, and append.
+ * 2 means output is filehandle name.
+ * All this is ignored if output is NULL
+ */
+ int errorFile = FILE_NAME; /* 0 means error is the name of error file.
+ * 1 means error is the name of error file, and append.
+ * 2 means error is filehandle name.
+ * All this is ignored if error is NULL
+ */
+ const char *output = NULL; /* Holds name of output file to pipe to,
+ * or NULL if output goes to stdout/pipe. */
+ const char *error = NULL; /* Holds name of stderr file to pipe to,
+ * or NULL if stderr goes to stderr/pipe. */
+ int inputId = -1;
+ int outputId = -1;
+ int errorId = -1;
+ int lastOutputId = -1;
+ int pipeIds[2];
+ int firstArg, lastArg; /* Indexes of first and last arguments in
+ * current command. */
+ int lastBar;
+ int i;
+ pidtype pid;
+ char **save_environ;
+#ifndef __MINGW32__
+ char **child_environ;
+#endif
+ struct WaitInfoTable *table = Jim_CmdPrivData(interp);
+
+
+ char **arg_array = Jim_Alloc(sizeof(*arg_array) * (argc + 1));
+ int arg_count = 0;
+
+ if (inPipePtr != NULL) {
+ *inPipePtr = -1;
+ }
+ if (outPipePtr != NULL) {
+ *outPipePtr = -1;
+ }
+ if (errFilePtr != NULL) {
+ *errFilePtr = -1;
+ }
+ pipeIds[0] = pipeIds[1] = -1;
+
+ cmdCount = 1;
+ lastBar = -1;
+ for (i = 0; i < argc; i++) {
+ const char *arg = Jim_String(argv[i]);
+
+ if (arg[0] == '<') {
+ inputFile = FILE_NAME;
+ input = arg + 1;
+ if (*input == '<') {
+ inputFile = FILE_TEXT;
+ input_len = Jim_Length(argv[i]) - 2;
+ input++;
+ }
+ else if (*input == '@') {
+ inputFile = FILE_HANDLE;
+ input++;
+ }
+
+ if (!*input && ++i < argc) {
+ input = Jim_GetString(argv[i], &input_len);
+ }
+ }
+ else if (arg[0] == '>') {
+ int dup_error = 0;
+
+ outputFile = FILE_NAME;
+
+ output = arg + 1;
+ if (*output == '>') {
+ outputFile = FILE_APPEND;
+ output++;
+ }
+ if (*output == '&') {
+
+ output++;
+ dup_error = 1;
+ }
+ if (*output == '@') {
+ outputFile = FILE_HANDLE;
+ output++;
+ }
+ if (!*output && ++i < argc) {
+ output = Jim_String(argv[i]);
+ }
+ if (dup_error) {
+ errorFile = outputFile;
+ error = output;
+ }
+ }
+ else if (arg[0] == '2' && arg[1] == '>') {
+ error = arg + 2;
+ errorFile = FILE_NAME;
+
+ if (*error == '@') {
+ errorFile = FILE_HANDLE;
+ error++;
+ }
+ else if (*error == '>') {
+ errorFile = FILE_APPEND;
+ error++;
+ }
+ if (!*error && ++i < argc) {
+ error = Jim_String(argv[i]);
+ }
+ }
+ else {
+ if (strcmp(arg, "|") == 0 || strcmp(arg, "|&") == 0) {
+ if (i == lastBar + 1 || i == argc - 1) {
+ Jim_SetResultString(interp, "illegal use of | or |& in command", -1);
+ goto badargs;
+ }
+ lastBar = i;
+ cmdCount++;
+ }
+
+ arg_array[arg_count++] = (char *)arg;
+ continue;
+ }
+
+ if (i >= argc) {
+ Jim_SetResultFormatted(interp, "can't specify \"%s\" as last word in command", arg);
+ goto badargs;
+ }
+ }
+
+ if (arg_count == 0) {
+ Jim_SetResultString(interp, "didn't specify command to execute", -1);
+badargs:
+ Jim_Free(arg_array);
+ return -1;
+ }
+
+
+ save_environ = JimSaveEnv(JimBuildEnv(interp));
+
+ if (input != NULL) {
+ if (inputFile == FILE_TEXT) {
+ inputId = Jim_MakeTempFile(interp, NULL, 1);
+ if (inputId == -1) {
+ goto error;
+ }
+ if (write(inputId, input, input_len) != input_len) {
+ Jim_SetResultErrno(interp, "couldn't write temp file");
+ close(inputId);
+ goto error;
+ }
+ lseek(inputId, 0L, SEEK_SET);
+ }
+ else if (inputFile == FILE_HANDLE) {
+ int fd = JimGetChannelFd(interp, input);
+
+ if (fd < 0) {
+ goto error;
+ }
+ inputId = dup(fd);
+ }
+ else {
+ inputId = Jim_OpenForRead(input);
+ if (inputId == -1) {
+ Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", input, strerror(Jim_Errno()));
+ goto error;
+ }
+ }
+ }
+ else if (inPipePtr != NULL) {
+ if (pipe(pipeIds) != 0) {
+ Jim_SetResultErrno(interp, "couldn't create input pipe for command");
+ goto error;
+ }
+ inputId = pipeIds[0];
+ *inPipePtr = pipeIds[1];
+ pipeIds[0] = pipeIds[1] = -1;
+ }
+
+ if (output != NULL) {
+ if (outputFile == FILE_HANDLE) {
+ int fd = JimGetChannelFd(interp, output);
+ if (fd < 0) {
+ goto error;
+ }
+ lastOutputId = dup(fd);
+ }
+ else {
+ lastOutputId = Jim_OpenForWrite(output, outputFile == FILE_APPEND);
+ if (lastOutputId == -1) {
+ Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", output, strerror(Jim_Errno()));
+ goto error;
+ }
+ }
+ }
+ else if (outPipePtr != NULL) {
+ if (pipe(pipeIds) != 0) {
+ Jim_SetResultErrno(interp, "couldn't create output pipe");
+ goto error;
+ }
+ lastOutputId = pipeIds[1];
+ *outPipePtr = pipeIds[0];
+ pipeIds[0] = pipeIds[1] = -1;
+ }
+
+ if (error != NULL) {
+ if (errorFile == FILE_HANDLE) {
+ if (strcmp(error, "1") == 0) {
+
+ if (lastOutputId != -1) {
+ errorId = dup(lastOutputId);
+ }
+ else {
+
+ error = "stdout";
+ }
+ }
+ if (errorId == -1) {
+ int fd = JimGetChannelFd(interp, error);
+ if (fd < 0) {
+ goto error;
+ }
+ errorId = dup(fd);
+ }
+ }
+ else {
+ errorId = Jim_OpenForWrite(error, errorFile == FILE_APPEND);
+ if (errorId == -1) {
+ Jim_SetResultFormatted(interp, "couldn't write file \"%s\": %s", error, strerror(Jim_Errno()));
+ goto error;
+ }
+ }
+ }
+ else if (errFilePtr != NULL) {
+ errorId = Jim_MakeTempFile(interp, NULL, 1);
+ if (errorId == -1) {
+ goto error;
+ }
+ *errFilePtr = dup(errorId);
+ }
+
+
+ pidPtr = Jim_Alloc(cmdCount * sizeof(*pidPtr));
+ for (i = 0; i < numPids; i++) {
+ pidPtr[i] = JIM_BAD_PID;
+ }
+ for (firstArg = 0; firstArg < arg_count; numPids++, firstArg = lastArg + 1) {
+ int pipe_dup_err = 0;
+ int origErrorId = errorId;
+
+ for (lastArg = firstArg; lastArg < arg_count; lastArg++) {
+ if (strcmp(arg_array[lastArg], "|") == 0) {
+ break;
+ }
+ if (strcmp(arg_array[lastArg], "|&") == 0) {
+ pipe_dup_err = 1;
+ break;
+ }
+ }
+
+ if (lastArg == firstArg) {
+ Jim_SetResultString(interp, "missing command to exec", -1);
+ goto error;
+ }
+
+
+ arg_array[lastArg] = NULL;
+ if (lastArg == arg_count) {
+ outputId = lastOutputId;
+ lastOutputId = -1;
+ }
+ else {
+ if (pipe(pipeIds) != 0) {
+ Jim_SetResultErrno(interp, "couldn't create pipe");
+ goto error;
+ }
+ outputId = pipeIds[1];
+ }
+
+
+ if (pipe_dup_err) {
+ errorId = outputId;
+ }
+
+
+
+#ifdef __MINGW32__
+ pid = JimStartWinProcess(interp, &arg_array[firstArg], save_environ, inputId, outputId, errorId);
+ if (pid == JIM_BAD_PID) {
+ Jim_SetResultFormatted(interp, "couldn't exec \"%s\"", arg_array[firstArg]);
+ goto error;
+ }
+#else
+ i = strlen(arg_array[firstArg]);
+
+ child_environ = Jim_GetEnviron();
+ pid = vfork();
+ if (pid < 0) {
+ Jim_SetResultErrno(interp, "couldn't fork child process");
+ goto error;
+ }
+ if (pid == 0) {
+
+
+ if (inputId != -1) {
+ dup2(inputId, fileno(stdin));
+ close(inputId);
+ }
+ if (outputId != -1) {
+ dup2(outputId, fileno(stdout));
+ if (outputId != errorId) {
+ close(outputId);
+ }
+ }
+ if (errorId != -1) {
+ dup2(errorId, fileno(stderr));
+ close(errorId);
+ }
+
+ if (outPipePtr) {
+ close(*outPipePtr);
+ }
+ if (errFilePtr) {
+ close(*errFilePtr);
+ }
+ if (pipeIds[0] != -1) {
+ close(pipeIds[0]);
+ }
+ if (lastOutputId != -1) {
+ close(lastOutputId);
+ }
+
+
+ (void)signal(SIGPIPE, SIG_DFL);
+
+ execvpe(arg_array[firstArg], &arg_array[firstArg], child_environ);
+
+ if (write(fileno(stderr), "couldn't exec \"", 15) &&
+ write(fileno(stderr), arg_array[firstArg], i) &&
+ write(fileno(stderr), "\"\n", 2)) {
+
+ }
+#ifdef JIM_MAINTAINER
+ {
+
+ static char *const false_argv[2] = {"false", NULL};
+ execvp(false_argv[0],false_argv);
+ }
+#endif
+ _exit(127);
+ }
+#endif
+
+
+
+ if (table->used == table->size) {
+ table->size += WAIT_TABLE_GROW_BY;
+ table->info = Jim_Realloc(table->info, table->size * sizeof(*table->info));
+ }
+
+ table->info[table->used].pid = pid;
+ table->info[table->used].flags = 0;
+ table->used++;
+
+ pidPtr[numPids] = pid;
+
+
+ errorId = origErrorId;
+
+
+ if (inputId != -1) {
+ close(inputId);
+ }
+ if (outputId != -1) {
+ close(outputId);
+ }
+ inputId = pipeIds[0];
+ pipeIds[0] = pipeIds[1] = -1;
+ }
+ *pidArrayPtr = pidPtr;
+
+
+ cleanup:
+ if (inputId != -1) {
+ close(inputId);
+ }
+ if (lastOutputId != -1) {
+ close(lastOutputId);
+ }
+ if (errorId != -1) {
+ close(errorId);
+ }
+ Jim_Free(arg_array);
+
+ JimRestoreEnv(save_environ);
+
+ return numPids;
+
+
+ error:
+ if ((inPipePtr != NULL) && (*inPipePtr != -1)) {
+ close(*inPipePtr);
+ *inPipePtr = -1;
+ }
+ if ((outPipePtr != NULL) && (*outPipePtr != -1)) {
+ close(*outPipePtr);
+ *outPipePtr = -1;
+ }
+ if ((errFilePtr != NULL) && (*errFilePtr != -1)) {
+ close(*errFilePtr);
+ *errFilePtr = -1;
+ }
+ if (pipeIds[0] != -1) {
+ close(pipeIds[0]);
+ }
+ if (pipeIds[1] != -1) {
+ close(pipeIds[1]);
+ }
+ if (pidPtr != NULL) {
+ for (i = 0; i < numPids; i++) {
+ if (pidPtr[i] != JIM_BAD_PID) {
+ JimDetachPids(table, 1, &pidPtr[i]);
+ }
+ }
+ Jim_Free(pidPtr);
+ }
+ numPids = -1;
+ goto cleanup;
+}
+
+
+static int JimCleanupChildren(Jim_Interp *interp, int numPids, pidtype *pidPtr, Jim_Obj *errStrObj)
+{
+ struct WaitInfoTable *table = Jim_CmdPrivData(interp);
+ int result = JIM_OK;
+ int i;
+
+
+ for (i = 0; i < numPids; i++) {
+ int waitStatus = 0;
+ if (JimWaitForProcess(table, pidPtr[i], &waitStatus) != JIM_BAD_PID) {
+ if (JimCheckWaitStatus(interp, pidPtr[i], waitStatus, errStrObj) != JIM_OK) {
+ result = JIM_ERR;
+ }
+ }
+ }
+ Jim_Free(pidPtr);
+
+ return result;
+}
+
+int Jim_execInit(Jim_Interp *interp)
+{
+ struct WaitInfoTable *waitinfo;
+ if (Jim_PackageProvide(interp, "exec", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+#ifdef SIGPIPE
+ (void)signal(SIGPIPE, SIG_IGN);
+#endif
+
+ waitinfo = JimAllocWaitInfoTable();
+ Jim_CreateCommand(interp, "exec", Jim_ExecCmd, waitinfo, JimFreeWaitInfoTable);
+ waitinfo->refcount++;
+ Jim_CreateCommand(interp, "wait", Jim_WaitCommand, waitinfo, JimFreeWaitInfoTable);
+ Jim_CreateCommand(interp, "pid", Jim_PidCommand, 0, 0);
+
+ return JIM_OK;
+}
+
+#if defined(__MINGW32__)
+
+
+static int
+JimWinFindExecutable(const char *originalName, char fullPath[MAX_PATH])
+{
+ int i;
+ static char extensions[][5] = {".exe", "", ".bat"};
+
+ for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
+ snprintf(fullPath, MAX_PATH, "%s%s", originalName, extensions[i]);
+
+ if (SearchPath(NULL, fullPath, NULL, MAX_PATH, fullPath, NULL) == 0) {
+ continue;
+ }
+ if (GetFileAttributes(fullPath) & FILE_ATTRIBUTE_DIRECTORY) {
+ continue;
+ }
+ return 0;
+ }
+
+ return -1;
+}
+
+static char **JimSaveEnv(char **env)
+{
+ return env;
+}
+
+static void JimRestoreEnv(char **env)
+{
+ JimFreeEnv(env, Jim_GetEnviron());
+}
+
+static char **JimOriginalEnviron(void)
+{
+ return NULL;
+}
+
+static Jim_Obj *
+JimWinBuildCommandLine(Jim_Interp *interp, char **argv)
+{
+ char *start, *special;
+ int quote, i;
+
+ Jim_Obj *strObj = Jim_NewStringObj(interp, "", 0);
+
+ for (i = 0; argv[i]; i++) {
+ if (i > 0) {
+ Jim_AppendString(interp, strObj, " ", 1);
+ }
+
+ if (argv[i][0] == '\0') {
+ quote = 1;
+ }
+ else {
+ quote = 0;
+ for (start = argv[i]; *start != '\0'; start++) {
+ if (isspace(UCHAR(*start))) {
+ quote = 1;
+ break;
+ }
+ }
+ }
+ if (quote) {
+ Jim_AppendString(interp, strObj, "\"" , 1);
+ }
+
+ start = argv[i];
+ for (special = argv[i]; ; ) {
+ if ((*special == '\\') && (special[1] == '\\' ||
+ special[1] == '"' || (quote && special[1] == '\0'))) {
+ Jim_AppendString(interp, strObj, start, special - start);
+ start = special;
+ while (1) {
+ special++;
+ if (*special == '"' || (quote && *special == '\0')) {
+
+ Jim_AppendString(interp, strObj, start, special - start);
+ break;
+ }
+ if (*special != '\\') {
+ break;
+ }
+ }
+ Jim_AppendString(interp, strObj, start, special - start);
+ start = special;
+ }
+ if (*special == '"') {
+ if (special == start) {
+ Jim_AppendString(interp, strObj, "\"", 1);
+ }
+ else {
+ Jim_AppendString(interp, strObj, start, special - start);
+ }
+ Jim_AppendString(interp, strObj, "\\\"", 2);
+ start = special + 1;
+ }
+ if (*special == '\0') {
+ break;
+ }
+ special++;
+ }
+ Jim_AppendString(interp, strObj, start, special - start);
+ if (quote) {
+ Jim_AppendString(interp, strObj, "\"", 1);
+ }
+ }
+ return strObj;
+}
+
+static pidtype
+JimStartWinProcess(Jim_Interp *interp, char **argv, char **env, int inputId, int outputId, int errorId)
+{
+ STARTUPINFO startInfo;
+ PROCESS_INFORMATION procInfo;
+ HANDLE hProcess;
+ char execPath[MAX_PATH];
+ pidtype pid = JIM_BAD_PID;
+ Jim_Obj *cmdLineObj;
+ char *winenv;
+
+ if (JimWinFindExecutable(argv[0], execPath) < 0) {
+ return JIM_BAD_PID;
+ }
+ argv[0] = execPath;
+
+ hProcess = GetCurrentProcess();
+ cmdLineObj = JimWinBuildCommandLine(interp, argv);
+
+
+ ZeroMemory(&startInfo, sizeof(startInfo));
+ startInfo.cb = sizeof(startInfo);
+ startInfo.dwFlags = STARTF_USESTDHANDLES;
+ startInfo.hStdInput = INVALID_HANDLE_VALUE;
+ startInfo.hStdOutput= INVALID_HANDLE_VALUE;
+ startInfo.hStdError = INVALID_HANDLE_VALUE;
+
+ if (inputId == -1) {
+ inputId = _fileno(stdin);
+ }
+ DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(inputId), hProcess, &startInfo.hStdInput,
+ 0, TRUE, DUPLICATE_SAME_ACCESS);
+ if (startInfo.hStdInput == INVALID_HANDLE_VALUE) {
+ goto end;
+ }
+
+ if (outputId == -1) {
+ outputId = _fileno(stdout);
+ }
+ DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(outputId), hProcess, &startInfo.hStdOutput,
+ 0, TRUE, DUPLICATE_SAME_ACCESS);
+ if (startInfo.hStdOutput == INVALID_HANDLE_VALUE) {
+ goto end;
+ }
+
+
+ if (errorId == -1) {
+ errorId = _fileno(stderr);
+ }
+ DuplicateHandle(hProcess, (HANDLE)_get_osfhandle(errorId), hProcess, &startInfo.hStdError,
+ 0, TRUE, DUPLICATE_SAME_ACCESS);
+ if (startInfo.hStdError == INVALID_HANDLE_VALUE) {
+ goto end;
+ }
+
+ if (env == NULL) {
+
+ winenv = NULL;
+ }
+ else if (env[0] == NULL) {
+ winenv = (char *)"\0";
+ }
+ else {
+ winenv = env[0];
+ }
+
+ if (!CreateProcess(NULL, (char *)Jim_String(cmdLineObj), NULL, NULL, TRUE,
+ 0, winenv, NULL, &startInfo, &procInfo)) {
+ goto end;
+ }
+
+
+ WaitForInputIdle(procInfo.hProcess, 5000);
+ CloseHandle(procInfo.hThread);
+
+ pid = procInfo.hProcess;
+
+ end:
+ Jim_FreeNewObj(interp, cmdLineObj);
+ if (startInfo.hStdInput != INVALID_HANDLE_VALUE) {
+ CloseHandle(startInfo.hStdInput);
+ }
+ if (startInfo.hStdOutput != INVALID_HANDLE_VALUE) {
+ CloseHandle(startInfo.hStdOutput);
+ }
+ if (startInfo.hStdError != INVALID_HANDLE_VALUE) {
+ CloseHandle(startInfo.hStdError);
+ }
+ return pid;
+}
+
+#else
+
+static char **JimOriginalEnviron(void)
+{
+ return Jim_GetEnviron();
+}
+
+static char **JimSaveEnv(char **env)
+{
+ char **saveenv = Jim_GetEnviron();
+ Jim_SetEnviron(env);
+ return saveenv;
+}
+
+static void JimRestoreEnv(char **env)
+{
+ JimFreeEnv(Jim_GetEnviron(), env);
+ Jim_SetEnviron(env);
+}
+#endif
+#endif
+
+
+
+#ifdef STRPTIME_NEEDS_XOPEN_SOURCE
+#ifndef _XOPEN_SOURCE
+#define _XOPEN_SOURCE 500
+#endif
+#endif
+
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include
+#include
+#include
+#include
+
+
+#ifdef HAVE_SYS_TIME_H
+#include
+#endif
+
+struct clock_options {
+ int gmt;
+ const char *format;
+};
+
+static int parse_clock_options(Jim_Interp *interp, int argc, Jim_Obj *const *argv, struct clock_options *opts)
+{
+ static const char * const options[] = { "-gmt", "-format", NULL };
+ enum { OPT_GMT, OPT_FORMAT, };
+ int i;
+
+ for (i = 0; i < argc; i += 2) {
+ int option;
+ if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+ return JIM_ERR;
+ }
+ switch (option) {
+ case OPT_GMT:
+ if (Jim_GetBoolean(interp, argv[i + 1], &opts->gmt) != JIM_OK) {
+ return JIM_ERR;
+ }
+ break;
+ case OPT_FORMAT:
+ opts->format = Jim_String(argv[i + 1]);
+ break;
+ }
+ }
+ return JIM_OK;
+}
+
+static int clock_cmd_format(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+
+ char buf[100];
+ time_t t;
+ jim_wide seconds;
+ struct clock_options options = { 0, "%a %b %d %H:%M:%S %Z %Y" };
+ struct tm *tm;
+
+ if (Jim_GetWide(interp, argv[0], &seconds) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (argc % 2 == 0) {
+ return -1;
+ }
+ if (parse_clock_options(interp, argc - 1, argv + 1, &options) == JIM_ERR) {
+ return JIM_ERR;
+ }
+
+ t = seconds;
+ tm = options.gmt ? gmtime(&t) : localtime(&t);
+
+ if (tm == NULL || strftime(buf, sizeof(buf), options.format, tm) == 0) {
+ Jim_SetResultString(interp, "format string too long or invalid time", -1);
+ return JIM_ERR;
+ }
+
+ Jim_SetResultString(interp, buf, -1);
+
+ return JIM_OK;
+}
+
+#ifdef HAVE_STRPTIME
+static time_t jim_timegm(const struct tm *tm)
+{
+ int m = tm->tm_mon + 1;
+ int y = 1900 + tm->tm_year - (m <= 2);
+ int era = (y >= 0 ? y : y - 399) / 400;
+ unsigned yoe = (unsigned)(y - era * 400);
+ unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + tm->tm_mday - 1;
+ unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
+ long days = (era * 146097 + (int)doe - 719468);
+ int secs = tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
+
+ return days * 24 * 60 * 60 + secs;
+}
+
+static int clock_cmd_scan(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ char *pt;
+ struct tm tm;
+ time_t now = time(NULL);
+
+ struct clock_options options = { 0, NULL };
+
+ if (argc % 2 == 0) {
+ return -1;
+ }
+
+ if (parse_clock_options(interp, argc - 1, argv + 1, &options) == JIM_ERR) {
+ return JIM_ERR;
+ }
+ if (options.format == NULL) {
+ return -1;
+ }
+
+ localtime_r(&now, &tm);
+
+ pt = strptime(Jim_String(argv[0]), options.format, &tm);
+ if (pt == 0 || *pt != 0) {
+ Jim_SetResultString(interp, "Failed to parse time according to format", -1);
+ return JIM_ERR;
+ }
+
+
+ Jim_SetResultInt(interp, options.gmt ? jim_timegm(&tm) : mktime(&tm));
+
+ return JIM_OK;
+}
+#endif
+
+static int clock_cmd_seconds(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_SetResultInt(interp, time(NULL));
+
+ return JIM_OK;
+}
+
+static int clock_cmd_micros(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct timeval tv;
+
+ gettimeofday(&tv, NULL);
+
+ Jim_SetResultInt(interp, (jim_wide) tv.tv_sec * 1000000 + tv.tv_usec);
+
+ return JIM_OK;
+}
+
+static int clock_cmd_millis(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ struct timeval tv;
+
+ gettimeofday(&tv, NULL);
+
+ Jim_SetResultInt(interp, (jim_wide) tv.tv_sec * 1000 + tv.tv_usec / 1000);
+
+ return JIM_OK;
+}
+
+static const jim_subcmd_type clock_command_table[] = {
+ { "clicks",
+ NULL,
+ clock_cmd_micros,
+ 0,
+ 0,
+
+ },
+ { "format",
+ "seconds ?-format string? ?-gmt boolean?",
+ clock_cmd_format,
+ 1,
+ 5,
+
+ },
+ { "microseconds",
+ NULL,
+ clock_cmd_micros,
+ 0,
+ 0,
+
+ },
+ { "milliseconds",
+ NULL,
+ clock_cmd_millis,
+ 0,
+ 0,
+
+ },
+#ifdef HAVE_STRPTIME
+ { "scan",
+ "str -format format ?-gmt boolean?",
+ clock_cmd_scan,
+ 3,
+ 5,
+
+ },
+#endif
+ { "seconds",
+ NULL,
+ clock_cmd_seconds,
+ 0,
+ 0,
+
+ },
+ { NULL }
+};
+
+int Jim_clockInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "clock", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ Jim_CreateCommand(interp, "clock", Jim_SubCmdProc, (void *)clock_command_table, NULL);
+ return JIM_OK;
+}
+
+#include
+#include
+#include
+#include
+#include
+
+
+static int array_cmd_exists(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+
+ Jim_Obj *dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
+ Jim_SetResultInt(interp, dictObj && Jim_DictSize(interp, dictObj) != -1);
+ return JIM_OK;
+}
+
+static int array_cmd_get(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+ Jim_Obj *patternObj;
+
+ if (!objPtr) {
+ return JIM_OK;
+ }
+
+ patternObj = (argc == 1) ? NULL : argv[1];
+
+
+ if (patternObj == NULL || Jim_CompareStringImmediate(interp, patternObj, "*")) {
+ if (Jim_IsList(objPtr) && Jim_ListLength(interp, objPtr) % 2 == 0) {
+
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+ }
+
+ return Jim_DictMatchTypes(interp, objPtr, patternObj, JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS | JIM_DICTMATCH_VALUES);
+}
+
+static int array_cmd_names(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+
+ if (!objPtr) {
+ return JIM_OK;
+ }
+
+ return Jim_DictMatchTypes(interp, objPtr, argc == 1 ? NULL : argv[1], JIM_DICTMATCH_KEYS, JIM_DICTMATCH_KEYS);
+}
+
+static int array_cmd_unset(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int i;
+ int len;
+ Jim_Obj *resultObj;
+ Jim_Obj *objPtr;
+ Jim_Obj **dictValuesObj;
+
+ if (argc == 1 || Jim_CompareStringImmediate(interp, argv[1], "*")) {
+
+ Jim_UnsetVariable(interp, argv[0], JIM_NONE);
+ return JIM_OK;
+ }
+
+ objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+
+ if (objPtr == NULL) {
+
+ return JIM_OK;
+ }
+
+ if (Jim_DictPairs(interp, objPtr, &dictValuesObj, &len) != JIM_OK) {
+
+ Jim_SetResultString(interp, "", -1);
+ return JIM_OK;
+ }
+
+
+ resultObj = Jim_NewDictObj(interp, NULL, 0);
+
+ for (i = 0; i < len; i += 2) {
+ if (!Jim_StringMatchObj(interp, argv[1], dictValuesObj[i], 0)) {
+ Jim_DictAddElement(interp, resultObj, dictValuesObj[i], dictValuesObj[i + 1]);
+ }
+ }
+ Jim_Free(dictValuesObj);
+
+ Jim_SetVariable(interp, argv[0], resultObj);
+ return JIM_OK;
+}
+
+static int array_cmd_size(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr;
+ int len = 0;
+
+
+ objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+ if (objPtr) {
+ len = Jim_DictSize(interp, objPtr);
+ if (len < 0) {
+
+ Jim_SetResultInt(interp, 0);
+ return JIM_OK;
+ }
+ }
+
+ Jim_SetResultInt(interp, len);
+
+ return JIM_OK;
+}
+
+static int array_cmd_stat(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr = Jim_GetVariable(interp, argv[0], JIM_NONE);
+ if (objPtr) {
+ return Jim_DictInfo(interp, objPtr);
+ }
+ Jim_SetResultFormatted(interp, "\"%#s\" isn't an array", argv[0], NULL);
+ return JIM_ERR;
+}
+
+static int array_cmd_set(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int i;
+ int len;
+ Jim_Obj *listObj = argv[1];
+ Jim_Obj *dictObj;
+
+ len = Jim_ListLength(interp, listObj);
+ if (len % 2) {
+ Jim_SetResultString(interp, "list must have an even number of elements", -1);
+ return JIM_ERR;
+ }
+
+ dictObj = Jim_GetVariable(interp, argv[0], JIM_UNSHARED);
+ if (!dictObj) {
+
+ return Jim_SetVariable(interp, argv[0], listObj);
+ }
+ else if (Jim_DictSize(interp, dictObj) < 0) {
+ return JIM_ERR;
+ }
+
+ if (Jim_IsShared(dictObj)) {
+ dictObj = Jim_DuplicateObj(interp, dictObj);
+ }
+
+ for (i = 0; i < len; i += 2) {
+ Jim_Obj *nameObj;
+ Jim_Obj *valueObj;
+
+ Jim_ListIndex(interp, listObj, i, &nameObj, JIM_NONE);
+ Jim_ListIndex(interp, listObj, i + 1, &valueObj, JIM_NONE);
+
+ Jim_DictAddElement(interp, dictObj, nameObj, valueObj);
+ }
+ return Jim_SetVariable(interp, argv[0], dictObj);
+}
+
+static const jim_subcmd_type array_command_table[] = {
+ { "exists",
+ "arrayName",
+ array_cmd_exists,
+ 1,
+ 1,
+
+ },
+ { "get",
+ "arrayName ?pattern?",
+ array_cmd_get,
+ 1,
+ 2,
+
+ },
+ { "names",
+ "arrayName ?pattern?",
+ array_cmd_names,
+ 1,
+ 2,
+
+ },
+ { "set",
+ "arrayName list",
+ array_cmd_set,
+ 2,
+ 2,
+
+ },
+ { "size",
+ "arrayName",
+ array_cmd_size,
+ 1,
+ 1,
+
+ },
+ { "stat",
+ "arrayName",
+ array_cmd_stat,
+ 1,
+ 1,
+
+ },
+ { "unset",
+ "arrayName ?pattern?",
+ array_cmd_unset,
+ 1,
+ 2,
+
+ },
+ { NULL
+ }
+};
+
+int Jim_arrayInit(Jim_Interp *interp)
+{
+ if (Jim_PackageProvide(interp, "array", "1.0", JIM_ERRMSG))
+ return JIM_ERR;
+
+ Jim_CreateCommand(interp, "array", Jim_SubCmdProc, (void *)array_command_table, NULL);
+ return JIM_OK;
+}
+int Jim_InitStaticExtensions(Jim_Interp *interp)
+{
+extern int Jim_bootstrapInit(Jim_Interp *);
+extern int Jim_aioInit(Jim_Interp *);
+extern int Jim_readdirInit(Jim_Interp *);
+extern int Jim_regexpInit(Jim_Interp *);
+extern int Jim_fileInit(Jim_Interp *);
+extern int Jim_globInit(Jim_Interp *);
+extern int Jim_execInit(Jim_Interp *);
+extern int Jim_clockInit(Jim_Interp *);
+extern int Jim_arrayInit(Jim_Interp *);
+extern int Jim_stdlibInit(Jim_Interp *);
+extern int Jim_tclcompatInit(Jim_Interp *);
+Jim_bootstrapInit(interp);
+Jim_aioInit(interp);
+Jim_readdirInit(interp);
+Jim_regexpInit(interp);
+Jim_fileInit(interp);
+Jim_globInit(interp);
+Jim_execInit(interp);
+Jim_clockInit(interp);
+Jim_arrayInit(interp);
+Jim_stdlibInit(interp);
+Jim_tclcompatInit(interp);
+return JIM_OK;
+}
+#define JIM_OPTIMIZATION
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+
+#ifdef HAVE_SYS_TIME_H
+#include
+#endif
+#ifdef HAVE_BACKTRACE
+#include
+#endif
+#ifdef HAVE_CRT_EXTERNS_H
+#include
+#endif
+
+
+#include
+
+
+
+
+
+#ifndef TCL_LIBRARY
+#define TCL_LIBRARY "."
+#endif
+#ifndef TCL_PLATFORM_OS
+#define TCL_PLATFORM_OS "unknown"
+#endif
+#ifndef TCL_PLATFORM_PLATFORM
+#define TCL_PLATFORM_PLATFORM "unknown"
+#endif
+#ifndef TCL_PLATFORM_PATH_SEPARATOR
+#define TCL_PLATFORM_PATH_SEPARATOR ":"
+#endif
+
+
+
+
+
+
+
+#ifdef JIM_MAINTAINER
+#define JIM_DEBUG_COMMAND
+#define JIM_DEBUG_PANIC
+#endif
+
+
+
+#define JIM_INTEGER_SPACE 24
+
+const char *jim_tt_name(int type);
+
+#ifdef JIM_DEBUG_PANIC
+static void JimPanicDump(int fail_condition, const char *fmt, ...);
+#define JimPanic(X) JimPanicDump X
+#else
+#define JimPanic(X)
+#endif
+
+#ifdef JIM_OPTIMIZATION
+#define JIM_IF_OPTIM(X) X
+#else
+#define JIM_IF_OPTIM(X)
+#endif
+
+
+static char JimEmptyStringRep[] = "";
+
+static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action);
+static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int listindex, Jim_Obj *newObjPtr,
+ int flags);
+static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands);
+static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr);
+static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
+static Jim_Obj **JimDictPairs(Jim_Obj *dictPtr, int *len);
+static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
+ const char *prefix, const char *const *tablePtr, const char *name);
+static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv);
+static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr);
+static int JimSign(jim_wide w);
+static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr);
+static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen);
+static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len);
+
+
+
+#define JimWideValue(objPtr) (objPtr)->internalRep.wideValue
+
+#define JimObjTypeName(O) ((O)->typePtr ? (O)->typePtr->name : "none")
+
+static int utf8_tounicode_case(const char *s, int *uc, int upper)
+{
+ int l = utf8_tounicode(s, uc);
+ if (upper) {
+ *uc = utf8_upper(*uc);
+ }
+ return l;
+}
+
+
+#define JIM_CHARSET_SCAN 2
+#define JIM_CHARSET_GLOB 0
+
+static const char *JimCharsetMatch(const char *pattern, int c, int flags)
+{
+ int not = 0;
+ int pchar;
+ int match = 0;
+ int nocase = 0;
+
+ if (flags & JIM_NOCASE) {
+ nocase++;
+ c = utf8_upper(c);
+ }
+
+ if (flags & JIM_CHARSET_SCAN) {
+ if (*pattern == '^') {
+ not++;
+ pattern++;
+ }
+
+
+ if (*pattern == ']') {
+ goto first;
+ }
+ }
+
+ while (*pattern && *pattern != ']') {
+
+ if (pattern[0] == '\\') {
+first:
+ pattern += utf8_tounicode_case(pattern, &pchar, nocase);
+ }
+ else {
+
+ int start;
+ int end;
+
+ pattern += utf8_tounicode_case(pattern, &start, nocase);
+ if (pattern[0] == '-' && pattern[1]) {
+
+ pattern++;
+ pattern += utf8_tounicode_case(pattern, &end, nocase);
+
+
+ if ((c >= start && c <= end) || (c >= end && c <= start)) {
+ match = 1;
+ }
+ continue;
+ }
+ pchar = start;
+ }
+
+ if (pchar == c) {
+ match = 1;
+ }
+ }
+ if (not) {
+ match = !match;
+ }
+
+ return match ? pattern : NULL;
+}
+
+
+
+static int JimGlobMatch(const char *pattern, const char *string, int nocase)
+{
+ int c;
+ int pchar;
+ while (*pattern) {
+ switch (pattern[0]) {
+ case '*':
+ while (pattern[1] == '*') {
+ pattern++;
+ }
+ pattern++;
+ if (!pattern[0]) {
+ return 1;
+ }
+ while (*string) {
+
+ if (JimGlobMatch(pattern, string, nocase))
+ return 1;
+ string += utf8_tounicode(string, &c);
+ }
+ return 0;
+
+ case '?':
+ string += utf8_tounicode(string, &c);
+ break;
+
+ case '[': {
+ string += utf8_tounicode(string, &c);
+ pattern = JimCharsetMatch(pattern + 1, c, nocase ? JIM_NOCASE : 0);
+ if (!pattern) {
+ return 0;
+ }
+ if (!*pattern) {
+
+ continue;
+ }
+ break;
+ }
+ case '\\':
+ if (pattern[1]) {
+ pattern++;
+ }
+
+ default:
+ string += utf8_tounicode_case(string, &c, nocase);
+ utf8_tounicode_case(pattern, &pchar, nocase);
+ if (pchar != c) {
+ return 0;
+ }
+ break;
+ }
+ pattern += utf8_tounicode_case(pattern, &pchar, nocase);
+ if (!*string) {
+ while (*pattern == '*') {
+ pattern++;
+ }
+ break;
+ }
+ }
+ if (!*pattern && !*string) {
+ return 1;
+ }
+ return 0;
+}
+
+static int JimStringCompare(const char *s1, int l1, const char *s2, int l2)
+{
+ if (l1 < l2) {
+ return memcmp(s1, s2, l1) <= 0 ? -1 : 1;
+ }
+ else if (l2 < l1) {
+ return memcmp(s1, s2, l2) >= 0 ? 1 : -1;
+ }
+ else {
+ return JimSign(memcmp(s1, s2, l1));
+ }
+}
+
+static int JimStringCompareLen(const char *s1, const char *s2, int maxchars, int nocase)
+{
+ while (*s1 && *s2 && maxchars) {
+ int c1, c2;
+ s1 += utf8_tounicode_case(s1, &c1, nocase);
+ s2 += utf8_tounicode_case(s2, &c2, nocase);
+ if (c1 != c2) {
+ return JimSign(c1 - c2);
+ }
+ maxchars--;
+ }
+ if (!maxchars) {
+ return 0;
+ }
+
+ if (*s1) {
+ return 1;
+ }
+ if (*s2) {
+ return -1;
+ }
+ return 0;
+}
+
+static int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int idx)
+{
+ int i;
+ int l1bytelen;
+
+ if (!l1 || !l2 || l1 > l2) {
+ return -1;
+ }
+ if (idx < 0)
+ idx = 0;
+ s2 += utf8_index(s2, idx);
+
+ l1bytelen = utf8_index(s1, l1);
+
+ for (i = idx; i <= l2 - l1; i++) {
+ int c;
+ if (memcmp(s2, s1, l1bytelen) == 0) {
+ return i;
+ }
+ s2 += utf8_tounicode(s2, &c);
+ }
+ return -1;
+}
+
+static int JimStringLast(const char *s1, int l1, const char *s2, int l2)
+{
+ const char *p;
+
+ if (!l1 || !l2 || l1 > l2)
+ return -1;
+
+
+ for (p = s2 + l2 - 1; p != s2 - 1; p--) {
+ if (*p == *s1 && memcmp(s1, p, l1) == 0) {
+ return p - s2;
+ }
+ }
+ return -1;
+}
+
+#ifdef JIM_UTF8
+static int JimStringLastUtf8(const char *s1, int l1, const char *s2, int l2)
+{
+ int n = JimStringLast(s1, utf8_index(s1, l1), s2, utf8_index(s2, l2));
+ if (n > 0) {
+ n = utf8_strlen(s2, n);
+ }
+ return n;
+}
+#endif
+
+static int JimCheckConversion(const char *str, const char *endptr)
+{
+ if (str[0] == '\0' || str == endptr) {
+ return JIM_ERR;
+ }
+
+ if (endptr[0] != '\0') {
+ while (*endptr) {
+ if (!isspace(UCHAR(*endptr))) {
+ return JIM_ERR;
+ }
+ endptr++;
+ }
+ }
+ return JIM_OK;
+}
+
+static int JimNumberBase(const char *str, int *base, int *sign)
+{
+ int i = 0;
+
+ *base = 10;
+
+ while (isspace(UCHAR(str[i]))) {
+ i++;
+ }
+
+ if (str[i] == '-') {
+ *sign = -1;
+ i++;
+ }
+ else {
+ if (str[i] == '+') {
+ i++;
+ }
+ *sign = 1;
+ }
+
+ if (str[i] != '0') {
+
+ return 0;
+ }
+
+
+ switch (str[i + 1]) {
+ case 'x': case 'X': *base = 16; break;
+ case 'o': case 'O': *base = 8; break;
+ case 'b': case 'B': *base = 2; break;
+ default: return 0;
+ }
+ i += 2;
+
+ if (str[i] != '-' && str[i] != '+' && !isspace(UCHAR(str[i]))) {
+
+ return i;
+ }
+
+ *base = 10;
+ return 0;
+}
+
+static long jim_strtol(const char *str, char **endptr)
+{
+ int sign;
+ int base;
+ int i = JimNumberBase(str, &base, &sign);
+
+ if (base != 10) {
+ long value = strtol(str + i, endptr, base);
+ if (endptr == NULL || *endptr != str + i) {
+ return value * sign;
+ }
+ }
+
+
+ return strtol(str, endptr, 10);
+}
+
+
+static jim_wide jim_strtoull(const char *str, char **endptr)
+{
+#ifdef HAVE_LONG_LONG
+ int sign;
+ int base;
+ int i = JimNumberBase(str, &base, &sign);
+
+ if (base != 10) {
+ jim_wide value = strtoull(str + i, endptr, base);
+ if (endptr == NULL || *endptr != str + i) {
+ return value * sign;
+ }
+ }
+
+
+ return strtoull(str, endptr, 10);
+#else
+ return (unsigned long)jim_strtol(str, endptr);
+#endif
+}
+
+int Jim_StringToWide(const char *str, jim_wide * widePtr, int base)
+{
+ char *endptr;
+
+ if (base) {
+ *widePtr = strtoull(str, &endptr, base);
+ }
+ else {
+ *widePtr = jim_strtoull(str, &endptr);
+ }
+
+ return JimCheckConversion(str, endptr);
+}
+
+int Jim_StringToDouble(const char *str, double *doublePtr)
+{
+ char *endptr;
+
+
+ errno = 0;
+
+ *doublePtr = strtod(str, &endptr);
+
+ return JimCheckConversion(str, endptr);
+}
+
+static jim_wide JimPowWide(jim_wide b, jim_wide e)
+{
+ jim_wide res = 1;
+
+
+ if (b == 1) {
+
+ return 1;
+ }
+ if (e < 0) {
+ if (b != -1) {
+ return 0;
+ }
+ e = -e;
+ }
+ while (e)
+ {
+ if (e & 1) {
+ res *= b;
+ }
+ e >>= 1;
+ b *= b;
+ }
+ return res;
+}
+
+#ifdef JIM_DEBUG_PANIC
+static void JimPanicDump(int condition, const char *fmt, ...)
+{
+ va_list ap;
+
+ if (!condition) {
+ return;
+ }
+
+ va_start(ap, fmt);
+
+ fprintf(stderr, "\nJIM INTERPRETER PANIC: ");
+ vfprintf(stderr, fmt, ap);
+ fprintf(stderr, "\n\n");
+ va_end(ap);
+
+#ifdef HAVE_BACKTRACE
+ {
+ void *array[40];
+ int size, i;
+ char **strings;
+
+ size = backtrace(array, 40);
+ strings = backtrace_symbols(array, size);
+ for (i = 0; i < size; i++)
+ fprintf(stderr, "[backtrace] %s\n", strings[i]);
+ fprintf(stderr, "[backtrace] Include the above lines and the output\n");
+ fprintf(stderr, "[backtrace] of 'nm ' in the bug report.\n");
+ }
+#endif
+
+ exit(1);
+}
+#endif
+
+
+void *Jim_Alloc(int size)
+{
+ return size ? malloc(size) : NULL;
+}
+
+void Jim_Free(void *ptr)
+{
+ free(ptr);
+}
+
+void *Jim_Realloc(void *ptr, int size)
+{
+ return realloc(ptr, size);
+}
+
+char *Jim_StrDup(const char *s)
+{
+ return strdup(s);
+}
+
+char *Jim_StrDupLen(const char *s, int l)
+{
+ char *copy = Jim_Alloc(l + 1);
+
+ memcpy(copy, s, l + 1);
+ copy[l] = 0;
+ return copy;
+}
+
+
+
+static jim_wide JimClock(void)
+{
+ struct timeval tv;
+
+ gettimeofday(&tv, NULL);
+ return (jim_wide) tv.tv_sec * 1000000 + tv.tv_usec;
+}
+
+
+
+static void JimExpandHashTableIfNeeded(Jim_HashTable *ht);
+static unsigned int JimHashTableNextPower(unsigned int size);
+static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace);
+
+
+
+
+unsigned int Jim_IntHashFunction(unsigned int key)
+{
+ key += ~(key << 15);
+ key ^= (key >> 10);
+ key += (key << 3);
+ key ^= (key >> 6);
+ key += ~(key << 11);
+ key ^= (key >> 16);
+ return key;
+}
+
+unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
+{
+ unsigned int h = 0;
+
+ while (len--)
+ h += (h << 3) + *buf++;
+ return h;
+}
+
+
+
+
+static void JimResetHashTable(Jim_HashTable *ht)
+{
+ ht->table = NULL;
+ ht->size = 0;
+ ht->sizemask = 0;
+ ht->used = 0;
+ ht->collisions = 0;
+#ifdef JIM_RANDOMISE_HASH
+ ht->uniq = (rand() ^ time(NULL) ^ clock());
+#else
+ ht->uniq = 0;
+#endif
+}
+
+static void JimInitHashTableIterator(Jim_HashTable *ht, Jim_HashTableIterator *iter)
+{
+ iter->ht = ht;
+ iter->index = -1;
+ iter->entry = NULL;
+ iter->nextEntry = NULL;
+}
+
+
+int Jim_InitHashTable(Jim_HashTable *ht, const Jim_HashTableType *type, void *privDataPtr)
+{
+ JimResetHashTable(ht);
+ ht->type = type;
+ ht->privdata = privDataPtr;
+ return JIM_OK;
+}
+
+void Jim_ResizeHashTable(Jim_HashTable *ht)
+{
+ int minimal = ht->used;
+
+ if (minimal < JIM_HT_INITIAL_SIZE)
+ minimal = JIM_HT_INITIAL_SIZE;
+ Jim_ExpandHashTable(ht, minimal);
+}
+
+
+void Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
+{
+ Jim_HashTable n;
+ unsigned int realsize = JimHashTableNextPower(size), i;
+
+ if (size <= ht->used)
+ return;
+
+ Jim_InitHashTable(&n, ht->type, ht->privdata);
+ n.size = realsize;
+ n.sizemask = realsize - 1;
+ n.table = Jim_Alloc(realsize * sizeof(Jim_HashEntry *));
+
+ n.uniq = ht->uniq;
+
+
+ memset(n.table, 0, realsize * sizeof(Jim_HashEntry *));
+
+ n.used = ht->used;
+ for (i = 0; ht->used > 0; i++) {
+ Jim_HashEntry *he, *nextHe;
+
+ if (ht->table[i] == NULL)
+ continue;
+
+
+ he = ht->table[i];
+ while (he) {
+ unsigned int h;
+
+ nextHe = he->next;
+
+ h = Jim_HashKey(ht, he->key) & n.sizemask;
+ he->next = n.table[h];
+ n.table[h] = he;
+ ht->used--;
+
+ he = nextHe;
+ }
+ }
+ assert(ht->used == 0);
+ Jim_Free(ht->table);
+
+
+ *ht = n;
+}
+
+
+int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
+{
+ Jim_HashEntry *entry;
+
+ entry = JimInsertHashEntry(ht, key, 0);
+ if (entry == NULL)
+ return JIM_ERR;
+
+
+ Jim_SetHashKey(ht, entry, key);
+ Jim_SetHashVal(ht, entry, val);
+ return JIM_OK;
+}
+
+
+int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
+{
+ int existed;
+ Jim_HashEntry *entry;
+
+ entry = JimInsertHashEntry(ht, key, 1);
+ if (entry->key) {
+ if (ht->type->valDestructor && ht->type->valDup) {
+ void *newval = ht->type->valDup(ht->privdata, val);
+ ht->type->valDestructor(ht->privdata, entry->u.val);
+ entry->u.val = newval;
+ }
+ else {
+ Jim_FreeEntryVal(ht, entry);
+ Jim_SetHashVal(ht, entry, val);
+ }
+ existed = 1;
+ }
+ else {
+
+ Jim_SetHashKey(ht, entry, key);
+ Jim_SetHashVal(ht, entry, val);
+ existed = 0;
+ }
+
+ return existed;
+}
+
+
+int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
+{
+ unsigned int h;
+ Jim_HashEntry *he, *prevHe;
+
+ if (ht->used == 0)
+ return JIM_ERR;
+ h = Jim_HashKey(ht, key) & ht->sizemask;
+ he = ht->table[h];
+
+ prevHe = NULL;
+ while (he) {
+ if (Jim_CompareHashKeys(ht, key, he->key)) {
+
+ if (prevHe)
+ prevHe->next = he->next;
+ else
+ ht->table[h] = he->next;
+ Jim_FreeEntryKey(ht, he);
+ Jim_FreeEntryVal(ht, he);
+ Jim_Free(he);
+ ht->used--;
+ return JIM_OK;
+ }
+ prevHe = he;
+ he = he->next;
+ }
+ return JIM_ERR;
+}
+
+
+int Jim_FreeHashTable(Jim_HashTable *ht)
+{
+ unsigned int i;
+
+
+ for (i = 0; ht->used > 0; i++) {
+ Jim_HashEntry *he, *nextHe;
+
+ if ((he = ht->table[i]) == NULL)
+ continue;
+ while (he) {
+ nextHe = he->next;
+ Jim_FreeEntryKey(ht, he);
+ Jim_FreeEntryVal(ht, he);
+ Jim_Free(he);
+ ht->used--;
+ he = nextHe;
+ }
+ }
+
+ Jim_Free(ht->table);
+
+ JimResetHashTable(ht);
+ return JIM_OK;
+}
+
+Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
+{
+ Jim_HashEntry *he;
+ unsigned int h;
+
+ if (ht->used == 0)
+ return NULL;
+ h = Jim_HashKey(ht, key) & ht->sizemask;
+ he = ht->table[h];
+ while (he) {
+ if (Jim_CompareHashKeys(ht, key, he->key))
+ return he;
+ he = he->next;
+ }
+ return NULL;
+}
+
+Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
+{
+ Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
+ JimInitHashTableIterator(ht, iter);
+ return iter;
+}
+
+Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
+{
+ while (1) {
+ if (iter->entry == NULL) {
+ iter->index++;
+ if (iter->index >= (signed)iter->ht->size)
+ break;
+ iter->entry = iter->ht->table[iter->index];
+ }
+ else {
+ iter->entry = iter->nextEntry;
+ }
+ if (iter->entry) {
+ iter->nextEntry = iter->entry->next;
+ return iter->entry;
+ }
+ }
+ return NULL;
+}
+
+
+
+
+static void JimExpandHashTableIfNeeded(Jim_HashTable *ht)
+{
+ if (ht->size == 0)
+ Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
+ if (ht->size == ht->used)
+ Jim_ExpandHashTable(ht, ht->size * 2);
+}
+
+
+static unsigned int JimHashTableNextPower(unsigned int size)
+{
+ unsigned int i = JIM_HT_INITIAL_SIZE;
+
+ if (size >= 2147483648U)
+ return 2147483648U;
+ while (1) {
+ if (i >= size)
+ return i;
+ i *= 2;
+ }
+}
+
+static Jim_HashEntry *JimInsertHashEntry(Jim_HashTable *ht, const void *key, int replace)
+{
+ unsigned int h;
+ Jim_HashEntry *he;
+
+
+ JimExpandHashTableIfNeeded(ht);
+
+
+ h = Jim_HashKey(ht, key) & ht->sizemask;
+
+ he = ht->table[h];
+ while (he) {
+ if (Jim_CompareHashKeys(ht, key, he->key))
+ return replace ? he : NULL;
+ he = he->next;
+ }
+
+
+ he = Jim_Alloc(sizeof(*he));
+ he->next = ht->table[h];
+ ht->table[h] = he;
+ ht->used++;
+ he->key = NULL;
+
+ return he;
+}
+
+
+
+static unsigned int JimStringCopyHTHashFunction(const void *key)
+{
+ return Jim_GenHashFunction(key, strlen(key));
+}
+
+static void *JimStringCopyHTDup(void *privdata, const void *key)
+{
+ return Jim_StrDup(key);
+}
+
+static int JimStringCopyHTKeyCompare(void *privdata, const void *key1, const void *key2)
+{
+ return strcmp(key1, key2) == 0;
+}
+
+static void JimStringCopyHTKeyDestructor(void *privdata, void *key)
+{
+ Jim_Free(key);
+}
+
+static const Jim_HashTableType JimPackageHashTableType = {
+ JimStringCopyHTHashFunction,
+ JimStringCopyHTDup,
+ NULL,
+ JimStringCopyHTKeyCompare,
+ JimStringCopyHTKeyDestructor,
+ NULL
+};
+
+typedef struct AssocDataValue
+{
+ Jim_InterpDeleteProc *delProc;
+ void *data;
+} AssocDataValue;
+
+static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
+{
+ AssocDataValue *assocPtr = (AssocDataValue *) data;
+
+ if (assocPtr->delProc != NULL)
+ assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
+ Jim_Free(data);
+}
+
+static const Jim_HashTableType JimAssocDataHashTableType = {
+ JimStringCopyHTHashFunction,
+ JimStringCopyHTDup,
+ NULL,
+ JimStringCopyHTKeyCompare,
+ JimStringCopyHTKeyDestructor,
+ JimAssocDataHashTableValueDestructor
+};
+
+void Jim_InitStack(Jim_Stack *stack)
+{
+ stack->len = 0;
+ stack->maxlen = 0;
+ stack->vector = NULL;
+}
+
+void Jim_FreeStack(Jim_Stack *stack)
+{
+ Jim_Free(stack->vector);
+}
+
+int Jim_StackLen(Jim_Stack *stack)
+{
+ return stack->len;
+}
+
+void Jim_StackPush(Jim_Stack *stack, void *element)
+{
+ int neededLen = stack->len + 1;
+
+ if (neededLen > stack->maxlen) {
+ stack->maxlen = neededLen < 20 ? 20 : neededLen * 2;
+ stack->vector = Jim_Realloc(stack->vector, sizeof(void *) * stack->maxlen);
+ }
+ stack->vector[stack->len] = element;
+ stack->len++;
+}
+
+void *Jim_StackPop(Jim_Stack *stack)
+{
+ if (stack->len == 0)
+ return NULL;
+ stack->len--;
+ return stack->vector[stack->len];
+}
+
+void *Jim_StackPeek(Jim_Stack *stack)
+{
+ if (stack->len == 0)
+ return NULL;
+ return stack->vector[stack->len - 1];
+}
+
+void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc) (void *ptr))
+{
+ int i;
+
+ for (i = 0; i < stack->len; i++)
+ freeFunc(stack->vector[i]);
+}
+
+
+
+#define JIM_TT_NONE 0
+#define JIM_TT_STR 1
+#define JIM_TT_ESC 2
+#define JIM_TT_VAR 3
+#define JIM_TT_DICTSUGAR 4
+#define JIM_TT_CMD 5
+
+#define JIM_TT_SEP 6
+#define JIM_TT_EOL 7
+#define JIM_TT_EOF 8
+
+#define JIM_TT_LINE 9
+#define JIM_TT_WORD 10
+
+
+#define JIM_TT_SUBEXPR_START 11
+#define JIM_TT_SUBEXPR_END 12
+#define JIM_TT_SUBEXPR_COMMA 13
+#define JIM_TT_EXPR_INT 14
+#define JIM_TT_EXPR_DOUBLE 15
+#define JIM_TT_EXPR_BOOLEAN 16
+
+#define JIM_TT_EXPRSUGAR 17
+
+
+#define JIM_TT_EXPR_OP 20
+
+#define TOKEN_IS_SEP(type) (type >= JIM_TT_SEP && type <= JIM_TT_EOF)
+
+#define TOKEN_IS_EXPR_START(type) (type == JIM_TT_NONE || type == JIM_TT_SUBEXPR_START || type == JIM_TT_SUBEXPR_COMMA)
+
+#define TOKEN_IS_EXPR_OP(type) (type >= JIM_TT_EXPR_OP)
+
+struct JimParseMissing {
+ int ch;
+ int line;
+};
+
+struct JimParserCtx
+{
+ const char *p;
+ int len;
+ int linenr;
+ const char *tstart;
+ const char *tend;
+ int tline;
+ int tt;
+ int eof;
+ int inquote;
+ int comment;
+ struct JimParseMissing missing;
+};
+
+static int JimParseScript(struct JimParserCtx *pc);
+static int JimParseSep(struct JimParserCtx *pc);
+static int JimParseEol(struct JimParserCtx *pc);
+static int JimParseCmd(struct JimParserCtx *pc);
+static int JimParseQuote(struct JimParserCtx *pc);
+static int JimParseVar(struct JimParserCtx *pc);
+static int JimParseBrace(struct JimParserCtx *pc);
+static int JimParseStr(struct JimParserCtx *pc);
+static int JimParseComment(struct JimParserCtx *pc);
+static void JimParseSubCmd(struct JimParserCtx *pc);
+static int JimParseSubQuote(struct JimParserCtx *pc);
+static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc);
+
+static void JimParserInit(struct JimParserCtx *pc, const char *prg, int len, int linenr)
+{
+ pc->p = prg;
+ pc->len = len;
+ pc->tstart = NULL;
+ pc->tend = NULL;
+ pc->tline = 0;
+ pc->tt = JIM_TT_NONE;
+ pc->eof = 0;
+ pc->inquote = 0;
+ pc->linenr = linenr;
+ pc->comment = 1;
+ pc->missing.ch = ' ';
+ pc->missing.line = linenr;
+}
+
+static int JimParseScript(struct JimParserCtx *pc)
+{
+ while (1) {
+ if (!pc->len) {
+ pc->tstart = pc->p;
+ pc->tend = pc->p - 1;
+ pc->tline = pc->linenr;
+ pc->tt = JIM_TT_EOL;
+ pc->eof = 1;
+ return JIM_OK;
+ }
+ switch (*(pc->p)) {
+ case '\\':
+ if (*(pc->p + 1) == '\n' && !pc->inquote) {
+ return JimParseSep(pc);
+ }
+ pc->comment = 0;
+ return JimParseStr(pc);
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\f':
+ if (!pc->inquote)
+ return JimParseSep(pc);
+ pc->comment = 0;
+ return JimParseStr(pc);
+ case '\n':
+ case ';':
+ pc->comment = 1;
+ if (!pc->inquote)
+ return JimParseEol(pc);
+ return JimParseStr(pc);
+ case '[':
+ pc->comment = 0;
+ return JimParseCmd(pc);
+ case '$':
+ pc->comment = 0;
+ if (JimParseVar(pc) == JIM_ERR) {
+
+ pc->tstart = pc->tend = pc->p++;
+ pc->len--;
+ pc->tt = JIM_TT_ESC;
+ }
+ return JIM_OK;
+ case '#':
+ if (pc->comment) {
+ JimParseComment(pc);
+ continue;
+ }
+ return JimParseStr(pc);
+ default:
+ pc->comment = 0;
+ return JimParseStr(pc);
+ }
+ return JIM_OK;
+ }
+}
+
+static int JimParseSep(struct JimParserCtx *pc)
+{
+ pc->tstart = pc->p;
+ pc->tline = pc->linenr;
+ while (isspace(UCHAR(*pc->p)) || (*pc->p == '\\' && *(pc->p + 1) == '\n')) {
+ if (*pc->p == '\n') {
+ break;
+ }
+ if (*pc->p == '\\') {
+ pc->p++;
+ pc->len--;
+ pc->linenr++;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_SEP;
+ return JIM_OK;
+}
+
+static int JimParseEol(struct JimParserCtx *pc)
+{
+ pc->tstart = pc->p;
+ pc->tline = pc->linenr;
+ while (isspace(UCHAR(*pc->p)) || *pc->p == ';') {
+ if (*pc->p == '\n')
+ pc->linenr++;
+ pc->p++;
+ pc->len--;
+ }
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_EOL;
+ return JIM_OK;
+}
+
+
+static void JimParseSubBrace(struct JimParserCtx *pc)
+{
+ int level = 1;
+
+
+ pc->p++;
+ pc->len--;
+ while (pc->len) {
+ switch (*pc->p) {
+ case '\\':
+ if (pc->len > 1) {
+ if (*++pc->p == '\n') {
+ pc->linenr++;
+ }
+ pc->len--;
+ }
+ break;
+
+ case '{':
+ level++;
+ break;
+
+ case '}':
+ if (--level == 0) {
+ pc->tend = pc->p - 1;
+ pc->p++;
+ pc->len--;
+ return;
+ }
+ break;
+
+ case '\n':
+ pc->linenr++;
+ break;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ pc->missing.ch = '{';
+ pc->missing.line = pc->tline;
+ pc->tend = pc->p - 1;
+}
+
+static int JimParseSubQuote(struct JimParserCtx *pc)
+{
+ int tt = JIM_TT_STR;
+ int line = pc->tline;
+
+
+ pc->p++;
+ pc->len--;
+ while (pc->len) {
+ switch (*pc->p) {
+ case '\\':
+ if (pc->len > 1) {
+ if (*++pc->p == '\n') {
+ pc->linenr++;
+ }
+ pc->len--;
+ tt = JIM_TT_ESC;
+ }
+ break;
+
+ case '"':
+ pc->tend = pc->p - 1;
+ pc->p++;
+ pc->len--;
+ return tt;
+
+ case '[':
+ JimParseSubCmd(pc);
+ tt = JIM_TT_ESC;
+ continue;
+
+ case '\n':
+ pc->linenr++;
+ break;
+
+ case '$':
+ tt = JIM_TT_ESC;
+ break;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ pc->missing.ch = '"';
+ pc->missing.line = line;
+ pc->tend = pc->p - 1;
+ return tt;
+}
+
+static void JimParseSubCmd(struct JimParserCtx *pc)
+{
+ int level = 1;
+ int startofword = 1;
+ int line = pc->tline;
+
+
+ pc->p++;
+ pc->len--;
+ while (pc->len) {
+ switch (*pc->p) {
+ case '\\':
+ if (pc->len > 1) {
+ if (*++pc->p == '\n') {
+ pc->linenr++;
+ }
+ pc->len--;
+ }
+ break;
+
+ case '[':
+ level++;
+ break;
+
+ case ']':
+ if (--level == 0) {
+ pc->tend = pc->p - 1;
+ pc->p++;
+ pc->len--;
+ return;
+ }
+ break;
+
+ case '"':
+ if (startofword) {
+ JimParseSubQuote(pc);
+ continue;
+ }
+ break;
+
+ case '{':
+ JimParseSubBrace(pc);
+ startofword = 0;
+ continue;
+
+ case '\n':
+ pc->linenr++;
+ break;
+ }
+ startofword = isspace(UCHAR(*pc->p));
+ pc->p++;
+ pc->len--;
+ }
+ pc->missing.ch = '[';
+ pc->missing.line = line;
+ pc->tend = pc->p - 1;
+}
+
+static int JimParseBrace(struct JimParserCtx *pc)
+{
+ pc->tstart = pc->p + 1;
+ pc->tline = pc->linenr;
+ pc->tt = JIM_TT_STR;
+ JimParseSubBrace(pc);
+ return JIM_OK;
+}
+
+static int JimParseCmd(struct JimParserCtx *pc)
+{
+ pc->tstart = pc->p + 1;
+ pc->tline = pc->linenr;
+ pc->tt = JIM_TT_CMD;
+ JimParseSubCmd(pc);
+ return JIM_OK;
+}
+
+static int JimParseQuote(struct JimParserCtx *pc)
+{
+ pc->tstart = pc->p + 1;
+ pc->tline = pc->linenr;
+ pc->tt = JimParseSubQuote(pc);
+ return JIM_OK;
+}
+
+static int JimParseVar(struct JimParserCtx *pc)
+{
+
+ pc->p++;
+ pc->len--;
+
+#ifdef EXPRSUGAR_BRACKET
+ if (*pc->p == '[') {
+
+ JimParseCmd(pc);
+ pc->tt = JIM_TT_EXPRSUGAR;
+ return JIM_OK;
+ }
+#endif
+
+ pc->tstart = pc->p;
+ pc->tt = JIM_TT_VAR;
+ pc->tline = pc->linenr;
+
+ if (*pc->p == '{') {
+ pc->tstart = ++pc->p;
+ pc->len--;
+
+ while (pc->len && *pc->p != '}') {
+ if (*pc->p == '\n') {
+ pc->linenr++;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ pc->tend = pc->p - 1;
+ if (pc->len) {
+ pc->p++;
+ pc->len--;
+ }
+ }
+ else {
+ while (1) {
+
+ if (pc->p[0] == ':' && pc->p[1] == ':') {
+ while (*pc->p == ':') {
+ pc->p++;
+ pc->len--;
+ }
+ continue;
+ }
+ if (isalnum(UCHAR(*pc->p)) || *pc->p == '_' || UCHAR(*pc->p) >= 0x80) {
+ pc->p++;
+ pc->len--;
+ continue;
+ }
+ break;
+ }
+
+ if (*pc->p == '(') {
+ int count = 1;
+ const char *paren = NULL;
+
+ pc->tt = JIM_TT_DICTSUGAR;
+
+ while (count && pc->len) {
+ pc->p++;
+ pc->len--;
+ if (*pc->p == '\\' && pc->len >= 1) {
+ pc->p++;
+ pc->len--;
+ }
+ else if (*pc->p == '(') {
+ count++;
+ }
+ else if (*pc->p == ')') {
+ paren = pc->p;
+ count--;
+ }
+ }
+ if (count == 0) {
+ pc->p++;
+ pc->len--;
+ }
+ else if (paren) {
+
+ paren++;
+ pc->len += (pc->p - paren);
+ pc->p = paren;
+ }
+#ifndef EXPRSUGAR_BRACKET
+ if (*pc->tstart == '(') {
+ pc->tt = JIM_TT_EXPRSUGAR;
+ }
+#endif
+ }
+ pc->tend = pc->p - 1;
+ }
+ if (pc->tstart == pc->p) {
+ pc->p--;
+ pc->len++;
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+static int JimParseStr(struct JimParserCtx *pc)
+{
+ if (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
+ pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR) {
+
+ if (*pc->p == '{') {
+ return JimParseBrace(pc);
+ }
+ if (*pc->p == '"') {
+ pc->inquote = 1;
+ pc->p++;
+ pc->len--;
+
+ pc->missing.line = pc->tline;
+ }
+ }
+ pc->tstart = pc->p;
+ pc->tline = pc->linenr;
+ while (1) {
+ if (pc->len == 0) {
+ if (pc->inquote) {
+ pc->missing.ch = '"';
+ }
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_ESC;
+ return JIM_OK;
+ }
+ switch (*pc->p) {
+ case '\\':
+ if (!pc->inquote && *(pc->p + 1) == '\n') {
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_ESC;
+ return JIM_OK;
+ }
+ if (pc->len >= 2) {
+ if (*(pc->p + 1) == '\n') {
+ pc->linenr++;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ else if (pc->len == 1) {
+
+ pc->missing.ch = '\\';
+ }
+ break;
+ case '(':
+
+ if (pc->len > 1 && pc->p[1] != '$') {
+ break;
+ }
+
+ case ')':
+
+ if (*pc->p == '(' || pc->tt == JIM_TT_VAR) {
+ if (pc->p == pc->tstart) {
+
+ pc->p++;
+ pc->len--;
+ }
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_ESC;
+ return JIM_OK;
+ }
+ break;
+
+ case '$':
+ case '[':
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_ESC;
+ return JIM_OK;
+ case ' ':
+ case '\t':
+ case '\n':
+ case '\r':
+ case '\f':
+ case ';':
+ if (!pc->inquote) {
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_ESC;
+ return JIM_OK;
+ }
+ else if (*pc->p == '\n') {
+ pc->linenr++;
+ }
+ break;
+ case '"':
+ if (pc->inquote) {
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_ESC;
+ pc->p++;
+ pc->len--;
+ pc->inquote = 0;
+ return JIM_OK;
+ }
+ break;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ return JIM_OK;
+}
+
+static int JimParseComment(struct JimParserCtx *pc)
+{
+ while (*pc->p) {
+ if (*pc->p == '\\') {
+ pc->p++;
+ pc->len--;
+ if (pc->len == 0) {
+ pc->missing.ch = '\\';
+ return JIM_OK;
+ }
+ if (*pc->p == '\n') {
+ pc->linenr++;
+ }
+ }
+ else if (*pc->p == '\n') {
+ pc->p++;
+ pc->len--;
+ pc->linenr++;
+ break;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ return JIM_OK;
+}
+
+
+static int xdigitval(int c)
+{
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+ return -1;
+}
+
+static int odigitval(int c)
+{
+ if (c >= '0' && c <= '7')
+ return c - '0';
+ return -1;
+}
+
+static int JimEscape(char *dest, const char *s, int slen)
+{
+ char *p = dest;
+ int i, len;
+
+ for (i = 0; i < slen; i++) {
+ switch (s[i]) {
+ case '\\':
+ switch (s[i + 1]) {
+ case 'a':
+ *p++ = 0x7;
+ i++;
+ break;
+ case 'b':
+ *p++ = 0x8;
+ i++;
+ break;
+ case 'f':
+ *p++ = 0xc;
+ i++;
+ break;
+ case 'n':
+ *p++ = 0xa;
+ i++;
+ break;
+ case 'r':
+ *p++ = 0xd;
+ i++;
+ break;
+ case 't':
+ *p++ = 0x9;
+ i++;
+ break;
+ case 'u':
+ case 'U':
+ case 'x':
+ {
+ unsigned val = 0;
+ int k;
+ int maxchars = 2;
+
+ i++;
+
+ if (s[i] == 'U') {
+ maxchars = 8;
+ }
+ else if (s[i] == 'u') {
+ if (s[i + 1] == '{') {
+ maxchars = 6;
+ i++;
+ }
+ else {
+ maxchars = 4;
+ }
+ }
+
+ for (k = 0; k < maxchars; k++) {
+ int c = xdigitval(s[i + k + 1]);
+ if (c == -1) {
+ break;
+ }
+ val = (val << 4) | c;
+ }
+
+ if (s[i] == '{') {
+ if (k == 0 || val > 0x1fffff || s[i + k + 1] != '}') {
+
+ i--;
+ k = 0;
+ }
+ else {
+
+ k++;
+ }
+ }
+ if (k) {
+
+ if (s[i] == 'x') {
+ *p++ = val;
+ }
+ else {
+ p += utf8_fromunicode(p, val);
+ }
+ i += k;
+ break;
+ }
+
+ *p++ = s[i];
+ }
+ break;
+ case 'v':
+ *p++ = 0xb;
+ i++;
+ break;
+ case '\0':
+ *p++ = '\\';
+ i++;
+ break;
+ case '\n':
+
+ *p++ = ' ';
+ do {
+ i++;
+ } while (s[i + 1] == ' ' || s[i + 1] == '\t');
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+
+ {
+ int val = 0;
+ int c = odigitval(s[i + 1]);
+
+ val = c;
+ c = odigitval(s[i + 2]);
+ if (c == -1) {
+ *p++ = val;
+ i++;
+ break;
+ }
+ val = (val * 8) + c;
+ c = odigitval(s[i + 3]);
+ if (c == -1) {
+ *p++ = val;
+ i += 2;
+ break;
+ }
+ val = (val * 8) + c;
+ *p++ = val;
+ i += 3;
+ }
+ break;
+ default:
+ *p++ = s[i + 1];
+ i++;
+ break;
+ }
+ break;
+ default:
+ *p++ = s[i];
+ break;
+ }
+ }
+ len = p - dest;
+ *p = '\0';
+ return len;
+}
+
+static Jim_Obj *JimParserGetTokenObj(Jim_Interp *interp, struct JimParserCtx *pc)
+{
+ const char *start, *end;
+ char *token;
+ int len;
+
+ start = pc->tstart;
+ end = pc->tend;
+ len = (end - start) + 1;
+ if (len < 0) {
+ len = 0;
+ }
+ token = Jim_Alloc(len + 1);
+ if (pc->tt != JIM_TT_ESC) {
+
+ memcpy(token, start, len);
+ token[len] = '\0';
+ }
+ else {
+
+ len = JimEscape(token, start, len);
+ }
+
+ return Jim_NewStringObjNoAlloc(interp, token, len);
+}
+
+static int JimParseListSep(struct JimParserCtx *pc);
+static int JimParseListStr(struct JimParserCtx *pc);
+static int JimParseListQuote(struct JimParserCtx *pc);
+
+static int JimParseList(struct JimParserCtx *pc)
+{
+ if (isspace(UCHAR(*pc->p))) {
+ return JimParseListSep(pc);
+ }
+ switch (*pc->p) {
+ case '"':
+ return JimParseListQuote(pc);
+
+ case '{':
+ return JimParseBrace(pc);
+
+ default:
+ if (pc->len) {
+ return JimParseListStr(pc);
+ }
+ break;
+ }
+
+ pc->tstart = pc->tend = pc->p;
+ pc->tline = pc->linenr;
+ pc->tt = JIM_TT_EOL;
+ pc->eof = 1;
+ return JIM_OK;
+}
+
+static int JimParseListSep(struct JimParserCtx *pc)
+{
+ pc->tstart = pc->p;
+ pc->tline = pc->linenr;
+ while (isspace(UCHAR(*pc->p))) {
+ if (*pc->p == '\n') {
+ pc->linenr++;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_SEP;
+ return JIM_OK;
+}
+
+static int JimParseListQuote(struct JimParserCtx *pc)
+{
+ pc->p++;
+ pc->len--;
+
+ pc->tstart = pc->p;
+ pc->tline = pc->linenr;
+ pc->tt = JIM_TT_STR;
+
+ while (pc->len) {
+ switch (*pc->p) {
+ case '\\':
+ pc->tt = JIM_TT_ESC;
+ if (--pc->len == 0) {
+
+ pc->tend = pc->p;
+ return JIM_OK;
+ }
+ pc->p++;
+ break;
+ case '\n':
+ pc->linenr++;
+ break;
+ case '"':
+ pc->tend = pc->p - 1;
+ pc->p++;
+ pc->len--;
+ return JIM_OK;
+ }
+ pc->p++;
+ pc->len--;
+ }
+
+ pc->tend = pc->p - 1;
+ return JIM_OK;
+}
+
+static int JimParseListStr(struct JimParserCtx *pc)
+{
+ pc->tstart = pc->p;
+ pc->tline = pc->linenr;
+ pc->tt = JIM_TT_STR;
+
+ while (pc->len) {
+ if (isspace(UCHAR(*pc->p))) {
+ pc->tend = pc->p - 1;
+ return JIM_OK;
+ }
+ if (*pc->p == '\\') {
+ if (--pc->len == 0) {
+
+ pc->tend = pc->p;
+ return JIM_OK;
+ }
+ pc->tt = JIM_TT_ESC;
+ pc->p++;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ pc->tend = pc->p - 1;
+ return JIM_OK;
+}
+
+
+
+Jim_Obj *Jim_NewObj(Jim_Interp *interp)
+{
+ Jim_Obj *objPtr;
+
+
+ if (interp->freeList != NULL) {
+
+ objPtr = interp->freeList;
+ interp->freeList = objPtr->nextObjPtr;
+ }
+ else {
+
+ objPtr = Jim_Alloc(sizeof(*objPtr));
+ }
+
+ objPtr->refCount = 0;
+
+
+ objPtr->prevObjPtr = NULL;
+ objPtr->nextObjPtr = interp->liveList;
+ if (interp->liveList)
+ interp->liveList->prevObjPtr = objPtr;
+ interp->liveList = objPtr;
+
+ return objPtr;
+}
+
+void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+
+ JimPanic((objPtr->refCount != 0, "!!!Object %p freed with bad refcount %d, type=%s", objPtr,
+ objPtr->refCount, objPtr->typePtr ? objPtr->typePtr->name : ""));
+
+
+ Jim_FreeIntRep(interp, objPtr);
+
+ if (objPtr->bytes != NULL) {
+ if (objPtr->bytes != JimEmptyStringRep)
+ Jim_Free(objPtr->bytes);
+ }
+
+ if (objPtr->prevObjPtr)
+ objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
+ if (objPtr->nextObjPtr)
+ objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
+ if (interp->liveList == objPtr)
+ interp->liveList = objPtr->nextObjPtr;
+#ifdef JIM_DISABLE_OBJECT_POOL
+ Jim_Free(objPtr);
+#else
+
+ objPtr->prevObjPtr = NULL;
+ objPtr->nextObjPtr = interp->freeList;
+ if (interp->freeList)
+ interp->freeList->prevObjPtr = objPtr;
+ interp->freeList = objPtr;
+ objPtr->refCount = -1;
+#endif
+}
+
+
+void Jim_InvalidateStringRep(Jim_Obj *objPtr)
+{
+ if (objPtr->bytes != NULL) {
+ if (objPtr->bytes != JimEmptyStringRep)
+ Jim_Free(objPtr->bytes);
+ }
+ objPtr->bytes = NULL;
+}
+
+
+Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ Jim_Obj *dupPtr;
+
+ dupPtr = Jim_NewObj(interp);
+ if (objPtr->bytes == NULL) {
+
+ dupPtr->bytes = NULL;
+ }
+ else if (objPtr->length == 0) {
+ dupPtr->bytes = JimEmptyStringRep;
+ dupPtr->length = 0;
+ dupPtr->typePtr = NULL;
+ return dupPtr;
+ }
+ else {
+ dupPtr->bytes = Jim_Alloc(objPtr->length + 1);
+ dupPtr->length = objPtr->length;
+
+ memcpy(dupPtr->bytes, objPtr->bytes, objPtr->length + 1);
+ }
+
+
+ dupPtr->typePtr = objPtr->typePtr;
+ if (objPtr->typePtr != NULL) {
+ if (objPtr->typePtr->dupIntRepProc == NULL) {
+ dupPtr->internalRep = objPtr->internalRep;
+ }
+ else {
+
+ objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
+ }
+ }
+ return dupPtr;
+}
+
+const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
+{
+ if (objPtr->bytes == NULL) {
+
+ JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
+ objPtr->typePtr->updateStringProc(objPtr);
+ }
+ if (lenPtr)
+ *lenPtr = objPtr->length;
+ return objPtr->bytes;
+}
+
+
+int Jim_Length(Jim_Obj *objPtr)
+{
+ if (objPtr->bytes == NULL) {
+
+ Jim_GetString(objPtr, NULL);
+ }
+ return objPtr->length;
+}
+
+
+const char *Jim_String(Jim_Obj *objPtr)
+{
+ if (objPtr->bytes == NULL) {
+
+ Jim_GetString(objPtr, NULL);
+ }
+ return objPtr->bytes;
+}
+
+static void JimSetStringBytes(Jim_Obj *objPtr, const char *str)
+{
+ objPtr->bytes = Jim_StrDup(str);
+ objPtr->length = strlen(str);
+}
+
+static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
+static const Jim_ObjType dictSubstObjType = {
+ "dict-substitution",
+ FreeDictSubstInternalRep,
+ DupDictSubstInternalRep,
+ NULL,
+ JIM_TYPE_NONE,
+};
+
+static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
+static const Jim_ObjType interpolatedObjType = {
+ "interpolated",
+ FreeInterpolatedInternalRep,
+ DupInterpolatedInternalRep,
+ NULL,
+ JIM_TYPE_NONE,
+};
+
+static void FreeInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
+}
+
+static void DupInterpolatedInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+
+ dupPtr->internalRep = srcPtr->internalRep;
+
+ Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.indexObjPtr);
+}
+
+static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static const Jim_ObjType stringObjType = {
+ "string",
+ NULL,
+ DupStringInternalRep,
+ NULL,
+ JIM_TYPE_REFERENCES,
+};
+
+static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ JIM_NOTUSED(interp);
+
+ dupPtr->internalRep.strValue.maxLength = srcPtr->length;
+ dupPtr->internalRep.strValue.charLength = srcPtr->internalRep.strValue.charLength;
+}
+
+static int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ if (objPtr->typePtr != &stringObjType) {
+
+ if (objPtr->bytes == NULL) {
+
+ JimPanic((objPtr->typePtr->updateStringProc == NULL, "UpdateStringProc called against '%s' type.", objPtr->typePtr->name));
+ objPtr->typePtr->updateStringProc(objPtr);
+ }
+
+ Jim_FreeIntRep(interp, objPtr);
+
+ objPtr->typePtr = &stringObjType;
+ objPtr->internalRep.strValue.maxLength = objPtr->length;
+
+ objPtr->internalRep.strValue.charLength = -1;
+ }
+ return JIM_OK;
+}
+
+int Jim_Utf8Length(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+#ifdef JIM_UTF8
+ SetStringFromAny(interp, objPtr);
+
+ if (objPtr->internalRep.strValue.charLength < 0) {
+ objPtr->internalRep.strValue.charLength = utf8_strlen(objPtr->bytes, objPtr->length);
+ }
+ return objPtr->internalRep.strValue.charLength;
+#else
+ return Jim_Length(objPtr);
+#endif
+}
+
+
+Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
+{
+ Jim_Obj *objPtr = Jim_NewObj(interp);
+
+
+ if (len == -1)
+ len = strlen(s);
+
+ if (len == 0) {
+ objPtr->bytes = JimEmptyStringRep;
+ }
+ else {
+ objPtr->bytes = Jim_StrDupLen(s, len);
+ }
+ objPtr->length = len;
+
+
+ objPtr->typePtr = NULL;
+ return objPtr;
+}
+
+
+Jim_Obj *Jim_NewStringObjUtf8(Jim_Interp *interp, const char *s, int charlen)
+{
+#ifdef JIM_UTF8
+
+ int bytelen = utf8_index(s, charlen);
+
+ Jim_Obj *objPtr = Jim_NewStringObj(interp, s, bytelen);
+
+
+ objPtr->typePtr = &stringObjType;
+ objPtr->internalRep.strValue.maxLength = bytelen;
+ objPtr->internalRep.strValue.charLength = charlen;
+
+ return objPtr;
+#else
+ return Jim_NewStringObj(interp, s, charlen);
+#endif
+}
+
+Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
+{
+ Jim_Obj *objPtr = Jim_NewObj(interp);
+
+ objPtr->bytes = s;
+ objPtr->length = (len == -1) ? strlen(s) : len;
+ objPtr->typePtr = NULL;
+ return objPtr;
+}
+
+static void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
+{
+ int needlen;
+
+ if (len == -1)
+ len = strlen(str);
+ needlen = objPtr->length + len;
+ if (objPtr->internalRep.strValue.maxLength < needlen ||
+ objPtr->internalRep.strValue.maxLength == 0) {
+ needlen *= 2;
+
+ if (needlen < 7) {
+ needlen = 7;
+ }
+ if (objPtr->bytes == JimEmptyStringRep) {
+ objPtr->bytes = Jim_Alloc(needlen + 1);
+ }
+ else {
+ objPtr->bytes = Jim_Realloc(objPtr->bytes, needlen + 1);
+ }
+ objPtr->internalRep.strValue.maxLength = needlen;
+ }
+ memcpy(objPtr->bytes + objPtr->length, str, len);
+ objPtr->bytes[objPtr->length + len] = '\0';
+
+ if (objPtr->internalRep.strValue.charLength >= 0) {
+
+ objPtr->internalRep.strValue.charLength += utf8_strlen(objPtr->bytes + objPtr->length, len);
+ }
+ objPtr->length += len;
+}
+
+void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str, int len)
+{
+ JimPanic((Jim_IsShared(objPtr), "Jim_AppendString called with shared object"));
+ SetStringFromAny(interp, objPtr);
+ StringAppendString(objPtr, str, len);
+}
+
+void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
+{
+ int len;
+ const char *str = Jim_GetString(appendObjPtr, &len);
+ Jim_AppendString(interp, objPtr, str, len);
+}
+
+void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
+{
+ va_list ap;
+
+ SetStringFromAny(interp, objPtr);
+ va_start(ap, objPtr);
+ while (1) {
+ const char *s = va_arg(ap, const char *);
+
+ if (s == NULL)
+ break;
+ Jim_AppendString(interp, objPtr, s, -1);
+ }
+ va_end(ap);
+}
+
+int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr)
+{
+ if (aObjPtr == bObjPtr) {
+ return 1;
+ }
+ else {
+ int Alen, Blen;
+ const char *sA = Jim_GetString(aObjPtr, &Alen);
+ const char *sB = Jim_GetString(bObjPtr, &Blen);
+
+ return Alen == Blen && memcmp(sA, sB, Alen) == 0;
+ }
+}
+
+int Jim_StringMatchObj(Jim_Interp *interp, Jim_Obj *patternObjPtr, Jim_Obj *objPtr, int nocase)
+{
+ return JimGlobMatch(Jim_String(patternObjPtr), Jim_String(objPtr), nocase);
+}
+
+int Jim_StringCompareObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
+{
+ int l1, l2;
+ const char *s1 = Jim_GetString(firstObjPtr, &l1);
+ const char *s2 = Jim_GetString(secondObjPtr, &l2);
+
+ if (nocase) {
+
+ return JimStringCompareLen(s1, s2, -1, nocase);
+ }
+ return JimStringCompare(s1, l1, s2, l2);
+}
+
+int Jim_StringCompareLenObj(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *secondObjPtr, int nocase)
+{
+ const char *s1 = Jim_String(firstObjPtr);
+ const char *s2 = Jim_String(secondObjPtr);
+
+ return JimStringCompareLen(s1, s2, Jim_Utf8Length(interp, firstObjPtr), nocase);
+}
+
+static int JimRelToAbsIndex(int len, int idx)
+{
+ if (idx < 0)
+ return len + idx;
+ return idx;
+}
+
+static void JimRelToAbsRange(int len, int *firstPtr, int *lastPtr, int *rangeLenPtr)
+{
+ int rangeLen;
+
+ if (*firstPtr > *lastPtr) {
+ rangeLen = 0;
+ }
+ else {
+ rangeLen = *lastPtr - *firstPtr + 1;
+ if (rangeLen) {
+ if (*firstPtr < 0) {
+ rangeLen += *firstPtr;
+ *firstPtr = 0;
+ }
+ if (*lastPtr >= len) {
+ rangeLen -= (*lastPtr - (len - 1));
+ *lastPtr = len - 1;
+ }
+ }
+ }
+ if (rangeLen < 0)
+ rangeLen = 0;
+
+ *rangeLenPtr = rangeLen;
+}
+
+static int JimStringGetRange(Jim_Interp *interp, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr,
+ int len, int *first, int *last, int *range)
+{
+ if (Jim_GetIndex(interp, firstObjPtr, first) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (Jim_GetIndex(interp, lastObjPtr, last) != JIM_OK) {
+ return JIM_ERR;
+ }
+ *first = JimRelToAbsIndex(len, *first);
+ *last = JimRelToAbsIndex(len, *last);
+ JimRelToAbsRange(len, first, last, range);
+ return JIM_OK;
+}
+
+Jim_Obj *Jim_StringByteRangeObj(Jim_Interp *interp,
+ Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
+{
+ int first, last;
+ const char *str;
+ int rangeLen;
+ int bytelen;
+
+ str = Jim_GetString(strObjPtr, &bytelen);
+
+ if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, bytelen, &first, &last, &rangeLen) != JIM_OK) {
+ return NULL;
+ }
+
+ if (first == 0 && rangeLen == bytelen) {
+ return strObjPtr;
+ }
+ return Jim_NewStringObj(interp, str + first, rangeLen);
+}
+
+Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
+ Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
+{
+#ifdef JIM_UTF8
+ int first, last;
+ const char *str;
+ int len, rangeLen;
+ int bytelen;
+
+ str = Jim_GetString(strObjPtr, &bytelen);
+ len = Jim_Utf8Length(interp, strObjPtr);
+
+ if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
+ return NULL;
+ }
+
+ if (first == 0 && rangeLen == len) {
+ return strObjPtr;
+ }
+ if (len == bytelen) {
+
+ return Jim_NewStringObj(interp, str + first, rangeLen);
+ }
+ return Jim_NewStringObjUtf8(interp, str + utf8_index(str, first), rangeLen);
+#else
+ return Jim_StringByteRangeObj(interp, strObjPtr, firstObjPtr, lastObjPtr);
+#endif
+}
+
+Jim_Obj *JimStringReplaceObj(Jim_Interp *interp,
+ Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr, Jim_Obj *newStrObj)
+{
+ int first, last;
+ const char *str;
+ int len, rangeLen;
+ Jim_Obj *objPtr;
+
+ len = Jim_Utf8Length(interp, strObjPtr);
+
+ if (JimStringGetRange(interp, firstObjPtr, lastObjPtr, len, &first, &last, &rangeLen) != JIM_OK) {
+ return NULL;
+ }
+
+ if (last < first) {
+ return strObjPtr;
+ }
+
+ str = Jim_String(strObjPtr);
+
+
+ objPtr = Jim_NewStringObjUtf8(interp, str, first);
+
+
+ if (newStrObj) {
+ Jim_AppendObj(interp, objPtr, newStrObj);
+ }
+
+
+ Jim_AppendString(interp, objPtr, str + utf8_index(str, last + 1), len - last - 1);
+
+ return objPtr;
+}
+
+static void JimStrCopyUpperLower(char *dest, const char *str, int uc)
+{
+ while (*str) {
+ int c;
+ str += utf8_tounicode(str, &c);
+ dest += utf8_getchars(dest, uc ? utf8_upper(c) : utf8_lower(c));
+ }
+ *dest = 0;
+}
+
+static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
+{
+ char *buf;
+ int len;
+ const char *str;
+
+ str = Jim_GetString(strObjPtr, &len);
+
+#ifdef JIM_UTF8
+ len *= 2;
+#endif
+ buf = Jim_Alloc(len + 1);
+ JimStrCopyUpperLower(buf, str, 0);
+ return Jim_NewStringObjNoAlloc(interp, buf, -1);
+}
+
+static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
+{
+ char *buf;
+ const char *str;
+ int len;
+
+ str = Jim_GetString(strObjPtr, &len);
+
+#ifdef JIM_UTF8
+ len *= 2;
+#endif
+ buf = Jim_Alloc(len + 1);
+ JimStrCopyUpperLower(buf, str, 1);
+ return Jim_NewStringObjNoAlloc(interp, buf, -1);
+}
+
+static Jim_Obj *JimStringToTitle(Jim_Interp *interp, Jim_Obj *strObjPtr)
+{
+ char *buf, *p;
+ int len;
+ int c;
+ const char *str;
+
+ str = Jim_GetString(strObjPtr, &len);
+
+#ifdef JIM_UTF8
+ len *= 2;
+#endif
+ buf = p = Jim_Alloc(len + 1);
+
+ str += utf8_tounicode(str, &c);
+ p += utf8_getchars(p, utf8_title(c));
+
+ JimStrCopyUpperLower(p, str, 0);
+
+ return Jim_NewStringObjNoAlloc(interp, buf, -1);
+}
+
+static const char *utf8_memchr(const char *str, int len, int c)
+{
+#ifdef JIM_UTF8
+ while (len) {
+ int sc;
+ int n = utf8_tounicode(str, &sc);
+ if (sc == c) {
+ return str;
+ }
+ str += n;
+ len -= n;
+ }
+ return NULL;
+#else
+ return memchr(str, c, len);
+#endif
+}
+
+static const char *JimFindTrimLeft(const char *str, int len, const char *trimchars, int trimlen)
+{
+ while (len) {
+ int c;
+ int n = utf8_tounicode(str, &c);
+
+ if (utf8_memchr(trimchars, trimlen, c) == NULL) {
+
+ break;
+ }
+ str += n;
+ len -= n;
+ }
+ return str;
+}
+
+static const char *JimFindTrimRight(const char *str, int len, const char *trimchars, int trimlen)
+{
+ str += len;
+
+ while (len) {
+ int c;
+ int n = utf8_prev_len(str, len);
+
+ len -= n;
+ str -= n;
+
+ n = utf8_tounicode(str, &c);
+
+ if (utf8_memchr(trimchars, trimlen, c) == NULL) {
+ return str + n;
+ }
+ }
+
+ return NULL;
+}
+
+static const char default_trim_chars[] = " \t\n\r";
+
+static int default_trim_chars_len = sizeof(default_trim_chars);
+
+static Jim_Obj *JimStringTrimLeft(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
+{
+ int len;
+ const char *str = Jim_GetString(strObjPtr, &len);
+ const char *trimchars = default_trim_chars;
+ int trimcharslen = default_trim_chars_len;
+ const char *newstr;
+
+ if (trimcharsObjPtr) {
+ trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
+ }
+
+ newstr = JimFindTrimLeft(str, len, trimchars, trimcharslen);
+ if (newstr == str) {
+ return strObjPtr;
+ }
+
+ return Jim_NewStringObj(interp, newstr, len - (newstr - str));
+}
+
+static Jim_Obj *JimStringTrimRight(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
+{
+ int len;
+ const char *trimchars = default_trim_chars;
+ int trimcharslen = default_trim_chars_len;
+ const char *nontrim;
+
+ if (trimcharsObjPtr) {
+ trimchars = Jim_GetString(trimcharsObjPtr, &trimcharslen);
+ }
+
+ SetStringFromAny(interp, strObjPtr);
+
+ len = Jim_Length(strObjPtr);
+ nontrim = JimFindTrimRight(strObjPtr->bytes, len, trimchars, trimcharslen);
+
+ if (nontrim == NULL) {
+
+ return Jim_NewEmptyStringObj(interp);
+ }
+ if (nontrim == strObjPtr->bytes + len) {
+
+ return strObjPtr;
+ }
+
+ if (Jim_IsShared(strObjPtr)) {
+ strObjPtr = Jim_NewStringObj(interp, strObjPtr->bytes, (nontrim - strObjPtr->bytes));
+ }
+ else {
+
+ strObjPtr->bytes[nontrim - strObjPtr->bytes] = 0;
+ strObjPtr->length = (nontrim - strObjPtr->bytes);
+ }
+
+ return strObjPtr;
+}
+
+static Jim_Obj *JimStringTrim(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *trimcharsObjPtr)
+{
+
+ Jim_Obj *objPtr = JimStringTrimLeft(interp, strObjPtr, trimcharsObjPtr);
+
+
+ strObjPtr = JimStringTrimRight(interp, objPtr, trimcharsObjPtr);
+
+
+ if (objPtr != strObjPtr && objPtr->refCount == 0) {
+
+ Jim_FreeNewObj(interp, objPtr);
+ }
+
+ return strObjPtr;
+}
+
+
+#ifdef HAVE_ISASCII
+#define jim_isascii isascii
+#else
+static int jim_isascii(int c)
+{
+ return !(c & ~0x7f);
+}
+#endif
+
+static int JimStringIs(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *strClass, int strict)
+{
+ static const char * const strclassnames[] = {
+ "integer", "alpha", "alnum", "ascii", "digit",
+ "double", "lower", "upper", "space", "xdigit",
+ "control", "print", "graph", "punct", "boolean",
+ NULL
+ };
+ enum {
+ STR_IS_INTEGER, STR_IS_ALPHA, STR_IS_ALNUM, STR_IS_ASCII, STR_IS_DIGIT,
+ STR_IS_DOUBLE, STR_IS_LOWER, STR_IS_UPPER, STR_IS_SPACE, STR_IS_XDIGIT,
+ STR_IS_CONTROL, STR_IS_PRINT, STR_IS_GRAPH, STR_IS_PUNCT, STR_IS_BOOLEAN,
+ };
+ int strclass;
+ int len;
+ int i;
+ const char *str;
+ int (*isclassfunc)(int c) = NULL;
+
+ if (Jim_GetEnum(interp, strClass, strclassnames, &strclass, "class", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ str = Jim_GetString(strObjPtr, &len);
+ if (len == 0) {
+ Jim_SetResultBool(interp, !strict);
+ return JIM_OK;
+ }
+
+ switch (strclass) {
+ case STR_IS_INTEGER:
+ {
+ jim_wide w;
+ Jim_SetResultBool(interp, JimGetWideNoErr(interp, strObjPtr, &w) == JIM_OK);
+ return JIM_OK;
+ }
+
+ case STR_IS_DOUBLE:
+ {
+ double d;
+ Jim_SetResultBool(interp, Jim_GetDouble(interp, strObjPtr, &d) == JIM_OK && errno != ERANGE);
+ return JIM_OK;
+ }
+
+ case STR_IS_BOOLEAN:
+ {
+ int b;
+ Jim_SetResultBool(interp, Jim_GetBoolean(interp, strObjPtr, &b) == JIM_OK);
+ return JIM_OK;
+ }
+
+ case STR_IS_ALPHA: isclassfunc = isalpha; break;
+ case STR_IS_ALNUM: isclassfunc = isalnum; break;
+ case STR_IS_ASCII: isclassfunc = jim_isascii; break;
+ case STR_IS_DIGIT: isclassfunc = isdigit; break;
+ case STR_IS_LOWER: isclassfunc = islower; break;
+ case STR_IS_UPPER: isclassfunc = isupper; break;
+ case STR_IS_SPACE: isclassfunc = isspace; break;
+ case STR_IS_XDIGIT: isclassfunc = isxdigit; break;
+ case STR_IS_CONTROL: isclassfunc = iscntrl; break;
+ case STR_IS_PRINT: isclassfunc = isprint; break;
+ case STR_IS_GRAPH: isclassfunc = isgraph; break;
+ case STR_IS_PUNCT: isclassfunc = ispunct; break;
+ default:
+ return JIM_ERR;
+ }
+
+ for (i = 0; i < len; i++) {
+ if (!isclassfunc(UCHAR(str[i]))) {
+ Jim_SetResultBool(interp, 0);
+ return JIM_OK;
+ }
+ }
+ Jim_SetResultBool(interp, 1);
+ return JIM_OK;
+}
+
+
+
+static const Jim_ObjType comparedStringObjType = {
+ "compared-string",
+ NULL,
+ NULL,
+ NULL,
+ JIM_TYPE_REFERENCES,
+};
+
+int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr, const char *str)
+{
+ if (objPtr->typePtr == &comparedStringObjType && objPtr->internalRep.ptr == str) {
+ return 1;
+ }
+ else {
+ if (strcmp(str, Jim_String(objPtr)) != 0)
+ return 0;
+
+ if (objPtr->typePtr != &comparedStringObjType) {
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &comparedStringObjType;
+ }
+ objPtr->internalRep.ptr = (char *)str;
+ return 1;
+ }
+}
+
+static int qsortCompareStringPointers(const void *a, const void *b)
+{
+ char *const *sa = (char *const *)a;
+ char *const *sb = (char *const *)b;
+
+ return strcmp(*sa, *sb);
+}
+
+
+
+static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
+static const Jim_ObjType sourceObjType = {
+ "source",
+ FreeSourceInternalRep,
+ DupSourceInternalRep,
+ NULL,
+ JIM_TYPE_REFERENCES,
+};
+
+void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ Jim_DecrRefCount(interp, objPtr->internalRep.sourceValue.fileNameObj);
+}
+
+void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ dupPtr->internalRep.sourceValue = srcPtr->internalRep.sourceValue;
+ Jim_IncrRefCount(dupPtr->internalRep.sourceValue.fileNameObj);
+}
+
+static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
+ Jim_Obj *fileNameObj, int lineNumber)
+{
+ JimPanic((Jim_IsShared(objPtr), "JimSetSourceInfo called with shared object"));
+ JimPanic((objPtr->typePtr != NULL, "JimSetSourceInfo called with typed object"));
+ Jim_IncrRefCount(fileNameObj);
+ objPtr->internalRep.sourceValue.fileNameObj = fileNameObj;
+ objPtr->internalRep.sourceValue.lineNumber = lineNumber;
+ objPtr->typePtr = &sourceObjType;
+}
+
+static const Jim_ObjType scriptLineObjType = {
+ "scriptline",
+ NULL,
+ NULL,
+ NULL,
+ JIM_NONE,
+};
+
+static Jim_Obj *JimNewScriptLineObj(Jim_Interp *interp, int argc, int line)
+{
+ Jim_Obj *objPtr;
+
+#ifdef DEBUG_SHOW_SCRIPT
+ char buf[100];
+ snprintf(buf, sizeof(buf), "line=%d, argc=%d", line, argc);
+ objPtr = Jim_NewStringObj(interp, buf, -1);
+#else
+ objPtr = Jim_NewEmptyStringObj(interp);
+#endif
+ objPtr->typePtr = &scriptLineObjType;
+ objPtr->internalRep.scriptLineValue.argc = argc;
+ objPtr->internalRep.scriptLineValue.line = line;
+
+ return objPtr;
+}
+
+static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
+static const Jim_ObjType scriptObjType = {
+ "script",
+ FreeScriptInternalRep,
+ DupScriptInternalRep,
+ NULL,
+ JIM_TYPE_REFERENCES,
+};
+
+typedef struct ScriptToken
+{
+ Jim_Obj *objPtr;
+ int type;
+} ScriptToken;
+
+typedef struct ScriptObj
+{
+ ScriptToken *token;
+ Jim_Obj *fileNameObj;
+ int len;
+ int substFlags;
+ int inUse; /* Used to share a ScriptObj. Currently
+ only used by Jim_EvalObj() as protection against
+ shimmering of the currently evaluated object. */
+ int firstline;
+ int linenr;
+ int missing;
+} ScriptObj;
+
+static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+static int JimParseCheckMissing(Jim_Interp *interp, int ch);
+static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr);
+
+void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ int i;
+ struct ScriptObj *script = (void *)objPtr->internalRep.ptr;
+
+ if (--script->inUse != 0)
+ return;
+ for (i = 0; i < script->len; i++) {
+ Jim_DecrRefCount(interp, script->token[i].objPtr);
+ }
+ Jim_Free(script->token);
+ Jim_DecrRefCount(interp, script->fileNameObj);
+ Jim_Free(script);
+}
+
+void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ JIM_NOTUSED(interp);
+ JIM_NOTUSED(srcPtr);
+
+ dupPtr->typePtr = NULL;
+}
+
+typedef struct
+{
+ const char *token;
+ int len;
+ int type;
+ int line;
+} ParseToken;
+
+typedef struct
+{
+
+ ParseToken *list;
+ int size;
+ int count;
+ ParseToken static_list[20];
+} ParseTokenList;
+
+static void ScriptTokenListInit(ParseTokenList *tokenlist)
+{
+ tokenlist->list = tokenlist->static_list;
+ tokenlist->size = sizeof(tokenlist->static_list) / sizeof(ParseToken);
+ tokenlist->count = 0;
+}
+
+static void ScriptTokenListFree(ParseTokenList *tokenlist)
+{
+ if (tokenlist->list != tokenlist->static_list) {
+ Jim_Free(tokenlist->list);
+ }
+}
+
+static void ScriptAddToken(ParseTokenList *tokenlist, const char *token, int len, int type,
+ int line)
+{
+ ParseToken *t;
+
+ if (tokenlist->count == tokenlist->size) {
+
+ tokenlist->size *= 2;
+ if (tokenlist->list != tokenlist->static_list) {
+ tokenlist->list =
+ Jim_Realloc(tokenlist->list, tokenlist->size * sizeof(*tokenlist->list));
+ }
+ else {
+
+ tokenlist->list = Jim_Alloc(tokenlist->size * sizeof(*tokenlist->list));
+ memcpy(tokenlist->list, tokenlist->static_list,
+ tokenlist->count * sizeof(*tokenlist->list));
+ }
+ }
+ t = &tokenlist->list[tokenlist->count++];
+ t->token = token;
+ t->len = len;
+ t->type = type;
+ t->line = line;
+}
+
+static int JimCountWordTokens(struct ScriptObj *script, ParseToken *t)
+{
+ int expand = 1;
+ int count = 0;
+
+
+ if (t->type == JIM_TT_STR && !TOKEN_IS_SEP(t[1].type)) {
+ if ((t->len == 1 && *t->token == '*') || (t->len == 6 && strncmp(t->token, "expand", 6) == 0)) {
+
+ expand = -1;
+ t++;
+ }
+ else {
+ if (script->missing == ' ') {
+
+ script->missing = '}';
+ script->linenr = t[1].line;
+ }
+ }
+ }
+
+
+ while (!TOKEN_IS_SEP(t->type)) {
+ t++;
+ count++;
+ }
+
+ return count * expand;
+}
+
+static Jim_Obj *JimMakeScriptObj(Jim_Interp *interp, const ParseToken *t)
+{
+ Jim_Obj *objPtr;
+
+ if (t->type == JIM_TT_ESC && memchr(t->token, '\\', t->len) != NULL) {
+
+ int len = t->len;
+ char *str = Jim_Alloc(len + 1);
+ len = JimEscape(str, t->token, len);
+ objPtr = Jim_NewStringObjNoAlloc(interp, str, len);
+ }
+ else {
+ objPtr = Jim_NewStringObj(interp, t->token, t->len);
+ }
+ return objPtr;
+}
+
+static void ScriptObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
+ ParseTokenList *tokenlist)
+{
+ int i;
+ struct ScriptToken *token;
+
+ int lineargs = 0;
+
+ ScriptToken *linefirst;
+ int count;
+ int linenr;
+
+#ifdef DEBUG_SHOW_SCRIPT_TOKENS
+ printf("==== Tokens ====\n");
+ for (i = 0; i < tokenlist->count; i++) {
+ printf("[%2d]@%d %s '%.*s'\n", i, tokenlist->list[i].line, jim_tt_name(tokenlist->list[i].type),
+ tokenlist->list[i].len, tokenlist->list[i].token);
+ }
+#endif
+
+
+ count = tokenlist->count;
+ for (i = 0; i < tokenlist->count; i++) {
+ if (tokenlist->list[i].type == JIM_TT_EOL) {
+ count++;
+ }
+ }
+ linenr = script->firstline = tokenlist->list[0].line;
+
+ token = script->token = Jim_Alloc(sizeof(ScriptToken) * count);
+
+
+ linefirst = token++;
+
+ for (i = 0; i < tokenlist->count; ) {
+
+ int wordtokens;
+
+
+ while (tokenlist->list[i].type == JIM_TT_SEP) {
+ i++;
+ }
+
+ wordtokens = JimCountWordTokens(script, tokenlist->list + i);
+
+ if (wordtokens == 0) {
+
+ if (lineargs) {
+ linefirst->type = JIM_TT_LINE;
+ linefirst->objPtr = JimNewScriptLineObj(interp, lineargs, linenr);
+ Jim_IncrRefCount(linefirst->objPtr);
+
+
+ lineargs = 0;
+ linefirst = token++;
+ }
+ i++;
+ continue;
+ }
+ else if (wordtokens != 1) {
+
+ token->type = JIM_TT_WORD;
+ token->objPtr = Jim_NewIntObj(interp, wordtokens);
+ Jim_IncrRefCount(token->objPtr);
+ token++;
+ if (wordtokens < 0) {
+
+ i++;
+ wordtokens = -wordtokens - 1;
+ lineargs--;
+ }
+ }
+
+ if (lineargs == 0) {
+
+ linenr = tokenlist->list[i].line;
+ }
+ lineargs++;
+
+
+ while (wordtokens--) {
+ const ParseToken *t = &tokenlist->list[i++];
+
+ token->type = t->type;
+ token->objPtr = JimMakeScriptObj(interp, t);
+ Jim_IncrRefCount(token->objPtr);
+
+ JimSetSourceInfo(interp, token->objPtr, script->fileNameObj, t->line);
+ token++;
+ }
+ }
+
+ if (lineargs == 0) {
+ token--;
+ }
+
+ script->len = token - script->token;
+
+ JimPanic((script->len >= count, "allocated script array is too short"));
+
+#ifdef DEBUG_SHOW_SCRIPT
+ printf("==== Script (%s) ====\n", Jim_String(script->fileNameObj));
+ for (i = 0; i < script->len; i++) {
+ const ScriptToken *t = &script->token[i];
+ printf("[%2d] %s %s\n", i, jim_tt_name(t->type), Jim_String(t->objPtr));
+ }
+#endif
+
+}
+
+int Jim_ScriptIsComplete(Jim_Interp *interp, Jim_Obj *scriptObj, char *stateCharPtr)
+{
+ ScriptObj *script = JimGetScript(interp, scriptObj);
+ if (stateCharPtr) {
+ *stateCharPtr = script->missing;
+ }
+ return script->missing == ' ' || script->missing == '}';
+}
+
+static int JimParseCheckMissing(Jim_Interp *interp, int ch)
+{
+ const char *msg;
+
+ switch (ch) {
+ case '\\':
+ case ' ':
+ return JIM_OK;
+
+ case '[':
+ msg = "unmatched \"[\"";
+ break;
+ case '{':
+ msg = "missing close-brace";
+ break;
+ case '}':
+ msg = "extra characters after close-brace";
+ break;
+ case '"':
+ default:
+ msg = "missing quote";
+ break;
+ }
+
+ Jim_SetResultString(interp, msg, -1);
+ return JIM_ERR;
+}
+
+static void SubstObjAddTokens(Jim_Interp *interp, struct ScriptObj *script,
+ ParseTokenList *tokenlist)
+{
+ int i;
+ struct ScriptToken *token;
+
+ token = script->token = Jim_Alloc(sizeof(ScriptToken) * tokenlist->count);
+
+ for (i = 0; i < tokenlist->count; i++) {
+ const ParseToken *t = &tokenlist->list[i];
+
+
+ token->type = t->type;
+ token->objPtr = JimMakeScriptObj(interp, t);
+ Jim_IncrRefCount(token->objPtr);
+ token++;
+ }
+
+ script->len = i;
+}
+
+static void JimSetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+ int scriptTextLen;
+ const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
+ struct JimParserCtx parser;
+ struct ScriptObj *script;
+ ParseTokenList tokenlist;
+ int line = 1;
+
+
+ if (objPtr->typePtr == &sourceObjType) {
+ line = objPtr->internalRep.sourceValue.lineNumber;
+ }
+
+
+ ScriptTokenListInit(&tokenlist);
+
+ JimParserInit(&parser, scriptText, scriptTextLen, line);
+ while (!parser.eof) {
+ JimParseScript(&parser);
+ ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
+ parser.tline);
+ }
+
+
+ ScriptAddToken(&tokenlist, scriptText + scriptTextLen, 0, JIM_TT_EOF, 0);
+
+
+ script = Jim_Alloc(sizeof(*script));
+ memset(script, 0, sizeof(*script));
+ script->inUse = 1;
+ if (objPtr->typePtr == &sourceObjType) {
+ script->fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
+ }
+ else {
+ script->fileNameObj = interp->emptyObj;
+ }
+ Jim_IncrRefCount(script->fileNameObj);
+ script->missing = parser.missing.ch;
+ script->linenr = parser.missing.line;
+
+ ScriptObjAddTokens(interp, script, &tokenlist);
+
+
+ ScriptTokenListFree(&tokenlist);
+
+
+ Jim_FreeIntRep(interp, objPtr);
+ Jim_SetIntRepPtr(objPtr, script);
+ objPtr->typePtr = &scriptObjType;
+}
+
+static void JimAddErrorToStack(Jim_Interp *interp, ScriptObj *script);
+
+static ScriptObj *JimGetScript(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ if (objPtr == interp->emptyObj) {
+
+ objPtr = interp->nullScriptObj;
+ }
+
+ if (objPtr->typePtr != &scriptObjType || ((struct ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags) {
+ JimSetScriptFromAny(interp, objPtr);
+ }
+
+ return (ScriptObj *)Jim_GetIntRepPtr(objPtr);
+}
+
+static int JimScriptValid(Jim_Interp *interp, ScriptObj *script)
+{
+ if (JimParseCheckMissing(interp, script->missing) == JIM_ERR) {
+ JimAddErrorToStack(interp, script);
+ return 0;
+ }
+ return 1;
+}
+
+
+static void JimIncrCmdRefCount(Jim_Cmd *cmdPtr)
+{
+ cmdPtr->inUse++;
+}
+
+static void JimDecrCmdRefCount(Jim_Interp *interp, Jim_Cmd *cmdPtr)
+{
+ if (--cmdPtr->inUse == 0) {
+ if (cmdPtr->isproc) {
+ Jim_DecrRefCount(interp, cmdPtr->u.proc.argListObjPtr);
+ Jim_DecrRefCount(interp, cmdPtr->u.proc.bodyObjPtr);
+ Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
+ if (cmdPtr->u.proc.staticVars) {
+ Jim_FreeHashTable(cmdPtr->u.proc.staticVars);
+ Jim_Free(cmdPtr->u.proc.staticVars);
+ }
+ }
+ else {
+
+ if (cmdPtr->u.native.delProc) {
+ cmdPtr->u.native.delProc(interp, cmdPtr->u.native.privData);
+ }
+ }
+ if (cmdPtr->prevCmd) {
+
+ JimDecrCmdRefCount(interp, cmdPtr->prevCmd);
+ }
+ Jim_Free(cmdPtr);
+ }
+}
+
+static void JimVariablesHTValDestructor(void *interp, void *val)
+{
+ Jim_DecrRefCount(interp, ((Jim_Var *)val)->objPtr);
+ Jim_Free(val);
+}
+
+static const Jim_HashTableType JimVariablesHashTableType = {
+ JimStringCopyHTHashFunction,
+ JimStringCopyHTDup,
+ NULL,
+ JimStringCopyHTKeyCompare,
+ JimStringCopyHTKeyDestructor,
+ JimVariablesHTValDestructor
+};
+
+static void JimCommandsHT_ValDestructor(void *interp, void *val)
+{
+ JimDecrCmdRefCount(interp, val);
+}
+
+static const Jim_HashTableType JimCommandsHashTableType = {
+ JimStringCopyHTHashFunction,
+ JimStringCopyHTDup,
+ NULL,
+ JimStringCopyHTKeyCompare,
+ JimStringCopyHTKeyDestructor,
+ JimCommandsHT_ValDestructor
+};
+
+
+
+#ifdef jim_ext_namespace
+static Jim_Obj *JimQualifyNameObj(Jim_Interp *interp, Jim_Obj *nsObj)
+{
+ const char *name = Jim_String(nsObj);
+ if (name[0] == ':' && name[1] == ':') {
+
+ while (*++name == ':') {
+ }
+ nsObj = Jim_NewStringObj(interp, name, -1);
+ }
+ else if (Jim_Length(interp->framePtr->nsObj)) {
+
+ nsObj = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
+ Jim_AppendStrings(interp, nsObj, "::", name, NULL);
+ }
+ return nsObj;
+}
+
+Jim_Obj *Jim_MakeGlobalNamespaceName(Jim_Interp *interp, Jim_Obj *nameObjPtr)
+{
+ Jim_Obj *resultObj;
+
+ const char *name = Jim_String(nameObjPtr);
+ if (name[0] == ':' && name[1] == ':') {
+ return nameObjPtr;
+ }
+ Jim_IncrRefCount(nameObjPtr);
+ resultObj = Jim_NewStringObj(interp, "::", -1);
+ Jim_AppendObj(interp, resultObj, nameObjPtr);
+ Jim_DecrRefCount(interp, nameObjPtr);
+
+ return resultObj;
+}
+
+static const char *JimQualifyName(Jim_Interp *interp, const char *name, Jim_Obj **objPtrPtr)
+{
+ Jim_Obj *objPtr = interp->emptyObj;
+
+ if (name[0] == ':' && name[1] == ':') {
+
+ while (*++name == ':') {
+ }
+ }
+ else if (Jim_Length(interp->framePtr->nsObj)) {
+
+ objPtr = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
+ Jim_AppendStrings(interp, objPtr, "::", name, NULL);
+ name = Jim_String(objPtr);
+ }
+ Jim_IncrRefCount(objPtr);
+ *objPtrPtr = objPtr;
+ return name;
+}
+
+ #define JimFreeQualifiedName(INTERP, OBJ) Jim_DecrRefCount((INTERP), (OBJ))
+
+#else
+
+ #define JimQualifyName(INTERP, NAME, DUMMY) (((NAME)[0] == ':' && (NAME)[1] == ':') ? (NAME) + 2 : (NAME))
+ #define JimFreeQualifiedName(INTERP, DUMMY) (void)(DUMMY)
+
+Jim_Obj *Jim_MakeGlobalNamespaceName(Jim_Interp *interp, Jim_Obj *nameObjPtr)
+{
+ return nameObjPtr;
+}
+#endif
+
+static int JimCreateCommand(Jim_Interp *interp, const char *name, Jim_Cmd *cmd)
+{
+ Jim_HashEntry *he = Jim_FindHashEntry(&interp->commands, name);
+ if (he) {
+
+ Jim_InterpIncrProcEpoch(interp);
+ }
+
+ if (he && interp->local) {
+
+ cmd->prevCmd = Jim_GetHashEntryVal(he);
+ Jim_SetHashVal(&interp->commands, he, cmd);
+ }
+ else {
+ if (he) {
+
+ Jim_DeleteHashEntry(&interp->commands, name);
+ }
+
+ Jim_AddHashEntry(&interp->commands, name, cmd);
+ }
+ return JIM_OK;
+}
+
+
+int Jim_CreateCommand(Jim_Interp *interp, const char *cmdNameStr,
+ Jim_CmdProc *cmdProc, void *privData, Jim_DelCmdProc *delProc)
+{
+ Jim_Cmd *cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
+
+
+ memset(cmdPtr, 0, sizeof(*cmdPtr));
+ cmdPtr->inUse = 1;
+ cmdPtr->u.native.delProc = delProc;
+ cmdPtr->u.native.cmdProc = cmdProc;
+ cmdPtr->u.native.privData = privData;
+
+ JimCreateCommand(interp, cmdNameStr, cmdPtr);
+
+ return JIM_OK;
+}
+
+static int JimCreateProcedureStatics(Jim_Interp *interp, Jim_Cmd *cmdPtr, Jim_Obj *staticsListObjPtr)
+{
+ int len, i;
+
+ len = Jim_ListLength(interp, staticsListObjPtr);
+ if (len == 0) {
+ return JIM_OK;
+ }
+
+ cmdPtr->u.proc.staticVars = Jim_Alloc(sizeof(Jim_HashTable));
+ Jim_InitHashTable(cmdPtr->u.proc.staticVars, &JimVariablesHashTableType, interp);
+ for (i = 0; i < len; i++) {
+ Jim_Obj *objPtr, *initObjPtr, *nameObjPtr;
+ Jim_Var *varPtr;
+ int subLen;
+
+ objPtr = Jim_ListGetIndex(interp, staticsListObjPtr, i);
+
+ subLen = Jim_ListLength(interp, objPtr);
+ if (subLen == 1 || subLen == 2) {
+ nameObjPtr = Jim_ListGetIndex(interp, objPtr, 0);
+ if (subLen == 1) {
+ initObjPtr = Jim_GetVariable(interp, nameObjPtr, JIM_NONE);
+ if (initObjPtr == NULL) {
+ Jim_SetResultFormatted(interp,
+ "variable for initialization of static \"%#s\" not found in the local context",
+ nameObjPtr);
+ return JIM_ERR;
+ }
+ }
+ else {
+ initObjPtr = Jim_ListGetIndex(interp, objPtr, 1);
+ }
+ if (JimValidName(interp, "static variable", nameObjPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ varPtr = Jim_Alloc(sizeof(*varPtr));
+ varPtr->objPtr = initObjPtr;
+ Jim_IncrRefCount(initObjPtr);
+ varPtr->linkFramePtr = NULL;
+ if (Jim_AddHashEntry(cmdPtr->u.proc.staticVars,
+ Jim_String(nameObjPtr), varPtr) != JIM_OK) {
+ Jim_SetResultFormatted(interp,
+ "static variable name \"%#s\" duplicated in statics list", nameObjPtr);
+ Jim_DecrRefCount(interp, initObjPtr);
+ Jim_Free(varPtr);
+ return JIM_ERR;
+ }
+ }
+ else {
+ Jim_SetResultFormatted(interp, "too many fields in static specifier \"%#s\"",
+ objPtr);
+ return JIM_ERR;
+ }
+ }
+ return JIM_OK;
+}
+
+static void JimUpdateProcNamespace(Jim_Interp *interp, Jim_Cmd *cmdPtr, const char *cmdname)
+{
+#ifdef jim_ext_namespace
+ if (cmdPtr->isproc) {
+
+ const char *pt = strrchr(cmdname, ':');
+ if (pt && pt != cmdname && pt[-1] == ':') {
+ Jim_DecrRefCount(interp, cmdPtr->u.proc.nsObj);
+ cmdPtr->u.proc.nsObj = Jim_NewStringObj(interp, cmdname, pt - cmdname - 1);
+ Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
+
+ if (Jim_FindHashEntry(&interp->commands, pt + 1)) {
+
+ Jim_InterpIncrProcEpoch(interp);
+ }
+ }
+ }
+#endif
+}
+
+static Jim_Cmd *JimCreateProcedureCmd(Jim_Interp *interp, Jim_Obj *argListObjPtr,
+ Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr, Jim_Obj *nsObj)
+{
+ Jim_Cmd *cmdPtr;
+ int argListLen;
+ int i;
+
+ argListLen = Jim_ListLength(interp, argListObjPtr);
+
+
+ cmdPtr = Jim_Alloc(sizeof(*cmdPtr) + sizeof(struct Jim_ProcArg) * argListLen);
+ memset(cmdPtr, 0, sizeof(*cmdPtr));
+ cmdPtr->inUse = 1;
+ cmdPtr->isproc = 1;
+ cmdPtr->u.proc.argListObjPtr = argListObjPtr;
+ cmdPtr->u.proc.argListLen = argListLen;
+ cmdPtr->u.proc.bodyObjPtr = bodyObjPtr;
+ cmdPtr->u.proc.argsPos = -1;
+ cmdPtr->u.proc.arglist = (struct Jim_ProcArg *)(cmdPtr + 1);
+ cmdPtr->u.proc.nsObj = nsObj ? nsObj : interp->emptyObj;
+ Jim_IncrRefCount(argListObjPtr);
+ Jim_IncrRefCount(bodyObjPtr);
+ Jim_IncrRefCount(cmdPtr->u.proc.nsObj);
+
+
+ if (staticsListObjPtr && JimCreateProcedureStatics(interp, cmdPtr, staticsListObjPtr) != JIM_OK) {
+ goto err;
+ }
+
+
+
+ for (i = 0; i < argListLen; i++) {
+ Jim_Obj *argPtr;
+ Jim_Obj *nameObjPtr;
+ Jim_Obj *defaultObjPtr;
+ int len;
+
+
+ argPtr = Jim_ListGetIndex(interp, argListObjPtr, i);
+ len = Jim_ListLength(interp, argPtr);
+ if (len == 0) {
+ Jim_SetResultString(interp, "argument with no name", -1);
+err:
+ JimDecrCmdRefCount(interp, cmdPtr);
+ return NULL;
+ }
+ if (len > 2) {
+ Jim_SetResultFormatted(interp, "too many fields in argument specifier \"%#s\"", argPtr);
+ goto err;
+ }
+
+ if (len == 2) {
+
+ nameObjPtr = Jim_ListGetIndex(interp, argPtr, 0);
+ defaultObjPtr = Jim_ListGetIndex(interp, argPtr, 1);
+ }
+ else {
+
+ nameObjPtr = argPtr;
+ defaultObjPtr = NULL;
+ }
+
+
+ if (Jim_CompareStringImmediate(interp, nameObjPtr, "args")) {
+ if (cmdPtr->u.proc.argsPos >= 0) {
+ Jim_SetResultString(interp, "'args' specified more than once", -1);
+ goto err;
+ }
+ cmdPtr->u.proc.argsPos = i;
+ }
+ else {
+ if (len == 2) {
+ cmdPtr->u.proc.optArity++;
+ }
+ else {
+ cmdPtr->u.proc.reqArity++;
+ }
+ }
+
+ cmdPtr->u.proc.arglist[i].nameObjPtr = nameObjPtr;
+ cmdPtr->u.proc.arglist[i].defaultObjPtr = defaultObjPtr;
+ }
+
+ return cmdPtr;
+}
+
+int Jim_DeleteCommand(Jim_Interp *interp, const char *name)
+{
+ int ret = JIM_OK;
+ Jim_Obj *qualifiedNameObj;
+ const char *qualname = JimQualifyName(interp, name, &qualifiedNameObj);
+
+ if (Jim_DeleteHashEntry(&interp->commands, qualname) == JIM_ERR) {
+ Jim_SetResultFormatted(interp, "can't delete \"%s\": command doesn't exist", name);
+ ret = JIM_ERR;
+ }
+ else {
+ Jim_InterpIncrProcEpoch(interp);
+ }
+
+ JimFreeQualifiedName(interp, qualifiedNameObj);
+
+ return ret;
+}
+
+int Jim_RenameCommand(Jim_Interp *interp, const char *oldName, const char *newName)
+{
+ int ret = JIM_ERR;
+ Jim_HashEntry *he;
+ Jim_Cmd *cmdPtr;
+ Jim_Obj *qualifiedOldNameObj;
+ Jim_Obj *qualifiedNewNameObj;
+ const char *fqold;
+ const char *fqnew;
+
+ if (newName[0] == 0) {
+ return Jim_DeleteCommand(interp, oldName);
+ }
+
+ fqold = JimQualifyName(interp, oldName, &qualifiedOldNameObj);
+ fqnew = JimQualifyName(interp, newName, &qualifiedNewNameObj);
+
+
+ he = Jim_FindHashEntry(&interp->commands, fqold);
+ if (he == NULL) {
+ Jim_SetResultFormatted(interp, "can't rename \"%s\": command doesn't exist", oldName);
+ }
+ else if (Jim_FindHashEntry(&interp->commands, fqnew)) {
+ Jim_SetResultFormatted(interp, "can't rename to \"%s\": command already exists", newName);
+ }
+ else {
+
+ cmdPtr = Jim_GetHashEntryVal(he);
+ JimIncrCmdRefCount(cmdPtr);
+ JimUpdateProcNamespace(interp, cmdPtr, fqnew);
+ Jim_AddHashEntry(&interp->commands, fqnew, cmdPtr);
+
+
+ Jim_DeleteHashEntry(&interp->commands, fqold);
+
+
+ Jim_InterpIncrProcEpoch(interp);
+
+ ret = JIM_OK;
+ }
+
+ JimFreeQualifiedName(interp, qualifiedOldNameObj);
+ JimFreeQualifiedName(interp, qualifiedNewNameObj);
+
+ return ret;
+}
+
+
+static void FreeCommandInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ Jim_DecrRefCount(interp, objPtr->internalRep.cmdValue.nsObj);
+}
+
+static void DupCommandInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ dupPtr->internalRep.cmdValue = srcPtr->internalRep.cmdValue;
+ dupPtr->typePtr = srcPtr->typePtr;
+ Jim_IncrRefCount(dupPtr->internalRep.cmdValue.nsObj);
+}
+
+static const Jim_ObjType commandObjType = {
+ "command",
+ FreeCommandInternalRep,
+ DupCommandInternalRep,
+ NULL,
+ JIM_TYPE_REFERENCES,
+};
+
+Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+ Jim_Cmd *cmd;
+
+ if (objPtr->typePtr != &commandObjType ||
+ objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch
+#ifdef jim_ext_namespace
+ || !Jim_StringEqObj(objPtr->internalRep.cmdValue.nsObj, interp->framePtr->nsObj)
+#endif
+ ) {
+
+
+
+ const char *name = Jim_String(objPtr);
+ Jim_HashEntry *he;
+
+ if (name[0] == ':' && name[1] == ':') {
+ while (*++name == ':') {
+ }
+ }
+#ifdef jim_ext_namespace
+ else if (Jim_Length(interp->framePtr->nsObj)) {
+
+ Jim_Obj *nameObj = Jim_DuplicateObj(interp, interp->framePtr->nsObj);
+ Jim_AppendStrings(interp, nameObj, "::", name, NULL);
+ he = Jim_FindHashEntry(&interp->commands, Jim_String(nameObj));
+ Jim_FreeNewObj(interp, nameObj);
+ if (he) {
+ goto found;
+ }
+ }
+#endif
+
+
+ he = Jim_FindHashEntry(&interp->commands, name);
+ if (he == NULL) {
+ if (flags & JIM_ERRMSG) {
+ Jim_SetResultFormatted(interp, "invalid command name \"%#s\"", objPtr);
+ }
+ return NULL;
+ }
+#ifdef jim_ext_namespace
+found:
+#endif
+ cmd = Jim_GetHashEntryVal(he);
+
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &commandObjType;
+ objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
+ objPtr->internalRep.cmdValue.cmdPtr = cmd;
+ objPtr->internalRep.cmdValue.nsObj = interp->framePtr->nsObj;
+ Jim_IncrRefCount(interp->framePtr->nsObj);
+ }
+ else {
+ cmd = objPtr->internalRep.cmdValue.cmdPtr;
+ }
+ while (cmd->u.proc.upcall) {
+ cmd = cmd->prevCmd;
+ }
+ return cmd;
+}
+
+
+
+#define JIM_DICT_SUGAR 100
+
+static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static const Jim_ObjType variableObjType = {
+ "variable",
+ NULL,
+ NULL,
+ NULL,
+ JIM_TYPE_REFERENCES,
+};
+
+static int JimValidName(Jim_Interp *interp, const char *type, Jim_Obj *nameObjPtr)
+{
+
+ if (nameObjPtr->typePtr != &variableObjType) {
+ int len;
+ const char *str = Jim_GetString(nameObjPtr, &len);
+ if (memchr(str, '\0', len)) {
+ Jim_SetResultFormatted(interp, "%s name contains embedded null", type);
+ return JIM_ERR;
+ }
+ }
+ return JIM_OK;
+}
+
+static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+ const char *varName;
+ Jim_CallFrame *framePtr;
+ Jim_HashEntry *he;
+ int global;
+ int len;
+
+
+ if (objPtr->typePtr == &variableObjType) {
+ framePtr = objPtr->internalRep.varValue.global ? interp->topFramePtr : interp->framePtr;
+ if (objPtr->internalRep.varValue.callFrameId == framePtr->id) {
+
+ return JIM_OK;
+ }
+
+ }
+ else if (objPtr->typePtr == &dictSubstObjType) {
+ return JIM_DICT_SUGAR;
+ }
+ else if (JimValidName(interp, "variable", objPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+
+ varName = Jim_GetString(objPtr, &len);
+
+
+ if (len && varName[len - 1] == ')' && strchr(varName, '(') != NULL) {
+ return JIM_DICT_SUGAR;
+ }
+
+ if (varName[0] == ':' && varName[1] == ':') {
+ while (*++varName == ':') {
+ }
+ global = 1;
+ framePtr = interp->topFramePtr;
+ }
+ else {
+ global = 0;
+ framePtr = interp->framePtr;
+ }
+
+
+ he = Jim_FindHashEntry(&framePtr->vars, varName);
+ if (he == NULL) {
+ if (!global && framePtr->staticVars) {
+
+ he = Jim_FindHashEntry(framePtr->staticVars, varName);
+ }
+ if (he == NULL) {
+ return JIM_ERR;
+ }
+ }
+
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &variableObjType;
+ objPtr->internalRep.varValue.callFrameId = framePtr->id;
+ objPtr->internalRep.varValue.varPtr = Jim_GetHashEntryVal(he);
+ objPtr->internalRep.varValue.global = global;
+ return JIM_OK;
+}
+
+
+static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr, Jim_Obj *valObjPtr);
+static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr, int flags);
+
+static Jim_Var *JimCreateVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
+{
+ const char *name;
+ Jim_CallFrame *framePtr;
+ int global;
+
+
+ Jim_Var *var = Jim_Alloc(sizeof(*var));
+
+ var->objPtr = valObjPtr;
+ Jim_IncrRefCount(valObjPtr);
+ var->linkFramePtr = NULL;
+
+ name = Jim_String(nameObjPtr);
+ if (name[0] == ':' && name[1] == ':') {
+ while (*++name == ':') {
+ }
+ framePtr = interp->topFramePtr;
+ global = 1;
+ }
+ else {
+ framePtr = interp->framePtr;
+ global = 0;
+ }
+
+
+ Jim_AddHashEntry(&framePtr->vars, name, var);
+
+
+ Jim_FreeIntRep(interp, nameObjPtr);
+ nameObjPtr->typePtr = &variableObjType;
+ nameObjPtr->internalRep.varValue.callFrameId = framePtr->id;
+ nameObjPtr->internalRep.varValue.varPtr = var;
+ nameObjPtr->internalRep.varValue.global = global;
+
+ return var;
+}
+
+
+int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
+{
+ int err;
+ Jim_Var *var;
+
+ switch (SetVariableFromAny(interp, nameObjPtr)) {
+ case JIM_DICT_SUGAR:
+ return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
+
+ case JIM_ERR:
+ if (JimValidName(interp, "variable", nameObjPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+ JimCreateVariable(interp, nameObjPtr, valObjPtr);
+ break;
+
+ case JIM_OK:
+ var = nameObjPtr->internalRep.varValue.varPtr;
+ if (var->linkFramePtr == NULL) {
+ Jim_IncrRefCount(valObjPtr);
+ Jim_DecrRefCount(interp, var->objPtr);
+ var->objPtr = valObjPtr;
+ }
+ else {
+ Jim_CallFrame *savedCallFrame;
+
+ savedCallFrame = interp->framePtr;
+ interp->framePtr = var->linkFramePtr;
+ err = Jim_SetVariable(interp, var->objPtr, valObjPtr);
+ interp->framePtr = savedCallFrame;
+ if (err != JIM_OK)
+ return err;
+ }
+ }
+ return JIM_OK;
+}
+
+int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
+{
+ Jim_Obj *nameObjPtr;
+ int result;
+
+ nameObjPtr = Jim_NewStringObj(interp, name, -1);
+ Jim_IncrRefCount(nameObjPtr);
+ result = Jim_SetVariable(interp, nameObjPtr, objPtr);
+ Jim_DecrRefCount(interp, nameObjPtr);
+ return result;
+}
+
+int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
+{
+ Jim_CallFrame *savedFramePtr;
+ int result;
+
+ savedFramePtr = interp->framePtr;
+ interp->framePtr = interp->topFramePtr;
+ result = Jim_SetVariableStr(interp, name, objPtr);
+ interp->framePtr = savedFramePtr;
+ return result;
+}
+
+int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
+{
+ Jim_Obj *valObjPtr;
+ int result;
+
+ valObjPtr = Jim_NewStringObj(interp, val, -1);
+ Jim_IncrRefCount(valObjPtr);
+ result = Jim_SetVariableStr(interp, name, valObjPtr);
+ Jim_DecrRefCount(interp, valObjPtr);
+ return result;
+}
+
+int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
+ Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
+{
+ const char *varName;
+ const char *targetName;
+ Jim_CallFrame *framePtr;
+ Jim_Var *varPtr;
+
+
+ switch (SetVariableFromAny(interp, nameObjPtr)) {
+ case JIM_DICT_SUGAR:
+
+ Jim_SetResultFormatted(interp, "bad variable name \"%#s\": upvar won't create a scalar variable that looks like an array element", nameObjPtr);
+ return JIM_ERR;
+
+ case JIM_OK:
+ varPtr = nameObjPtr->internalRep.varValue.varPtr;
+
+ if (varPtr->linkFramePtr == NULL) {
+ Jim_SetResultFormatted(interp, "variable \"%#s\" already exists", nameObjPtr);
+ return JIM_ERR;
+ }
+
+
+ varPtr->linkFramePtr = NULL;
+ break;
+ }
+
+
+
+ varName = Jim_String(nameObjPtr);
+
+ if (varName[0] == ':' && varName[1] == ':') {
+ while (*++varName == ':') {
+ }
+
+ framePtr = interp->topFramePtr;
+ }
+ else {
+ framePtr = interp->framePtr;
+ }
+
+ targetName = Jim_String(targetNameObjPtr);
+ if (targetName[0] == ':' && targetName[1] == ':') {
+ while (*++targetName == ':') {
+ }
+ targetNameObjPtr = Jim_NewStringObj(interp, targetName, -1);
+ targetCallFrame = interp->topFramePtr;
+ }
+ Jim_IncrRefCount(targetNameObjPtr);
+
+ if (framePtr->level < targetCallFrame->level) {
+ Jim_SetResultFormatted(interp,
+ "bad variable name \"%#s\": upvar won't create namespace variable that refers to procedure variable",
+ nameObjPtr);
+ Jim_DecrRefCount(interp, targetNameObjPtr);
+ return JIM_ERR;
+ }
+
+
+ if (framePtr == targetCallFrame) {
+ Jim_Obj *objPtr = targetNameObjPtr;
+
+
+ while (1) {
+ if (strcmp(Jim_String(objPtr), varName) == 0) {
+ Jim_SetResultString(interp, "can't upvar from variable to itself", -1);
+ Jim_DecrRefCount(interp, targetNameObjPtr);
+ return JIM_ERR;
+ }
+ if (SetVariableFromAny(interp, objPtr) != JIM_OK)
+ break;
+ varPtr = objPtr->internalRep.varValue.varPtr;
+ if (varPtr->linkFramePtr != targetCallFrame)
+ break;
+ objPtr = varPtr->objPtr;
+ }
+ }
+
+
+ Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
+
+ nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;
+ Jim_DecrRefCount(interp, targetNameObjPtr);
+ return JIM_OK;
+}
+
+Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+{
+ switch (SetVariableFromAny(interp, nameObjPtr)) {
+ case JIM_OK:{
+ Jim_Var *varPtr = nameObjPtr->internalRep.varValue.varPtr;
+
+ if (varPtr->linkFramePtr == NULL) {
+ return varPtr->objPtr;
+ }
+ else {
+ Jim_Obj *objPtr;
+
+
+ Jim_CallFrame *savedCallFrame = interp->framePtr;
+
+ interp->framePtr = varPtr->linkFramePtr;
+ objPtr = Jim_GetVariable(interp, varPtr->objPtr, flags);
+ interp->framePtr = savedCallFrame;
+ if (objPtr) {
+ return objPtr;
+ }
+
+ }
+ }
+ break;
+
+ case JIM_DICT_SUGAR:
+
+ return JimDictSugarGet(interp, nameObjPtr, flags);
+ }
+ if (flags & JIM_ERRMSG) {
+ Jim_SetResultFormatted(interp, "can't read \"%#s\": no such variable", nameObjPtr);
+ }
+ return NULL;
+}
+
+Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+{
+ Jim_CallFrame *savedFramePtr;
+ Jim_Obj *objPtr;
+
+ savedFramePtr = interp->framePtr;
+ interp->framePtr = interp->topFramePtr;
+ objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
+ interp->framePtr = savedFramePtr;
+
+ return objPtr;
+}
+
+Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
+{
+ Jim_Obj *nameObjPtr, *varObjPtr;
+
+ nameObjPtr = Jim_NewStringObj(interp, name, -1);
+ Jim_IncrRefCount(nameObjPtr);
+ varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
+ Jim_DecrRefCount(interp, nameObjPtr);
+ return varObjPtr;
+}
+
+Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name, int flags)
+{
+ Jim_CallFrame *savedFramePtr;
+ Jim_Obj *objPtr;
+
+ savedFramePtr = interp->framePtr;
+ interp->framePtr = interp->topFramePtr;
+ objPtr = Jim_GetVariableStr(interp, name, flags);
+ interp->framePtr = savedFramePtr;
+
+ return objPtr;
+}
+
+int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+{
+ Jim_Var *varPtr;
+ int retval;
+ Jim_CallFrame *framePtr;
+
+ retval = SetVariableFromAny(interp, nameObjPtr);
+ if (retval == JIM_DICT_SUGAR) {
+
+ return JimDictSugarSet(interp, nameObjPtr, NULL);
+ }
+ else if (retval == JIM_OK) {
+ varPtr = nameObjPtr->internalRep.varValue.varPtr;
+
+
+ if (varPtr->linkFramePtr) {
+ framePtr = interp->framePtr;
+ interp->framePtr = varPtr->linkFramePtr;
+ retval = Jim_UnsetVariable(interp, varPtr->objPtr, JIM_NONE);
+ interp->framePtr = framePtr;
+ }
+ else {
+ const char *name = Jim_String(nameObjPtr);
+ if (nameObjPtr->internalRep.varValue.global) {
+ name += 2;
+ framePtr = interp->topFramePtr;
+ }
+ else {
+ framePtr = interp->framePtr;
+ }
+
+ retval = Jim_DeleteHashEntry(&framePtr->vars, name);
+ if (retval == JIM_OK) {
+
+ framePtr->id = interp->callFrameEpoch++;
+ }
+ }
+ }
+ if (retval != JIM_OK && (flags & JIM_ERRMSG)) {
+ Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such variable", nameObjPtr);
+ }
+ return retval;
+}
+
+
+
+static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
+ Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
+{
+ const char *str, *p;
+ int len, keyLen;
+ Jim_Obj *varObjPtr, *keyObjPtr;
+
+ str = Jim_GetString(objPtr, &len);
+
+ p = strchr(str, '(');
+ JimPanic((p == NULL, "JimDictSugarParseVarKey() called for non-dict-sugar (%s)", str));
+
+ varObjPtr = Jim_NewStringObj(interp, str, p - str);
+
+ p++;
+ keyLen = (str + len) - p;
+ if (str[len - 1] == ')') {
+ keyLen--;
+ }
+
+
+ keyObjPtr = Jim_NewStringObj(interp, p, keyLen);
+
+ Jim_IncrRefCount(varObjPtr);
+ Jim_IncrRefCount(keyObjPtr);
+ *varPtrPtr = varObjPtr;
+ *keyPtrPtr = keyObjPtr;
+}
+
+static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *valObjPtr)
+{
+ int err;
+
+ SetDictSubstFromAny(interp, objPtr);
+
+ err = Jim_SetDictKeysVector(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
+ &objPtr->internalRep.dictSubstValue.indexObjPtr, 1, valObjPtr, JIM_MUSTEXIST);
+
+ if (err == JIM_OK) {
+
+ Jim_SetEmptyResult(interp);
+ }
+ else {
+ if (!valObjPtr) {
+
+ if (Jim_GetVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_NONE)) {
+ Jim_SetResultFormatted(interp, "can't unset \"%#s\": no such element in array",
+ objPtr);
+ return err;
+ }
+ }
+
+ Jim_SetResultFormatted(interp, "can't %s \"%#s\": variable isn't array",
+ (valObjPtr ? "set" : "unset"), objPtr);
+ }
+ return err;
+}
+
+static Jim_Obj *JimDictExpandArrayVariable(Jim_Interp *interp, Jim_Obj *varObjPtr,
+ Jim_Obj *keyObjPtr, int flags)
+{
+ Jim_Obj *dictObjPtr;
+ Jim_Obj *resObjPtr = NULL;
+ int ret;
+
+ dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
+ if (!dictObjPtr) {
+ return NULL;
+ }
+
+ ret = Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_NONE);
+ if (ret != JIM_OK) {
+ Jim_SetResultFormatted(interp,
+ "can't read \"%#s(%#s)\": %s array", varObjPtr, keyObjPtr,
+ ret < 0 ? "variable isn't" : "no such element in");
+ }
+ else if ((flags & JIM_UNSHARED) && Jim_IsShared(dictObjPtr)) {
+
+ Jim_SetVariable(interp, varObjPtr, Jim_DuplicateObj(interp, dictObjPtr));
+ }
+
+ return resObjPtr;
+}
+
+
+static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+ SetDictSubstFromAny(interp, objPtr);
+
+ return JimDictExpandArrayVariable(interp,
+ objPtr->internalRep.dictSubstValue.varNameObjPtr,
+ objPtr->internalRep.dictSubstValue.indexObjPtr, flags);
+}
+
+
+
+void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
+ Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
+}
+
+static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+
+ dupPtr->internalRep = srcPtr->internalRep;
+
+ Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.varNameObjPtr);
+ Jim_IncrRefCount(dupPtr->internalRep.dictSubstValue.indexObjPtr);
+}
+
+
+static void SetDictSubstFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ if (objPtr->typePtr != &dictSubstObjType) {
+ Jim_Obj *varObjPtr, *keyObjPtr;
+
+ if (objPtr->typePtr == &interpolatedObjType) {
+
+
+ varObjPtr = objPtr->internalRep.dictSubstValue.varNameObjPtr;
+ keyObjPtr = objPtr->internalRep.dictSubstValue.indexObjPtr;
+
+ Jim_IncrRefCount(varObjPtr);
+ Jim_IncrRefCount(keyObjPtr);
+ }
+ else {
+ JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
+ }
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &dictSubstObjType;
+ objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
+ objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
+ }
+}
+
+static Jim_Obj *JimExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ Jim_Obj *resObjPtr = NULL;
+ Jim_Obj *substKeyObjPtr = NULL;
+
+ SetDictSubstFromAny(interp, objPtr);
+
+ if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
+ &substKeyObjPtr, JIM_NONE)
+ != JIM_OK) {
+ return NULL;
+ }
+ Jim_IncrRefCount(substKeyObjPtr);
+ resObjPtr =
+ JimDictExpandArrayVariable(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr,
+ substKeyObjPtr, 0);
+ Jim_DecrRefCount(interp, substKeyObjPtr);
+
+ return resObjPtr;
+}
+
+static Jim_Obj *JimExpandExprSugar(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ if (Jim_EvalExpression(interp, objPtr) == JIM_OK) {
+ return Jim_GetResult(interp);
+ }
+ return NULL;
+}
+
+
+static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp, Jim_CallFrame *parent, Jim_Obj *nsObj)
+{
+ Jim_CallFrame *cf;
+
+ if (interp->freeFramesList) {
+ cf = interp->freeFramesList;
+ interp->freeFramesList = cf->next;
+
+ cf->argv = NULL;
+ cf->argc = 0;
+ cf->procArgsObjPtr = NULL;
+ cf->procBodyObjPtr = NULL;
+ cf->next = NULL;
+ cf->staticVars = NULL;
+ cf->localCommands = NULL;
+ cf->tailcallObj = NULL;
+ cf->tailcallCmd = NULL;
+ }
+ else {
+ cf = Jim_Alloc(sizeof(*cf));
+ memset(cf, 0, sizeof(*cf));
+
+ Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
+ }
+
+ cf->id = interp->callFrameEpoch++;
+ cf->parent = parent;
+ cf->level = parent ? parent->level + 1 : 0;
+ cf->nsObj = nsObj;
+ Jim_IncrRefCount(nsObj);
+
+ return cf;
+}
+
+static int JimDeleteLocalProcs(Jim_Interp *interp, Jim_Stack *localCommands)
+{
+
+ if (localCommands) {
+ Jim_Obj *cmdNameObj;
+
+ while ((cmdNameObj = Jim_StackPop(localCommands)) != NULL) {
+ Jim_HashEntry *he;
+ Jim_Obj *fqObjName;
+ Jim_HashTable *ht = &interp->commands;
+
+ const char *fqname = JimQualifyName(interp, Jim_String(cmdNameObj), &fqObjName);
+
+ he = Jim_FindHashEntry(ht, fqname);
+
+ if (he) {
+ Jim_Cmd *cmd = Jim_GetHashEntryVal(he);
+ if (cmd->prevCmd) {
+ Jim_Cmd *prevCmd = cmd->prevCmd;
+ cmd->prevCmd = NULL;
+
+
+ JimDecrCmdRefCount(interp, cmd);
+
+
+ Jim_SetHashVal(ht, he, prevCmd);
+ }
+ else {
+ Jim_DeleteHashEntry(ht, fqname);
+ }
+ Jim_InterpIncrProcEpoch(interp);
+ }
+ Jim_DecrRefCount(interp, cmdNameObj);
+ JimFreeQualifiedName(interp, fqObjName);
+ }
+ Jim_FreeStack(localCommands);
+ Jim_Free(localCommands);
+ }
+ return JIM_OK;
+}
+
+static int JimInvokeDefer(Jim_Interp *interp, int retcode)
+{
+ Jim_Obj *objPtr;
+
+
+ if (Jim_FindHashEntry(&interp->framePtr->vars, "jim::defer") == NULL) {
+ return retcode;
+ }
+
+ objPtr = Jim_GetVariableStr(interp, "jim::defer", JIM_NONE);
+
+ if (objPtr) {
+ int ret = JIM_OK;
+ int i;
+ int listLen = Jim_ListLength(interp, objPtr);
+ Jim_Obj *resultObjPtr;
+
+ Jim_IncrRefCount(objPtr);
+
+ resultObjPtr = Jim_GetResult(interp);
+ Jim_IncrRefCount(resultObjPtr);
+ Jim_SetEmptyResult(interp);
+
+
+ for (i = listLen; i > 0; i--) {
+
+ Jim_Obj *scriptObjPtr = Jim_ListGetIndex(interp, objPtr, i - 1);
+ ret = Jim_EvalObj(interp, scriptObjPtr);
+ if (ret != JIM_OK) {
+ break;
+ }
+ }
+
+ if (ret == JIM_OK || retcode == JIM_ERR) {
+
+ Jim_SetResult(interp, resultObjPtr);
+ }
+ else {
+ retcode = ret;
+ }
+
+ Jim_DecrRefCount(interp, resultObjPtr);
+ Jim_DecrRefCount(interp, objPtr);
+ }
+ return retcode;
+}
+
+#define JIM_FCF_FULL 0
+#define JIM_FCF_REUSE 1
+static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int action)
+ {
+ JimDeleteLocalProcs(interp, cf->localCommands);
+
+ if (cf->procArgsObjPtr)
+ Jim_DecrRefCount(interp, cf->procArgsObjPtr);
+ if (cf->procBodyObjPtr)
+ Jim_DecrRefCount(interp, cf->procBodyObjPtr);
+ Jim_DecrRefCount(interp, cf->nsObj);
+ if (action == JIM_FCF_FULL || cf->vars.size != JIM_HT_INITIAL_SIZE)
+ Jim_FreeHashTable(&cf->vars);
+ else {
+ int i;
+ Jim_HashEntry **table = cf->vars.table, *he;
+
+ for (i = 0; i < JIM_HT_INITIAL_SIZE; i++) {
+ he = table[i];
+ while (he != NULL) {
+ Jim_HashEntry *nextEntry = he->next;
+ Jim_Var *varPtr = Jim_GetHashEntryVal(he);
+
+ Jim_DecrRefCount(interp, varPtr->objPtr);
+ Jim_Free(Jim_GetHashEntryKey(he));
+ Jim_Free(varPtr);
+ Jim_Free(he);
+ table[i] = NULL;
+ he = nextEntry;
+ }
+ }
+ cf->vars.used = 0;
+ }
+ cf->next = interp->freeFramesList;
+ interp->freeFramesList = cf;
+}
+
+
+
+int Jim_IsBigEndian(void)
+{
+ union {
+ unsigned short s;
+ unsigned char c[2];
+ } uval = {0x0102};
+
+ return uval.c[0] == 1;
+}
+
+
+Jim_Interp *Jim_CreateInterp(void)
+{
+ Jim_Interp *i = Jim_Alloc(sizeof(*i));
+
+ memset(i, 0, sizeof(*i));
+
+ i->maxCallFrameDepth = JIM_MAX_CALLFRAME_DEPTH;
+ i->maxEvalDepth = JIM_MAX_EVAL_DEPTH;
+ i->lastCollectTime = time(NULL);
+
+ Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
+#ifdef JIM_REFERENCES
+ Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
+#endif
+ Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
+ Jim_InitHashTable(&i->packages, &JimPackageHashTableType, NULL);
+ i->emptyObj = Jim_NewEmptyStringObj(i);
+ i->trueObj = Jim_NewIntObj(i, 1);
+ i->falseObj = Jim_NewIntObj(i, 0);
+ i->framePtr = i->topFramePtr = JimCreateCallFrame(i, NULL, i->emptyObj);
+ i->errorFileNameObj = i->emptyObj;
+ i->result = i->emptyObj;
+ i->stackTrace = Jim_NewListObj(i, NULL, 0);
+ i->unknown = Jim_NewStringObj(i, "unknown", -1);
+ i->errorProc = i->emptyObj;
+ i->currentScriptObj = Jim_NewEmptyStringObj(i);
+ i->nullScriptObj = Jim_NewEmptyStringObj(i);
+ Jim_IncrRefCount(i->emptyObj);
+ Jim_IncrRefCount(i->errorFileNameObj);
+ Jim_IncrRefCount(i->result);
+ Jim_IncrRefCount(i->stackTrace);
+ Jim_IncrRefCount(i->unknown);
+ Jim_IncrRefCount(i->currentScriptObj);
+ Jim_IncrRefCount(i->nullScriptObj);
+ Jim_IncrRefCount(i->errorProc);
+ Jim_IncrRefCount(i->trueObj);
+ Jim_IncrRefCount(i->falseObj);
+
+
+ Jim_SetVariableStrWithStr(i, JIM_LIBPATH, TCL_LIBRARY);
+ Jim_SetVariableStrWithStr(i, JIM_INTERACTIVE, "0");
+
+ Jim_SetVariableStrWithStr(i, "tcl_platform(engine)", "Jim");
+ Jim_SetVariableStrWithStr(i, "tcl_platform(os)", TCL_PLATFORM_OS);
+ Jim_SetVariableStrWithStr(i, "tcl_platform(platform)", TCL_PLATFORM_PLATFORM);
+ Jim_SetVariableStrWithStr(i, "tcl_platform(pathSeparator)", TCL_PLATFORM_PATH_SEPARATOR);
+ Jim_SetVariableStrWithStr(i, "tcl_platform(byteOrder)", Jim_IsBigEndian() ? "bigEndian" : "littleEndian");
+ Jim_SetVariableStrWithStr(i, "tcl_platform(threaded)", "0");
+ Jim_SetVariableStr(i, "tcl_platform(pointerSize)", Jim_NewIntObj(i, sizeof(void *)));
+ Jim_SetVariableStr(i, "tcl_platform(wordSize)", Jim_NewIntObj(i, sizeof(jim_wide)));
+
+ return i;
+}
+
+void Jim_FreeInterp(Jim_Interp *i)
+{
+ Jim_CallFrame *cf, *cfx;
+
+ Jim_Obj *objPtr, *nextObjPtr;
+
+
+ for (cf = i->framePtr; cf; cf = cfx) {
+
+ JimInvokeDefer(i, JIM_OK);
+ cfx = cf->parent;
+ JimFreeCallFrame(i, cf, JIM_FCF_FULL);
+ }
+
+ Jim_DecrRefCount(i, i->emptyObj);
+ Jim_DecrRefCount(i, i->trueObj);
+ Jim_DecrRefCount(i, i->falseObj);
+ Jim_DecrRefCount(i, i->result);
+ Jim_DecrRefCount(i, i->stackTrace);
+ Jim_DecrRefCount(i, i->errorProc);
+ Jim_DecrRefCount(i, i->unknown);
+ Jim_DecrRefCount(i, i->errorFileNameObj);
+ Jim_DecrRefCount(i, i->currentScriptObj);
+ Jim_DecrRefCount(i, i->nullScriptObj);
+ Jim_FreeHashTable(&i->commands);
+#ifdef JIM_REFERENCES
+ Jim_FreeHashTable(&i->references);
+#endif
+ Jim_FreeHashTable(&i->packages);
+ Jim_Free(i->prngState);
+ Jim_FreeHashTable(&i->assocData);
+
+#ifdef JIM_MAINTAINER
+ if (i->liveList != NULL) {
+ objPtr = i->liveList;
+
+ printf("\n-------------------------------------\n");
+ printf("Objects still in the free list:\n");
+ while (objPtr) {
+ const char *type = objPtr->typePtr ? objPtr->typePtr->name : "string";
+ Jim_String(objPtr);
+
+ if (objPtr->bytes && strlen(objPtr->bytes) > 20) {
+ printf("%p (%d) %-10s: '%.20s...'\n",
+ (void *)objPtr, objPtr->refCount, type, objPtr->bytes);
+ }
+ else {
+ printf("%p (%d) %-10s: '%s'\n",
+ (void *)objPtr, objPtr->refCount, type, objPtr->bytes ? objPtr->bytes : "(null)");
+ }
+ if (objPtr->typePtr == &sourceObjType) {
+ printf("FILE %s LINE %d\n",
+ Jim_String(objPtr->internalRep.sourceValue.fileNameObj),
+ objPtr->internalRep.sourceValue.lineNumber);
+ }
+ objPtr = objPtr->nextObjPtr;
+ }
+ printf("-------------------------------------\n\n");
+ JimPanic((1, "Live list non empty freeing the interpreter! Leak?"));
+ }
+#endif
+
+
+ objPtr = i->freeList;
+ while (objPtr) {
+ nextObjPtr = objPtr->nextObjPtr;
+ Jim_Free(objPtr);
+ objPtr = nextObjPtr;
+ }
+
+
+ for (cf = i->freeFramesList; cf; cf = cfx) {
+ cfx = cf->next;
+ if (cf->vars.table)
+ Jim_FreeHashTable(&cf->vars);
+ Jim_Free(cf);
+ }
+
+
+ Jim_Free(i);
+}
+
+Jim_CallFrame *Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr)
+{
+ long level;
+ const char *str;
+ Jim_CallFrame *framePtr;
+
+ if (levelObjPtr) {
+ str = Jim_String(levelObjPtr);
+ if (str[0] == '#') {
+ char *endptr;
+
+ level = jim_strtol(str + 1, &endptr);
+ if (str[1] == '\0' || endptr[0] != '\0') {
+ level = -1;
+ }
+ }
+ else {
+ if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0) {
+ level = -1;
+ }
+ else {
+
+ level = interp->framePtr->level - level;
+ }
+ }
+ }
+ else {
+ str = "1";
+ level = interp->framePtr->level - 1;
+ }
+
+ if (level == 0) {
+ return interp->topFramePtr;
+ }
+ if (level > 0) {
+
+ for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
+ if (framePtr->level == level) {
+ return framePtr;
+ }
+ }
+ }
+
+ Jim_SetResultFormatted(interp, "bad level \"%s\"", str);
+ return NULL;
+}
+
+static Jim_CallFrame *JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr)
+{
+ long level;
+ Jim_CallFrame *framePtr;
+
+ if (Jim_GetLong(interp, levelObjPtr, &level) == JIM_OK) {
+ if (level <= 0) {
+
+ level = interp->framePtr->level + level;
+ }
+
+ if (level == 0) {
+ return interp->topFramePtr;
+ }
+
+
+ for (framePtr = interp->framePtr; framePtr; framePtr = framePtr->parent) {
+ if (framePtr->level == level) {
+ return framePtr;
+ }
+ }
+ }
+
+ Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
+ return NULL;
+}
+
+static void JimResetStackTrace(Jim_Interp *interp)
+{
+ Jim_DecrRefCount(interp, interp->stackTrace);
+ interp->stackTrace = Jim_NewListObj(interp, NULL, 0);
+ Jim_IncrRefCount(interp->stackTrace);
+}
+
+static void JimSetStackTrace(Jim_Interp *interp, Jim_Obj *stackTraceObj)
+{
+ int len;
+
+
+ Jim_IncrRefCount(stackTraceObj);
+ Jim_DecrRefCount(interp, interp->stackTrace);
+ interp->stackTrace = stackTraceObj;
+ interp->errorFlag = 1;
+
+ len = Jim_ListLength(interp, interp->stackTrace);
+ if (len >= 3) {
+ if (Jim_Length(Jim_ListGetIndex(interp, interp->stackTrace, len - 2)) == 0) {
+ interp->addStackTrace = 1;
+ }
+ }
+}
+
+static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,
+ Jim_Obj *fileNameObj, int linenr)
+{
+ if (strcmp(procname, "unknown") == 0) {
+ procname = "";
+ }
+ if (!*procname && !Jim_Length(fileNameObj)) {
+
+ return;
+ }
+
+ if (Jim_IsShared(interp->stackTrace)) {
+ Jim_DecrRefCount(interp, interp->stackTrace);
+ interp->stackTrace = Jim_DuplicateObj(interp, interp->stackTrace);
+ Jim_IncrRefCount(interp->stackTrace);
+ }
+
+
+ if (!*procname && Jim_Length(fileNameObj)) {
+
+ int len = Jim_ListLength(interp, interp->stackTrace);
+
+ if (len >= 3) {
+ Jim_Obj *objPtr = Jim_ListGetIndex(interp, interp->stackTrace, len - 3);
+ if (Jim_Length(objPtr)) {
+
+ objPtr = Jim_ListGetIndex(interp, interp->stackTrace, len - 2);
+ if (Jim_Length(objPtr) == 0) {
+
+ ListSetIndex(interp, interp->stackTrace, len - 2, fileNameObj, 0);
+ ListSetIndex(interp, interp->stackTrace, len - 1, Jim_NewIntObj(interp, linenr), 0);
+ return;
+ }
+ }
+ }
+ }
+
+ Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewStringObj(interp, procname, -1));
+ Jim_ListAppendElement(interp, interp->stackTrace, fileNameObj);
+ Jim_ListAppendElement(interp, interp->stackTrace, Jim_NewIntObj(interp, linenr));
+}
+
+int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc * delProc,
+ void *data)
+{
+ AssocDataValue *assocEntryPtr = (AssocDataValue *) Jim_Alloc(sizeof(AssocDataValue));
+
+ assocEntryPtr->delProc = delProc;
+ assocEntryPtr->data = data;
+ return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
+}
+
+void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
+{
+ Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
+
+ if (entryPtr != NULL) {
+ AssocDataValue *assocEntryPtr = Jim_GetHashEntryVal(entryPtr);
+ return assocEntryPtr->data;
+ }
+ return NULL;
+}
+
+int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
+{
+ return Jim_DeleteHashEntry(&interp->assocData, key);
+}
+
+int Jim_GetExitCode(Jim_Interp *interp)
+{
+ return interp->exitCode;
+}
+
+static void UpdateStringOfInt(struct Jim_Obj *objPtr);
+static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
+
+static const Jim_ObjType intObjType = {
+ "int",
+ NULL,
+ NULL,
+ UpdateStringOfInt,
+ JIM_TYPE_NONE,
+};
+
+static const Jim_ObjType coercedDoubleObjType = {
+ "coerced-double",
+ NULL,
+ NULL,
+ UpdateStringOfInt,
+ JIM_TYPE_NONE,
+};
+
+
+static void UpdateStringOfInt(struct Jim_Obj *objPtr)
+{
+ char buf[JIM_INTEGER_SPACE + 1];
+ jim_wide wideValue = JimWideValue(objPtr);
+ int pos = 0;
+
+ if (wideValue == 0) {
+ buf[pos++] = '0';
+ }
+ else {
+ char tmp[JIM_INTEGER_SPACE];
+ int num = 0;
+ int i;
+
+ if (wideValue < 0) {
+ buf[pos++] = '-';
+ i = wideValue % 10;
+ tmp[num++] = (i > 0) ? (10 - i) : -i;
+ wideValue /= -10;
+ }
+
+ while (wideValue) {
+ tmp[num++] = wideValue % 10;
+ wideValue /= 10;
+ }
+
+ for (i = 0; i < num; i++) {
+ buf[pos++] = '0' + tmp[num - i - 1];
+ }
+ }
+ buf[pos] = 0;
+
+ JimSetStringBytes(objPtr, buf);
+}
+
+static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+ jim_wide wideValue;
+ const char *str;
+
+ if (objPtr->typePtr == &coercedDoubleObjType) {
+
+ objPtr->typePtr = &intObjType;
+ return JIM_OK;
+ }
+
+
+ str = Jim_String(objPtr);
+
+ if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
+ if (flags & JIM_ERRMSG) {
+ Jim_SetResultFormatted(interp, "expected integer but got \"%#s\"", objPtr);
+ }
+ return JIM_ERR;
+ }
+ if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) && errno == ERANGE) {
+ Jim_SetResultString(interp, "Integer value too big to be represented", -1);
+ return JIM_ERR;
+ }
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &intObjType;
+ objPtr->internalRep.wideValue = wideValue;
+ return JIM_OK;
+}
+
+#ifdef JIM_OPTIMIZATION
+static int JimIsWide(Jim_Obj *objPtr)
+{
+ return objPtr->typePtr == &intObjType;
+}
+#endif
+
+int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
+{
+ if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
+ return JIM_ERR;
+ *widePtr = JimWideValue(objPtr);
+ return JIM_OK;
+}
+
+
+static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide * widePtr)
+{
+ if (objPtr->typePtr != &intObjType && SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
+ return JIM_ERR;
+ *widePtr = JimWideValue(objPtr);
+ return JIM_OK;
+}
+
+int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
+{
+ jim_wide wideValue;
+ int retval;
+
+ retval = Jim_GetWide(interp, objPtr, &wideValue);
+ if (retval == JIM_OK) {
+ *longPtr = (long)wideValue;
+ return JIM_OK;
+ }
+ return JIM_ERR;
+}
+
+Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
+{
+ Jim_Obj *objPtr;
+
+ objPtr = Jim_NewObj(interp);
+ objPtr->typePtr = &intObjType;
+ objPtr->bytes = NULL;
+ objPtr->internalRep.wideValue = wideValue;
+ return objPtr;
+}
+
+#define JIM_DOUBLE_SPACE 30
+
+static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
+static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
+
+static const Jim_ObjType doubleObjType = {
+ "double",
+ NULL,
+ NULL,
+ UpdateStringOfDouble,
+ JIM_TYPE_NONE,
+};
+
+#ifndef HAVE_ISNAN
+#undef isnan
+#define isnan(X) ((X) != (X))
+#endif
+#ifndef HAVE_ISINF
+#undef isinf
+#define isinf(X) (1.0 / (X) == 0.0)
+#endif
+
+static void UpdateStringOfDouble(struct Jim_Obj *objPtr)
+{
+ double value = objPtr->internalRep.doubleValue;
+
+ if (isnan(value)) {
+ JimSetStringBytes(objPtr, "NaN");
+ return;
+ }
+ if (isinf(value)) {
+ if (value < 0) {
+ JimSetStringBytes(objPtr, "-Inf");
+ }
+ else {
+ JimSetStringBytes(objPtr, "Inf");
+ }
+ return;
+ }
+ {
+ char buf[JIM_DOUBLE_SPACE + 1];
+ int i;
+ int len = sprintf(buf, "%.12g", value);
+
+
+ for (i = 0; i < len; i++) {
+ if (buf[i] == '.' || buf[i] == 'e') {
+#if defined(JIM_SPRINTF_DOUBLE_NEEDS_FIX)
+ char *e = strchr(buf, 'e');
+ if (e && (e[1] == '-' || e[1] == '+') && e[2] == '0') {
+
+ e += 2;
+ memmove(e, e + 1, len - (e - buf));
+ }
+#endif
+ break;
+ }
+ }
+ if (buf[i] == '\0') {
+ buf[i++] = '.';
+ buf[i++] = '0';
+ buf[i] = '\0';
+ }
+ JimSetStringBytes(objPtr, buf);
+ }
+}
+
+static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ double doubleValue;
+ jim_wide wideValue;
+ const char *str;
+
+#ifdef HAVE_LONG_LONG
+
+#define MIN_INT_IN_DOUBLE -(1LL << 53)
+#define MAX_INT_IN_DOUBLE -(MIN_INT_IN_DOUBLE + 1)
+
+ if (objPtr->typePtr == &intObjType
+ && JimWideValue(objPtr) >= MIN_INT_IN_DOUBLE
+ && JimWideValue(objPtr) <= MAX_INT_IN_DOUBLE) {
+
+
+ objPtr->typePtr = &coercedDoubleObjType;
+ return JIM_OK;
+ }
+#endif
+ str = Jim_String(objPtr);
+
+ if (Jim_StringToWide(str, &wideValue, 10) == JIM_OK) {
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &coercedDoubleObjType;
+ objPtr->internalRep.wideValue = wideValue;
+ return JIM_OK;
+ }
+ else {
+
+ if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
+ Jim_SetResultFormatted(interp, "expected floating-point number but got \"%#s\"", objPtr);
+ return JIM_ERR;
+ }
+
+ Jim_FreeIntRep(interp, objPtr);
+ }
+ objPtr->typePtr = &doubleObjType;
+ objPtr->internalRep.doubleValue = doubleValue;
+ return JIM_OK;
+}
+
+int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
+{
+ if (objPtr->typePtr == &coercedDoubleObjType) {
+ *doublePtr = JimWideValue(objPtr);
+ return JIM_OK;
+ }
+ if (objPtr->typePtr != &doubleObjType && SetDoubleFromAny(interp, objPtr) == JIM_ERR)
+ return JIM_ERR;
+
+ if (objPtr->typePtr == &coercedDoubleObjType) {
+ *doublePtr = JimWideValue(objPtr);
+ }
+ else {
+ *doublePtr = objPtr->internalRep.doubleValue;
+ }
+ return JIM_OK;
+}
+
+Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
+{
+ Jim_Obj *objPtr;
+
+ objPtr = Jim_NewObj(interp);
+ objPtr->typePtr = &doubleObjType;
+ objPtr->bytes = NULL;
+ objPtr->internalRep.doubleValue = doubleValue;
+ return objPtr;
+}
+
+static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
+
+int Jim_GetBoolean(Jim_Interp *interp, Jim_Obj *objPtr, int * booleanPtr)
+{
+ if (objPtr->typePtr != &intObjType && SetBooleanFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
+ return JIM_ERR;
+ *booleanPtr = (int) JimWideValue(objPtr);
+ return JIM_OK;
+}
+
+static int SetBooleanFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+ static const char * const falses[] = {
+ "0", "false", "no", "off", NULL
+ };
+ static const char * const trues[] = {
+ "1", "true", "yes", "on", NULL
+ };
+
+ int boolean;
+
+ int index;
+ if (Jim_GetEnum(interp, objPtr, falses, &index, NULL, 0) == JIM_OK) {
+ boolean = 0;
+ } else if (Jim_GetEnum(interp, objPtr, trues, &index, NULL, 0) == JIM_OK) {
+ boolean = 1;
+ } else {
+ if (flags & JIM_ERRMSG) {
+ Jim_SetResultFormatted(interp, "expected boolean but got \"%#s\"", objPtr);
+ }
+ return JIM_ERR;
+ }
+
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &intObjType;
+ objPtr->internalRep.wideValue = boolean;
+ return JIM_OK;
+}
+
+static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec);
+static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
+static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static void UpdateStringOfList(struct Jim_Obj *objPtr);
+static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static const Jim_ObjType listObjType = {
+ "list",
+ FreeListInternalRep,
+ DupListInternalRep,
+ UpdateStringOfList,
+ JIM_TYPE_NONE,
+};
+
+void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ int i;
+
+ for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
+ Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
+ }
+ Jim_Free(objPtr->internalRep.listValue.ele);
+}
+
+void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ int i;
+
+ JIM_NOTUSED(interp);
+
+ dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
+ dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
+ dupPtr->internalRep.listValue.ele =
+ Jim_Alloc(sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.maxLen);
+ memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
+ sizeof(Jim_Obj *) * srcPtr->internalRep.listValue.len);
+ for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
+ Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
+ }
+ dupPtr->typePtr = &listObjType;
+}
+
+#define JIM_ELESTR_SIMPLE 0
+#define JIM_ELESTR_BRACE 1
+#define JIM_ELESTR_QUOTE 2
+static unsigned char ListElementQuotingType(const char *s, int len)
+{
+ int i, level, blevel, trySimple = 1;
+
+
+ if (len == 0)
+ return JIM_ELESTR_BRACE;
+ if (s[0] == '"' || s[0] == '{') {
+ trySimple = 0;
+ goto testbrace;
+ }
+ for (i = 0; i < len; i++) {
+ switch (s[i]) {
+ case ' ':
+ case '$':
+ case '"':
+ case '[':
+ case ']':
+ case ';':
+ case '\\':
+ case '\r':
+ case '\n':
+ case '\t':
+ case '\f':
+ case '\v':
+ trySimple = 0;
+
+ case '{':
+ case '}':
+ goto testbrace;
+ }
+ }
+ return JIM_ELESTR_SIMPLE;
+
+ testbrace:
+
+ if (s[len - 1] == '\\')
+ return JIM_ELESTR_QUOTE;
+ level = 0;
+ blevel = 0;
+ for (i = 0; i < len; i++) {
+ switch (s[i]) {
+ case '{':
+ level++;
+ break;
+ case '}':
+ level--;
+ if (level < 0)
+ return JIM_ELESTR_QUOTE;
+ break;
+ case '[':
+ blevel++;
+ break;
+ case ']':
+ blevel--;
+ break;
+ case '\\':
+ if (s[i + 1] == '\n')
+ return JIM_ELESTR_QUOTE;
+ else if (s[i + 1] != '\0')
+ i++;
+ break;
+ }
+ }
+ if (blevel < 0) {
+ return JIM_ELESTR_QUOTE;
+ }
+
+ if (level == 0) {
+ if (!trySimple)
+ return JIM_ELESTR_BRACE;
+ for (i = 0; i < len; i++) {
+ switch (s[i]) {
+ case ' ':
+ case '$':
+ case '"':
+ case '[':
+ case ']':
+ case ';':
+ case '\\':
+ case '\r':
+ case '\n':
+ case '\t':
+ case '\f':
+ case '\v':
+ return JIM_ELESTR_BRACE;
+ break;
+ }
+ }
+ return JIM_ELESTR_SIMPLE;
+ }
+ return JIM_ELESTR_QUOTE;
+}
+
+static int BackslashQuoteString(const char *s, int len, char *q)
+{
+ char *p = q;
+
+ while (len--) {
+ switch (*s) {
+ case ' ':
+ case '$':
+ case '"':
+ case '[':
+ case ']':
+ case '{':
+ case '}':
+ case ';':
+ case '\\':
+ *p++ = '\\';
+ *p++ = *s++;
+ break;
+ case '\n':
+ *p++ = '\\';
+ *p++ = 'n';
+ s++;
+ break;
+ case '\r':
+ *p++ = '\\';
+ *p++ = 'r';
+ s++;
+ break;
+ case '\t':
+ *p++ = '\\';
+ *p++ = 't';
+ s++;
+ break;
+ case '\f':
+ *p++ = '\\';
+ *p++ = 'f';
+ s++;
+ break;
+ case '\v':
+ *p++ = '\\';
+ *p++ = 'v';
+ s++;
+ break;
+ default:
+ *p++ = *s++;
+ break;
+ }
+ }
+ *p = '\0';
+
+ return p - q;
+}
+
+static void JimMakeListStringRep(Jim_Obj *objPtr, Jim_Obj **objv, int objc)
+{
+ #define STATIC_QUOTING_LEN 32
+ int i, bufLen, realLength;
+ const char *strRep;
+ char *p;
+ unsigned char *quotingType, staticQuoting[STATIC_QUOTING_LEN];
+
+
+ if (objc > STATIC_QUOTING_LEN) {
+ quotingType = Jim_Alloc(objc);
+ }
+ else {
+ quotingType = staticQuoting;
+ }
+ bufLen = 0;
+ for (i = 0; i < objc; i++) {
+ int len;
+
+ strRep = Jim_GetString(objv[i], &len);
+ quotingType[i] = ListElementQuotingType(strRep, len);
+ switch (quotingType[i]) {
+ case JIM_ELESTR_SIMPLE:
+ if (i != 0 || strRep[0] != '#') {
+ bufLen += len;
+ break;
+ }
+
+ quotingType[i] = JIM_ELESTR_BRACE;
+
+ case JIM_ELESTR_BRACE:
+ bufLen += len + 2;
+ break;
+ case JIM_ELESTR_QUOTE:
+ bufLen += len * 2;
+ break;
+ }
+ bufLen++;
+ }
+ bufLen++;
+
+
+ p = objPtr->bytes = Jim_Alloc(bufLen + 1);
+ realLength = 0;
+ for (i = 0; i < objc; i++) {
+ int len, qlen;
+
+ strRep = Jim_GetString(objv[i], &len);
+
+ switch (quotingType[i]) {
+ case JIM_ELESTR_SIMPLE:
+ memcpy(p, strRep, len);
+ p += len;
+ realLength += len;
+ break;
+ case JIM_ELESTR_BRACE:
+ *p++ = '{';
+ memcpy(p, strRep, len);
+ p += len;
+ *p++ = '}';
+ realLength += len + 2;
+ break;
+ case JIM_ELESTR_QUOTE:
+ if (i == 0 && strRep[0] == '#') {
+ *p++ = '\\';
+ realLength++;
+ }
+ qlen = BackslashQuoteString(strRep, len, p);
+ p += qlen;
+ realLength += qlen;
+ break;
+ }
+
+ if (i + 1 != objc) {
+ *p++ = ' ';
+ realLength++;
+ }
+ }
+ *p = '\0';
+ objPtr->length = realLength;
+
+ if (quotingType != staticQuoting) {
+ Jim_Free(quotingType);
+ }
+}
+
+static void UpdateStringOfList(struct Jim_Obj *objPtr)
+{
+ JimMakeListStringRep(objPtr, objPtr->internalRep.listValue.ele, objPtr->internalRep.listValue.len);
+}
+
+static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+ struct JimParserCtx parser;
+ const char *str;
+ int strLen;
+ Jim_Obj *fileNameObj;
+ int linenr;
+
+ if (objPtr->typePtr == &listObjType) {
+ return JIM_OK;
+ }
+
+ if (Jim_IsDict(objPtr) && objPtr->bytes == NULL) {
+ Jim_Obj **listObjPtrPtr;
+ int len;
+ int i;
+
+ listObjPtrPtr = JimDictPairs(objPtr, &len);
+ for (i = 0; i < len; i++) {
+ Jim_IncrRefCount(listObjPtrPtr[i]);
+ }
+
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &listObjType;
+ objPtr->internalRep.listValue.len = len;
+ objPtr->internalRep.listValue.maxLen = len;
+ objPtr->internalRep.listValue.ele = listObjPtrPtr;
+
+ return JIM_OK;
+ }
+
+
+ if (objPtr->typePtr == &sourceObjType) {
+ fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
+ linenr = objPtr->internalRep.sourceValue.lineNumber;
+ }
+ else {
+ fileNameObj = interp->emptyObj;
+ linenr = 1;
+ }
+ Jim_IncrRefCount(fileNameObj);
+
+
+ str = Jim_GetString(objPtr, &strLen);
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &listObjType;
+ objPtr->internalRep.listValue.len = 0;
+ objPtr->internalRep.listValue.maxLen = 0;
+ objPtr->internalRep.listValue.ele = NULL;
+
+
+ if (strLen) {
+ JimParserInit(&parser, str, strLen, linenr);
+ while (!parser.eof) {
+ Jim_Obj *elementPtr;
+
+ JimParseList(&parser);
+ if (parser.tt != JIM_TT_STR && parser.tt != JIM_TT_ESC)
+ continue;
+ elementPtr = JimParserGetTokenObj(interp, &parser);
+ JimSetSourceInfo(interp, elementPtr, fileNameObj, parser.tline);
+ ListAppendElement(objPtr, elementPtr);
+ }
+ }
+ Jim_DecrRefCount(interp, fileNameObj);
+ return JIM_OK;
+}
+
+Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
+{
+ Jim_Obj *objPtr;
+
+ objPtr = Jim_NewObj(interp);
+ objPtr->typePtr = &listObjType;
+ objPtr->bytes = NULL;
+ objPtr->internalRep.listValue.ele = NULL;
+ objPtr->internalRep.listValue.len = 0;
+ objPtr->internalRep.listValue.maxLen = 0;
+
+ if (len) {
+ ListInsertElements(objPtr, 0, len, elements);
+ }
+
+ return objPtr;
+}
+
+static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *listLen,
+ Jim_Obj ***listVec)
+{
+ *listLen = Jim_ListLength(interp, listObj);
+ *listVec = listObj->internalRep.listValue.ele;
+}
+
+
+static int JimSign(jim_wide w)
+{
+ if (w == 0) {
+ return 0;
+ }
+ else if (w < 0) {
+ return -1;
+ }
+ return 1;
+}
+
+
+struct lsort_info {
+ jmp_buf jmpbuf;
+ Jim_Obj *command;
+ Jim_Interp *interp;
+ enum {
+ JIM_LSORT_ASCII,
+ JIM_LSORT_NOCASE,
+ JIM_LSORT_INTEGER,
+ JIM_LSORT_REAL,
+ JIM_LSORT_COMMAND
+ } type;
+ int order;
+ int index;
+ int indexed;
+ int unique;
+ int (*subfn)(Jim_Obj **, Jim_Obj **);
+};
+
+static struct lsort_info *sort_info;
+
+static int ListSortIndexHelper(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+ Jim_Obj *lObj, *rObj;
+
+ if (Jim_ListIndex(sort_info->interp, *lhsObj, sort_info->index, &lObj, JIM_ERRMSG) != JIM_OK ||
+ Jim_ListIndex(sort_info->interp, *rhsObj, sort_info->index, &rObj, JIM_ERRMSG) != JIM_OK) {
+ longjmp(sort_info->jmpbuf, JIM_ERR);
+ }
+ return sort_info->subfn(&lObj, &rObj);
+}
+
+
+static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+ return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 0) * sort_info->order;
+}
+
+static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+ return Jim_StringCompareObj(sort_info->interp, *lhsObj, *rhsObj, 1) * sort_info->order;
+}
+
+static int ListSortInteger(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+ jim_wide lhs = 0, rhs = 0;
+
+ if (Jim_GetWide(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
+ Jim_GetWide(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
+ longjmp(sort_info->jmpbuf, JIM_ERR);
+ }
+
+ return JimSign(lhs - rhs) * sort_info->order;
+}
+
+static int ListSortReal(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+ double lhs = 0, rhs = 0;
+
+ if (Jim_GetDouble(sort_info->interp, *lhsObj, &lhs) != JIM_OK ||
+ Jim_GetDouble(sort_info->interp, *rhsObj, &rhs) != JIM_OK) {
+ longjmp(sort_info->jmpbuf, JIM_ERR);
+ }
+ if (lhs == rhs) {
+ return 0;
+ }
+ if (lhs > rhs) {
+ return sort_info->order;
+ }
+ return -sort_info->order;
+}
+
+static int ListSortCommand(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+ Jim_Obj *compare_script;
+ int rc;
+
+ jim_wide ret = 0;
+
+
+ compare_script = Jim_DuplicateObj(sort_info->interp, sort_info->command);
+ Jim_ListAppendElement(sort_info->interp, compare_script, *lhsObj);
+ Jim_ListAppendElement(sort_info->interp, compare_script, *rhsObj);
+
+ rc = Jim_EvalObj(sort_info->interp, compare_script);
+
+ if (rc != JIM_OK || Jim_GetWide(sort_info->interp, Jim_GetResult(sort_info->interp), &ret) != JIM_OK) {
+ longjmp(sort_info->jmpbuf, rc);
+ }
+
+ return JimSign(ret) * sort_info->order;
+}
+
+static void ListRemoveDuplicates(Jim_Obj *listObjPtr, int (*comp)(Jim_Obj **lhs, Jim_Obj **rhs))
+{
+ int src;
+ int dst = 0;
+ Jim_Obj **ele = listObjPtr->internalRep.listValue.ele;
+
+ for (src = 1; src < listObjPtr->internalRep.listValue.len; src++) {
+ if (comp(&ele[dst], &ele[src]) == 0) {
+
+ Jim_DecrRefCount(sort_info->interp, ele[dst]);
+ }
+ else {
+
+ dst++;
+ }
+ ele[dst] = ele[src];
+ }
+
+
+ dst++;
+ if (dst < listObjPtr->internalRep.listValue.len) {
+ ele[dst] = ele[src];
+ }
+
+
+ listObjPtr->internalRep.listValue.len = dst;
+}
+
+
+static int ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, struct lsort_info *info)
+{
+ struct lsort_info *prev_info;
+
+ typedef int (qsort_comparator) (const void *, const void *);
+ int (*fn) (Jim_Obj **, Jim_Obj **);
+ Jim_Obj **vector;
+ int len;
+ int rc;
+
+ JimPanic((Jim_IsShared(listObjPtr), "ListSortElements called with shared object"));
+ SetListFromAny(interp, listObjPtr);
+
+
+ prev_info = sort_info;
+ sort_info = info;
+
+ vector = listObjPtr->internalRep.listValue.ele;
+ len = listObjPtr->internalRep.listValue.len;
+ switch (info->type) {
+ case JIM_LSORT_ASCII:
+ fn = ListSortString;
+ break;
+ case JIM_LSORT_NOCASE:
+ fn = ListSortStringNoCase;
+ break;
+ case JIM_LSORT_INTEGER:
+ fn = ListSortInteger;
+ break;
+ case JIM_LSORT_REAL:
+ fn = ListSortReal;
+ break;
+ case JIM_LSORT_COMMAND:
+ fn = ListSortCommand;
+ break;
+ default:
+ fn = NULL;
+ JimPanic((1, "ListSort called with invalid sort type"));
+ return -1;
+ }
+
+ if (info->indexed) {
+
+ info->subfn = fn;
+ fn = ListSortIndexHelper;
+ }
+
+ if ((rc = setjmp(info->jmpbuf)) == 0) {
+ qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *) fn);
+
+ if (info->unique && len > 1) {
+ ListRemoveDuplicates(listObjPtr, fn);
+ }
+
+ Jim_InvalidateStringRep(listObjPtr);
+ }
+ sort_info = prev_info;
+
+ return rc;
+}
+
+static void ListInsertElements(Jim_Obj *listPtr, int idx, int elemc, Jim_Obj *const *elemVec)
+{
+ int currentLen = listPtr->internalRep.listValue.len;
+ int requiredLen = currentLen + elemc;
+ int i;
+ Jim_Obj **point;
+
+ if (requiredLen > listPtr->internalRep.listValue.maxLen) {
+ if (requiredLen < 2) {
+
+ requiredLen = 4;
+ }
+ else {
+ requiredLen *= 2;
+ }
+
+ listPtr->internalRep.listValue.ele = Jim_Realloc(listPtr->internalRep.listValue.ele,
+ sizeof(Jim_Obj *) * requiredLen);
+
+ listPtr->internalRep.listValue.maxLen = requiredLen;
+ }
+ if (idx < 0) {
+ idx = currentLen;
+ }
+ point = listPtr->internalRep.listValue.ele + idx;
+ memmove(point + elemc, point, (currentLen - idx) * sizeof(Jim_Obj *));
+ for (i = 0; i < elemc; ++i) {
+ point[i] = elemVec[i];
+ Jim_IncrRefCount(point[i]);
+ }
+ listPtr->internalRep.listValue.len += elemc;
+}
+
+static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
+{
+ ListInsertElements(listPtr, -1, 1, &objPtr);
+}
+
+static void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
+{
+ ListInsertElements(listPtr, -1,
+ appendListPtr->internalRep.listValue.len, appendListPtr->internalRep.listValue.ele);
+}
+
+void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
+{
+ JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendElement called with shared object"));
+ SetListFromAny(interp, listPtr);
+ Jim_InvalidateStringRep(listPtr);
+ ListAppendElement(listPtr, objPtr);
+}
+
+void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
+{
+ JimPanic((Jim_IsShared(listPtr), "Jim_ListAppendList called with shared object"));
+ SetListFromAny(interp, listPtr);
+ SetListFromAny(interp, appendListPtr);
+ Jim_InvalidateStringRep(listPtr);
+ ListAppendList(listPtr, appendListPtr);
+}
+
+int Jim_ListLength(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ SetListFromAny(interp, objPtr);
+ return objPtr->internalRep.listValue.len;
+}
+
+void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
+ int objc, Jim_Obj *const *objVec)
+{
+ JimPanic((Jim_IsShared(listPtr), "Jim_ListInsertElement called with shared object"));
+ SetListFromAny(interp, listPtr);
+ if (idx >= 0 && idx > listPtr->internalRep.listValue.len)
+ idx = listPtr->internalRep.listValue.len;
+ else if (idx < 0)
+ idx = 0;
+ Jim_InvalidateStringRep(listPtr);
+ ListInsertElements(listPtr, idx, objc, objVec);
+}
+
+Jim_Obj *Jim_ListGetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx)
+{
+ SetListFromAny(interp, listPtr);
+ if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
+ (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
+ return NULL;
+ }
+ if (idx < 0)
+ idx = listPtr->internalRep.listValue.len + idx;
+ return listPtr->internalRep.listValue.ele[idx];
+}
+
+int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx, Jim_Obj **objPtrPtr, int flags)
+{
+ *objPtrPtr = Jim_ListGetIndex(interp, listPtr, idx);
+ if (*objPtrPtr == NULL) {
+ if (flags & JIM_ERRMSG) {
+ Jim_SetResultString(interp, "list index out of range", -1);
+ }
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int idx,
+ Jim_Obj *newObjPtr, int flags)
+{
+ SetListFromAny(interp, listPtr);
+ if ((idx >= 0 && idx >= listPtr->internalRep.listValue.len) ||
+ (idx < 0 && (-idx - 1) >= listPtr->internalRep.listValue.len)) {
+ if (flags & JIM_ERRMSG) {
+ Jim_SetResultString(interp, "list index out of range", -1);
+ }
+ return JIM_ERR;
+ }
+ if (idx < 0)
+ idx = listPtr->internalRep.listValue.len + idx;
+ Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[idx]);
+ listPtr->internalRep.listValue.ele[idx] = newObjPtr;
+ Jim_IncrRefCount(newObjPtr);
+ return JIM_OK;
+}
+
+int Jim_ListSetIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
+ Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
+{
+ Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
+ int shared, i, idx;
+
+ varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG | JIM_UNSHARED);
+ if (objPtr == NULL)
+ return JIM_ERR;
+ if ((shared = Jim_IsShared(objPtr)))
+ varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
+ for (i = 0; i < indexc - 1; i++) {
+ listObjPtr = objPtr;
+ if (Jim_GetIndex(interp, indexv[i], &idx) != JIM_OK)
+ goto err;
+ if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_ERRMSG) != JIM_OK) {
+ goto err;
+ }
+ if (Jim_IsShared(objPtr)) {
+ objPtr = Jim_DuplicateObj(interp, objPtr);
+ ListSetIndex(interp, listObjPtr, idx, objPtr, JIM_NONE);
+ }
+ Jim_InvalidateStringRep(listObjPtr);
+ }
+ if (Jim_GetIndex(interp, indexv[indexc - 1], &idx) != JIM_OK)
+ goto err;
+ if (ListSetIndex(interp, objPtr, idx, newObjPtr, JIM_ERRMSG) == JIM_ERR)
+ goto err;
+ Jim_InvalidateStringRep(objPtr);
+ Jim_InvalidateStringRep(varObjPtr);
+ if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
+ goto err;
+ Jim_SetResult(interp, varObjPtr);
+ return JIM_OK;
+ err:
+ if (shared) {
+ Jim_FreeNewObj(interp, varObjPtr);
+ }
+ return JIM_ERR;
+}
+
+Jim_Obj *Jim_ListJoin(Jim_Interp *interp, Jim_Obj *listObjPtr, const char *joinStr, int joinStrLen)
+{
+ int i;
+ int listLen = Jim_ListLength(interp, listObjPtr);
+ Jim_Obj *resObjPtr = Jim_NewEmptyStringObj(interp);
+
+ for (i = 0; i < listLen; ) {
+ Jim_AppendObj(interp, resObjPtr, Jim_ListGetIndex(interp, listObjPtr, i));
+ if (++i != listLen) {
+ Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
+ }
+ }
+ return resObjPtr;
+}
+
+Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+{
+ int i;
+
+ for (i = 0; i < objc; i++) {
+ if (!Jim_IsList(objv[i]))
+ break;
+ }
+ if (i == objc) {
+ Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
+
+ for (i = 0; i < objc; i++)
+ ListAppendList(objPtr, objv[i]);
+ return objPtr;
+ }
+ else {
+
+ int len = 0, objLen;
+ char *bytes, *p;
+
+
+ for (i = 0; i < objc; i++) {
+ len += Jim_Length(objv[i]);
+ }
+ if (objc)
+ len += objc - 1;
+
+ p = bytes = Jim_Alloc(len + 1);
+ for (i = 0; i < objc; i++) {
+ const char *s = Jim_GetString(objv[i], &objLen);
+
+
+ while (objLen && isspace(UCHAR(*s))) {
+ s++;
+ objLen--;
+ len--;
+ }
+
+ while (objLen && isspace(UCHAR(s[objLen - 1]))) {
+
+ if (objLen > 1 && s[objLen - 2] == '\\') {
+ break;
+ }
+ objLen--;
+ len--;
+ }
+ memcpy(p, s, objLen);
+ p += objLen;
+ if (i + 1 != objc) {
+ if (objLen)
+ *p++ = ' ';
+ else {
+ len--;
+ }
+ }
+ }
+ *p = '\0';
+ return Jim_NewStringObjNoAlloc(interp, bytes, len);
+ }
+}
+
+Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr,
+ Jim_Obj *lastObjPtr)
+{
+ int first, last;
+ int len, rangeLen;
+
+ if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
+ Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
+ return NULL;
+ len = Jim_ListLength(interp, listObjPtr);
+ first = JimRelToAbsIndex(len, first);
+ last = JimRelToAbsIndex(len, last);
+ JimRelToAbsRange(len, &first, &last, &rangeLen);
+ if (first == 0 && last == len) {
+ return listObjPtr;
+ }
+ return Jim_NewListObj(interp, listObjPtr->internalRep.listValue.ele + first, rangeLen);
+}
+
+static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static void UpdateStringOfDict(struct Jim_Obj *objPtr);
+static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+
+static unsigned int JimObjectHTHashFunction(const void *key)
+{
+ int len;
+ const char *str = Jim_GetString((Jim_Obj *)key, &len);
+ return Jim_GenHashFunction((const unsigned char *)str, len);
+}
+
+static int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
+{
+ return Jim_StringEqObj((Jim_Obj *)key1, (Jim_Obj *)key2);
+}
+
+static void *JimObjectHTKeyValDup(void *privdata, const void *val)
+{
+ Jim_IncrRefCount((Jim_Obj *)val);
+ return (void *)val;
+}
+
+static void JimObjectHTKeyValDestructor(void *interp, void *val)
+{
+ Jim_DecrRefCount(interp, (Jim_Obj *)val);
+}
+
+static const Jim_HashTableType JimDictHashTableType = {
+ JimObjectHTHashFunction,
+ JimObjectHTKeyValDup,
+ JimObjectHTKeyValDup,
+ JimObjectHTKeyCompare,
+ JimObjectHTKeyValDestructor,
+ JimObjectHTKeyValDestructor
+};
+
+static const Jim_ObjType dictObjType = {
+ "dict",
+ FreeDictInternalRep,
+ DupDictInternalRep,
+ UpdateStringOfDict,
+ JIM_TYPE_NONE,
+};
+
+void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ JIM_NOTUSED(interp);
+
+ Jim_FreeHashTable(objPtr->internalRep.ptr);
+ Jim_Free(objPtr->internalRep.ptr);
+}
+
+void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ Jim_HashTable *ht, *dupHt;
+ Jim_HashTableIterator htiter;
+ Jim_HashEntry *he;
+
+
+ ht = srcPtr->internalRep.ptr;
+ dupHt = Jim_Alloc(sizeof(*dupHt));
+ Jim_InitHashTable(dupHt, &JimDictHashTableType, interp);
+ if (ht->size != 0)
+ Jim_ExpandHashTable(dupHt, ht->size);
+
+ JimInitHashTableIterator(ht, &htiter);
+ while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+ Jim_AddHashEntry(dupHt, he->key, he->u.val);
+ }
+
+ dupPtr->internalRep.ptr = dupHt;
+ dupPtr->typePtr = &dictObjType;
+}
+
+static Jim_Obj **JimDictPairs(Jim_Obj *dictPtr, int *len)
+{
+ Jim_HashTable *ht;
+ Jim_HashTableIterator htiter;
+ Jim_HashEntry *he;
+ Jim_Obj **objv;
+ int i;
+
+ ht = dictPtr->internalRep.ptr;
+
+
+ objv = Jim_Alloc((ht->used * 2) * sizeof(Jim_Obj *));
+ JimInitHashTableIterator(ht, &htiter);
+ i = 0;
+ while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+ objv[i++] = Jim_GetHashEntryKey(he);
+ objv[i++] = Jim_GetHashEntryVal(he);
+ }
+ *len = i;
+ return objv;
+}
+
+static void UpdateStringOfDict(struct Jim_Obj *objPtr)
+{
+
+ int len;
+ Jim_Obj **objv = JimDictPairs(objPtr, &len);
+
+
+ JimMakeListStringRep(objPtr, objv, len);
+
+ Jim_Free(objv);
+}
+
+static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+ int listlen;
+
+ if (objPtr->typePtr == &dictObjType) {
+ return JIM_OK;
+ }
+
+ if (Jim_IsList(objPtr) && Jim_IsShared(objPtr)) {
+ Jim_String(objPtr);
+ }
+
+
+ listlen = Jim_ListLength(interp, objPtr);
+ if (listlen % 2) {
+ Jim_SetResultString(interp, "missing value to go with key", -1);
+ return JIM_ERR;
+ }
+ else {
+
+ Jim_HashTable *ht;
+ int i;
+
+ ht = Jim_Alloc(sizeof(*ht));
+ Jim_InitHashTable(ht, &JimDictHashTableType, interp);
+
+ for (i = 0; i < listlen; i += 2) {
+ Jim_Obj *keyObjPtr = Jim_ListGetIndex(interp, objPtr, i);
+ Jim_Obj *valObjPtr = Jim_ListGetIndex(interp, objPtr, i + 1);
+
+ Jim_ReplaceHashEntry(ht, keyObjPtr, valObjPtr);
+ }
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &dictObjType;
+ objPtr->internalRep.ptr = ht;
+
+ return JIM_OK;
+ }
+}
+
+
+
+static int DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+ Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
+{
+ Jim_HashTable *ht = objPtr->internalRep.ptr;
+
+ if (valueObjPtr == NULL) {
+ return Jim_DeleteHashEntry(ht, keyObjPtr);
+ }
+ Jim_ReplaceHashEntry(ht, keyObjPtr, valueObjPtr);
+ return JIM_OK;
+}
+
+int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+ Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
+{
+ JimPanic((Jim_IsShared(objPtr), "Jim_DictAddElement called with shared object"));
+ if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_InvalidateStringRep(objPtr);
+ return DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
+}
+
+Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
+{
+ Jim_Obj *objPtr;
+ int i;
+
+ JimPanic((len % 2, "Jim_NewDictObj() 'len' argument must be even"));
+
+ objPtr = Jim_NewObj(interp);
+ objPtr->typePtr = &dictObjType;
+ objPtr->bytes = NULL;
+ objPtr->internalRep.ptr = Jim_Alloc(sizeof(Jim_HashTable));
+ Jim_InitHashTable(objPtr->internalRep.ptr, &JimDictHashTableType, interp);
+ for (i = 0; i < len; i += 2)
+ DictAddElement(interp, objPtr, elements[i], elements[i + 1]);
+ return objPtr;
+}
+
+int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
+ Jim_Obj **objPtrPtr, int flags)
+{
+ Jim_HashEntry *he;
+ Jim_HashTable *ht;
+
+ if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
+ return -1;
+ }
+ ht = dictPtr->internalRep.ptr;
+ if ((he = Jim_FindHashEntry(ht, keyPtr)) == NULL) {
+ if (flags & JIM_ERRMSG) {
+ Jim_SetResultFormatted(interp, "key \"%#s\" not known in dictionary", keyPtr);
+ }
+ return JIM_ERR;
+ }
+ else {
+ *objPtrPtr = Jim_GetHashEntryVal(he);
+ return JIM_OK;
+ }
+}
+
+
+int Jim_DictPairs(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj ***objPtrPtr, int *len)
+{
+ if (SetDictFromAny(interp, dictPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+ *objPtrPtr = JimDictPairs(dictPtr, len);
+
+ return JIM_OK;
+}
+
+
+
+int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
+ Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
+{
+ int i;
+
+ if (keyc == 0) {
+ *objPtrPtr = dictPtr;
+ return JIM_OK;
+ }
+
+ for (i = 0; i < keyc; i++) {
+ Jim_Obj *objPtr;
+
+ int rc = Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags);
+ if (rc != JIM_OK) {
+ return rc;
+ }
+ dictPtr = objPtr;
+ }
+ *objPtrPtr = dictPtr;
+ return JIM_OK;
+}
+
+int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
+ Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr, int flags)
+{
+ Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
+ int shared, i;
+
+ varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, flags);
+ if (objPtr == NULL) {
+ if (newObjPtr == NULL && (flags & JIM_MUSTEXIST)) {
+
+ return JIM_ERR;
+ }
+ varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
+ if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
+ Jim_FreeNewObj(interp, varObjPtr);
+ return JIM_ERR;
+ }
+ }
+ if ((shared = Jim_IsShared(objPtr)))
+ varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
+ for (i = 0; i < keyc; i++) {
+ dictObjPtr = objPtr;
+
+
+ if (SetDictFromAny(interp, dictObjPtr) != JIM_OK) {
+ goto err;
+ }
+
+ if (i == keyc - 1) {
+
+ if (Jim_DictAddElement(interp, objPtr, keyv[keyc - 1], newObjPtr) != JIM_OK) {
+ if (newObjPtr || (flags & JIM_MUSTEXIST)) {
+ goto err;
+ }
+ }
+ break;
+ }
+
+
+ Jim_InvalidateStringRep(dictObjPtr);
+ if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
+ newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK) {
+ if (Jim_IsShared(objPtr)) {
+ objPtr = Jim_DuplicateObj(interp, objPtr);
+ DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
+ }
+ }
+ else {
+ if (newObjPtr == NULL) {
+ goto err;
+ }
+ objPtr = Jim_NewDictObj(interp, NULL, 0);
+ DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
+ }
+ }
+
+ Jim_InvalidateStringRep(objPtr);
+ Jim_InvalidateStringRep(varObjPtr);
+ if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK) {
+ goto err;
+ }
+ Jim_SetResult(interp, varObjPtr);
+ return JIM_OK;
+ err:
+ if (shared) {
+ Jim_FreeNewObj(interp, varObjPtr);
+ }
+ return JIM_ERR;
+}
+
+static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
+static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static const Jim_ObjType indexObjType = {
+ "index",
+ NULL,
+ NULL,
+ UpdateStringOfIndex,
+ JIM_TYPE_NONE,
+};
+
+static void UpdateStringOfIndex(struct Jim_Obj *objPtr)
+{
+ if (objPtr->internalRep.intValue == -1) {
+ JimSetStringBytes(objPtr, "end");
+ }
+ else {
+ char buf[JIM_INTEGER_SPACE + 1];
+ if (objPtr->internalRep.intValue >= 0) {
+ sprintf(buf, "%d", objPtr->internalRep.intValue);
+ }
+ else {
+
+ sprintf(buf, "end%d", objPtr->internalRep.intValue + 1);
+ }
+ JimSetStringBytes(objPtr, buf);
+ }
+}
+
+static int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ int idx, end = 0;
+ const char *str;
+ char *endptr;
+
+
+ str = Jim_String(objPtr);
+
+
+ if (strncmp(str, "end", 3) == 0) {
+ end = 1;
+ str += 3;
+ idx = 0;
+ }
+ else {
+ idx = jim_strtol(str, &endptr);
+
+ if (endptr == str) {
+ goto badindex;
+ }
+ str = endptr;
+ }
+
+
+ if (*str == '+' || *str == '-') {
+ int sign = (*str == '+' ? 1 : -1);
+
+ idx += sign * jim_strtol(++str, &endptr);
+ if (str == endptr || *endptr) {
+ goto badindex;
+ }
+ str = endptr;
+ }
+
+ while (isspace(UCHAR(*str))) {
+ str++;
+ }
+ if (*str) {
+ goto badindex;
+ }
+ if (end) {
+ if (idx > 0) {
+ idx = INT_MAX;
+ }
+ else {
+
+ idx--;
+ }
+ }
+ else if (idx < 0) {
+ idx = -INT_MAX;
+ }
+
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &indexObjType;
+ objPtr->internalRep.intValue = idx;
+ return JIM_OK;
+
+ badindex:
+ Jim_SetResultFormatted(interp,
+ "bad index \"%#s\": must be integer?[+-]integer? or end?[+-]integer?", objPtr);
+ return JIM_ERR;
+}
+
+int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
+{
+
+ if (objPtr->typePtr == &intObjType) {
+ jim_wide val = JimWideValue(objPtr);
+
+ if (val < 0)
+ *indexPtr = -INT_MAX;
+ else if (val > INT_MAX)
+ *indexPtr = INT_MAX;
+ else
+ *indexPtr = (int)val;
+ return JIM_OK;
+ }
+ if (objPtr->typePtr != &indexObjType && SetIndexFromAny(interp, objPtr) == JIM_ERR)
+ return JIM_ERR;
+ *indexPtr = objPtr->internalRep.intValue;
+ return JIM_OK;
+}
+
+
+
+static const char * const jimReturnCodes[] = {
+ "ok",
+ "error",
+ "return",
+ "break",
+ "continue",
+ "signal",
+ "exit",
+ "eval",
+ NULL
+};
+
+#define jimReturnCodesSize (sizeof(jimReturnCodes)/sizeof(*jimReturnCodes) - 1)
+
+static const Jim_ObjType returnCodeObjType = {
+ "return-code",
+ NULL,
+ NULL,
+ NULL,
+ JIM_TYPE_NONE,
+};
+
+const char *Jim_ReturnCode(int code)
+{
+ if (code < 0 || code >= (int)jimReturnCodesSize) {
+ return "?";
+ }
+ else {
+ return jimReturnCodes[code];
+ }
+}
+
+static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ int returnCode;
+ jim_wide wideValue;
+
+
+ if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
+ returnCode = (int)wideValue;
+ else if (Jim_GetEnum(interp, objPtr, jimReturnCodes, &returnCode, NULL, JIM_NONE) != JIM_OK) {
+ Jim_SetResultFormatted(interp, "expected return code but got \"%#s\"", objPtr);
+ return JIM_ERR;
+ }
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &returnCodeObjType;
+ objPtr->internalRep.intValue = returnCode;
+ return JIM_OK;
+}
+
+int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
+{
+ if (objPtr->typePtr != &returnCodeObjType && SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
+ return JIM_ERR;
+ *intPtr = objPtr->internalRep.intValue;
+ return JIM_OK;
+}
+
+static int JimParseExprOperator(struct JimParserCtx *pc);
+static int JimParseExprNumber(struct JimParserCtx *pc);
+static int JimParseExprIrrational(struct JimParserCtx *pc);
+static int JimParseExprBoolean(struct JimParserCtx *pc);
+
+
+enum
+{
+
+
+
+ JIM_EXPROP_MUL = JIM_TT_EXPR_OP,
+ JIM_EXPROP_DIV,
+ JIM_EXPROP_MOD,
+ JIM_EXPROP_SUB,
+ JIM_EXPROP_ADD,
+ JIM_EXPROP_LSHIFT,
+ JIM_EXPROP_RSHIFT,
+ JIM_EXPROP_ROTL,
+ JIM_EXPROP_ROTR,
+ JIM_EXPROP_LT,
+ JIM_EXPROP_GT,
+ JIM_EXPROP_LTE,
+ JIM_EXPROP_GTE,
+ JIM_EXPROP_NUMEQ,
+ JIM_EXPROP_NUMNE,
+ JIM_EXPROP_BITAND,
+ JIM_EXPROP_BITXOR,
+ JIM_EXPROP_BITOR,
+ JIM_EXPROP_LOGICAND,
+ JIM_EXPROP_LOGICOR,
+ JIM_EXPROP_TERNARY,
+ JIM_EXPROP_COLON,
+ JIM_EXPROP_POW,
+
+
+ JIM_EXPROP_STREQ,
+ JIM_EXPROP_STRNE,
+ JIM_EXPROP_STRIN,
+ JIM_EXPROP_STRNI,
+
+
+ JIM_EXPROP_NOT,
+ JIM_EXPROP_BITNOT,
+ JIM_EXPROP_UNARYMINUS,
+ JIM_EXPROP_UNARYPLUS,
+
+
+ JIM_EXPROP_FUNC_INT,
+ JIM_EXPROP_FUNC_WIDE,
+ JIM_EXPROP_FUNC_ABS,
+ JIM_EXPROP_FUNC_DOUBLE,
+ JIM_EXPROP_FUNC_ROUND,
+ JIM_EXPROP_FUNC_RAND,
+ JIM_EXPROP_FUNC_SRAND,
+
+
+ JIM_EXPROP_FUNC_SIN,
+ JIM_EXPROP_FUNC_COS,
+ JIM_EXPROP_FUNC_TAN,
+ JIM_EXPROP_FUNC_ASIN,
+ JIM_EXPROP_FUNC_ACOS,
+ JIM_EXPROP_FUNC_ATAN,
+ JIM_EXPROP_FUNC_ATAN2,
+ JIM_EXPROP_FUNC_SINH,
+ JIM_EXPROP_FUNC_COSH,
+ JIM_EXPROP_FUNC_TANH,
+ JIM_EXPROP_FUNC_CEIL,
+ JIM_EXPROP_FUNC_FLOOR,
+ JIM_EXPROP_FUNC_EXP,
+ JIM_EXPROP_FUNC_LOG,
+ JIM_EXPROP_FUNC_LOG10,
+ JIM_EXPROP_FUNC_SQRT,
+ JIM_EXPROP_FUNC_POW,
+ JIM_EXPROP_FUNC_HYPOT,
+ JIM_EXPROP_FUNC_FMOD,
+};
+
+struct JimExprNode {
+ int type;
+ struct Jim_Obj *objPtr;
+
+ struct JimExprNode *left;
+ struct JimExprNode *right;
+ struct JimExprNode *ternary;
+};
+
+
+typedef struct Jim_ExprOperator
+{
+ const char *name;
+ int (*funcop) (Jim_Interp *interp, struct JimExprNode *opnode);
+ unsigned char precedence;
+ unsigned char arity;
+ unsigned char attr;
+ unsigned char namelen;
+} Jim_ExprOperator;
+
+static int JimExprGetTerm(Jim_Interp *interp, struct JimExprNode *node, Jim_Obj **objPtrPtr);
+static int JimExprGetTermBoolean(Jim_Interp *interp, struct JimExprNode *node);
+static int JimExprEvalTermNode(Jim_Interp *interp, struct JimExprNode *node);
+
+static int JimExprOpNumUnary(Jim_Interp *interp, struct JimExprNode *node)
+{
+ int intresult = 1;
+ int rc;
+ double dA, dC = 0;
+ jim_wide wA, wC = 0;
+ Jim_Obj *A;
+
+ if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
+ return rc;
+ }
+
+ if ((A->typePtr != &doubleObjType || A->bytes) && JimGetWideNoErr(interp, A, &wA) == JIM_OK) {
+ switch (node->type) {
+ case JIM_EXPROP_FUNC_INT:
+ case JIM_EXPROP_FUNC_WIDE:
+ case JIM_EXPROP_FUNC_ROUND:
+ case JIM_EXPROP_UNARYPLUS:
+ wC = wA;
+ break;
+ case JIM_EXPROP_FUNC_DOUBLE:
+ dC = wA;
+ intresult = 0;
+ break;
+ case JIM_EXPROP_FUNC_ABS:
+ wC = wA >= 0 ? wA : -wA;
+ break;
+ case JIM_EXPROP_UNARYMINUS:
+ wC = -wA;
+ break;
+ case JIM_EXPROP_NOT:
+ wC = !wA;
+ break;
+ default:
+ abort();
+ }
+ }
+ else if ((rc = Jim_GetDouble(interp, A, &dA)) == JIM_OK) {
+ switch (node->type) {
+ case JIM_EXPROP_FUNC_INT:
+ case JIM_EXPROP_FUNC_WIDE:
+ wC = dA;
+ break;
+ case JIM_EXPROP_FUNC_ROUND:
+ wC = dA < 0 ? (dA - 0.5) : (dA + 0.5);
+ break;
+ case JIM_EXPROP_FUNC_DOUBLE:
+ case JIM_EXPROP_UNARYPLUS:
+ dC = dA;
+ intresult = 0;
+ break;
+ case JIM_EXPROP_FUNC_ABS:
+#ifdef JIM_MATH_FUNCTIONS
+ dC = fabs(dA);
+#else
+ dC = dA >= 0 ? dA : -dA;
+#endif
+ intresult = 0;
+ break;
+ case JIM_EXPROP_UNARYMINUS:
+ dC = -dA;
+ intresult = 0;
+ break;
+ case JIM_EXPROP_NOT:
+ wC = !dA;
+ break;
+ default:
+ abort();
+ }
+ }
+
+ if (rc == JIM_OK) {
+ if (intresult) {
+ Jim_SetResultInt(interp, wC);
+ }
+ else {
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
+ }
+ }
+
+ Jim_DecrRefCount(interp, A);
+
+ return rc;
+}
+
+static double JimRandDouble(Jim_Interp *interp)
+{
+ unsigned long x;
+ JimRandomBytes(interp, &x, sizeof(x));
+
+ return (double)x / (unsigned long)~0;
+}
+
+static int JimExprOpIntUnary(Jim_Interp *interp, struct JimExprNode *node)
+{
+ jim_wide wA;
+ Jim_Obj *A;
+ int rc;
+
+ if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
+ return rc;
+ }
+
+ rc = Jim_GetWide(interp, A, &wA);
+ if (rc == JIM_OK) {
+ switch (node->type) {
+ case JIM_EXPROP_BITNOT:
+ Jim_SetResultInt(interp, ~wA);
+ break;
+ case JIM_EXPROP_FUNC_SRAND:
+ JimPrngSeed(interp, (unsigned char *)&wA, sizeof(wA));
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
+ break;
+ default:
+ abort();
+ }
+ }
+
+ Jim_DecrRefCount(interp, A);
+
+ return rc;
+}
+
+static int JimExprOpNone(Jim_Interp *interp, struct JimExprNode *node)
+{
+ JimPanic((node->type != JIM_EXPROP_FUNC_RAND, "JimExprOpNone only support rand()"));
+
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, JimRandDouble(interp)));
+
+ return JIM_OK;
+}
+
+#ifdef JIM_MATH_FUNCTIONS
+static int JimExprOpDoubleUnary(Jim_Interp *interp, struct JimExprNode *node)
+{
+ int rc;
+ double dA, dC;
+ Jim_Obj *A;
+
+ if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
+ return rc;
+ }
+
+ rc = Jim_GetDouble(interp, A, &dA);
+ if (rc == JIM_OK) {
+ switch (node->type) {
+ case JIM_EXPROP_FUNC_SIN:
+ dC = sin(dA);
+ break;
+ case JIM_EXPROP_FUNC_COS:
+ dC = cos(dA);
+ break;
+ case JIM_EXPROP_FUNC_TAN:
+ dC = tan(dA);
+ break;
+ case JIM_EXPROP_FUNC_ASIN:
+ dC = asin(dA);
+ break;
+ case JIM_EXPROP_FUNC_ACOS:
+ dC = acos(dA);
+ break;
+ case JIM_EXPROP_FUNC_ATAN:
+ dC = atan(dA);
+ break;
+ case JIM_EXPROP_FUNC_SINH:
+ dC = sinh(dA);
+ break;
+ case JIM_EXPROP_FUNC_COSH:
+ dC = cosh(dA);
+ break;
+ case JIM_EXPROP_FUNC_TANH:
+ dC = tanh(dA);
+ break;
+ case JIM_EXPROP_FUNC_CEIL:
+ dC = ceil(dA);
+ break;
+ case JIM_EXPROP_FUNC_FLOOR:
+ dC = floor(dA);
+ break;
+ case JIM_EXPROP_FUNC_EXP:
+ dC = exp(dA);
+ break;
+ case JIM_EXPROP_FUNC_LOG:
+ dC = log(dA);
+ break;
+ case JIM_EXPROP_FUNC_LOG10:
+ dC = log10(dA);
+ break;
+ case JIM_EXPROP_FUNC_SQRT:
+ dC = sqrt(dA);
+ break;
+ default:
+ abort();
+ }
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
+ }
+
+ Jim_DecrRefCount(interp, A);
+
+ return rc;
+}
+#endif
+
+
+static int JimExprOpIntBin(Jim_Interp *interp, struct JimExprNode *node)
+{
+ jim_wide wA, wB;
+ int rc;
+ Jim_Obj *A, *B;
+
+ if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
+ return rc;
+ }
+ if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
+ Jim_DecrRefCount(interp, A);
+ return rc;
+ }
+
+ rc = JIM_ERR;
+
+ if (Jim_GetWide(interp, A, &wA) == JIM_OK && Jim_GetWide(interp, B, &wB) == JIM_OK) {
+ jim_wide wC;
+
+ rc = JIM_OK;
+
+ switch (node->type) {
+ case JIM_EXPROP_LSHIFT:
+ wC = wA << wB;
+ break;
+ case JIM_EXPROP_RSHIFT:
+ wC = wA >> wB;
+ break;
+ case JIM_EXPROP_BITAND:
+ wC = wA & wB;
+ break;
+ case JIM_EXPROP_BITXOR:
+ wC = wA ^ wB;
+ break;
+ case JIM_EXPROP_BITOR:
+ wC = wA | wB;
+ break;
+ case JIM_EXPROP_MOD:
+ if (wB == 0) {
+ wC = 0;
+ Jim_SetResultString(interp, "Division by zero", -1);
+ rc = JIM_ERR;
+ }
+ else {
+ int negative = 0;
+
+ if (wB < 0) {
+ wB = -wB;
+ wA = -wA;
+ negative = 1;
+ }
+ wC = wA % wB;
+ if (wC < 0) {
+ wC += wB;
+ }
+ if (negative) {
+ wC = -wC;
+ }
+ }
+ break;
+ case JIM_EXPROP_ROTL:
+ case JIM_EXPROP_ROTR:{
+
+ unsigned long uA = (unsigned long)wA;
+ unsigned long uB = (unsigned long)wB;
+ const unsigned int S = sizeof(unsigned long) * 8;
+
+
+ uB %= S;
+
+ if (node->type == JIM_EXPROP_ROTR) {
+ uB = S - uB;
+ }
+ wC = (unsigned long)(uA << uB) | (uA >> (S - uB));
+ break;
+ }
+ default:
+ abort();
+ }
+ Jim_SetResultInt(interp, wC);
+ }
+
+ Jim_DecrRefCount(interp, A);
+ Jim_DecrRefCount(interp, B);
+
+ return rc;
+}
+
+
+
+static int JimExprOpBin(Jim_Interp *interp, struct JimExprNode *node)
+{
+ int rc = JIM_OK;
+ double dA, dB, dC = 0;
+ jim_wide wA, wB, wC = 0;
+ Jim_Obj *A, *B;
+
+ if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
+ return rc;
+ }
+ if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
+ Jim_DecrRefCount(interp, A);
+ return rc;
+ }
+
+ if ((A->typePtr != &doubleObjType || A->bytes) &&
+ (B->typePtr != &doubleObjType || B->bytes) &&
+ JimGetWideNoErr(interp, A, &wA) == JIM_OK && JimGetWideNoErr(interp, B, &wB) == JIM_OK) {
+
+
+
+ switch (node->type) {
+ case JIM_EXPROP_POW:
+ case JIM_EXPROP_FUNC_POW:
+ if (wA == 0 && wB < 0) {
+ Jim_SetResultString(interp, "exponentiation of zero by negative power", -1);
+ rc = JIM_ERR;
+ goto done;
+ }
+ wC = JimPowWide(wA, wB);
+ goto intresult;
+ case JIM_EXPROP_ADD:
+ wC = wA + wB;
+ goto intresult;
+ case JIM_EXPROP_SUB:
+ wC = wA - wB;
+ goto intresult;
+ case JIM_EXPROP_MUL:
+ wC = wA * wB;
+ goto intresult;
+ case JIM_EXPROP_DIV:
+ if (wB == 0) {
+ Jim_SetResultString(interp, "Division by zero", -1);
+ rc = JIM_ERR;
+ goto done;
+ }
+ else {
+ if (wB < 0) {
+ wB = -wB;
+ wA = -wA;
+ }
+ wC = wA / wB;
+ if (wA % wB < 0) {
+ wC--;
+ }
+ goto intresult;
+ }
+ case JIM_EXPROP_LT:
+ wC = wA < wB;
+ goto intresult;
+ case JIM_EXPROP_GT:
+ wC = wA > wB;
+ goto intresult;
+ case JIM_EXPROP_LTE:
+ wC = wA <= wB;
+ goto intresult;
+ case JIM_EXPROP_GTE:
+ wC = wA >= wB;
+ goto intresult;
+ case JIM_EXPROP_NUMEQ:
+ wC = wA == wB;
+ goto intresult;
+ case JIM_EXPROP_NUMNE:
+ wC = wA != wB;
+ goto intresult;
+ }
+ }
+ if (Jim_GetDouble(interp, A, &dA) == JIM_OK && Jim_GetDouble(interp, B, &dB) == JIM_OK) {
+ switch (node->type) {
+#ifndef JIM_MATH_FUNCTIONS
+ case JIM_EXPROP_POW:
+ case JIM_EXPROP_FUNC_POW:
+ case JIM_EXPROP_FUNC_ATAN2:
+ case JIM_EXPROP_FUNC_HYPOT:
+ case JIM_EXPROP_FUNC_FMOD:
+ Jim_SetResultString(interp, "unsupported", -1);
+ rc = JIM_ERR;
+ goto done;
+#else
+ case JIM_EXPROP_POW:
+ case JIM_EXPROP_FUNC_POW:
+ dC = pow(dA, dB);
+ goto doubleresult;
+ case JIM_EXPROP_FUNC_ATAN2:
+ dC = atan2(dA, dB);
+ goto doubleresult;
+ case JIM_EXPROP_FUNC_HYPOT:
+ dC = hypot(dA, dB);
+ goto doubleresult;
+ case JIM_EXPROP_FUNC_FMOD:
+ dC = fmod(dA, dB);
+ goto doubleresult;
+#endif
+ case JIM_EXPROP_ADD:
+ dC = dA + dB;
+ goto doubleresult;
+ case JIM_EXPROP_SUB:
+ dC = dA - dB;
+ goto doubleresult;
+ case JIM_EXPROP_MUL:
+ dC = dA * dB;
+ goto doubleresult;
+ case JIM_EXPROP_DIV:
+ if (dB == 0) {
+#ifdef INFINITY
+ dC = dA < 0 ? -INFINITY : INFINITY;
+#else
+ dC = (dA < 0 ? -1.0 : 1.0) * strtod("Inf", NULL);
+#endif
+ }
+ else {
+ dC = dA / dB;
+ }
+ goto doubleresult;
+ case JIM_EXPROP_LT:
+ wC = dA < dB;
+ goto intresult;
+ case JIM_EXPROP_GT:
+ wC = dA > dB;
+ goto intresult;
+ case JIM_EXPROP_LTE:
+ wC = dA <= dB;
+ goto intresult;
+ case JIM_EXPROP_GTE:
+ wC = dA >= dB;
+ goto intresult;
+ case JIM_EXPROP_NUMEQ:
+ wC = dA == dB;
+ goto intresult;
+ case JIM_EXPROP_NUMNE:
+ wC = dA != dB;
+ goto intresult;
+ }
+ }
+ else {
+
+
+
+ int i = Jim_StringCompareObj(interp, A, B, 0);
+
+ switch (node->type) {
+ case JIM_EXPROP_LT:
+ wC = i < 0;
+ goto intresult;
+ case JIM_EXPROP_GT:
+ wC = i > 0;
+ goto intresult;
+ case JIM_EXPROP_LTE:
+ wC = i <= 0;
+ goto intresult;
+ case JIM_EXPROP_GTE:
+ wC = i >= 0;
+ goto intresult;
+ case JIM_EXPROP_NUMEQ:
+ wC = i == 0;
+ goto intresult;
+ case JIM_EXPROP_NUMNE:
+ wC = i != 0;
+ goto intresult;
+ }
+ }
+
+ rc = JIM_ERR;
+done:
+ Jim_DecrRefCount(interp, A);
+ Jim_DecrRefCount(interp, B);
+ return rc;
+intresult:
+ Jim_SetResultInt(interp, wC);
+ goto done;
+doubleresult:
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, dC));
+ goto done;
+}
+
+static int JimSearchList(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *valObj)
+{
+ int listlen;
+ int i;
+
+ listlen = Jim_ListLength(interp, listObjPtr);
+ for (i = 0; i < listlen; i++) {
+ if (Jim_StringEqObj(Jim_ListGetIndex(interp, listObjPtr, i), valObj)) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+
+
+static int JimExprOpStrBin(Jim_Interp *interp, struct JimExprNode *node)
+{
+ Jim_Obj *A, *B;
+ jim_wide wC;
+ int rc;
+
+ if ((rc = JimExprGetTerm(interp, node->left, &A)) != JIM_OK) {
+ return rc;
+ }
+ if ((rc = JimExprGetTerm(interp, node->right, &B)) != JIM_OK) {
+ Jim_DecrRefCount(interp, A);
+ return rc;
+ }
+
+ switch (node->type) {
+ case JIM_EXPROP_STREQ:
+ case JIM_EXPROP_STRNE:
+ wC = Jim_StringEqObj(A, B);
+ if (node->type == JIM_EXPROP_STRNE) {
+ wC = !wC;
+ }
+ break;
+ case JIM_EXPROP_STRIN:
+ wC = JimSearchList(interp, B, A);
+ break;
+ case JIM_EXPROP_STRNI:
+ wC = !JimSearchList(interp, B, A);
+ break;
+ default:
+ abort();
+ }
+ Jim_SetResultInt(interp, wC);
+
+ Jim_DecrRefCount(interp, A);
+ Jim_DecrRefCount(interp, B);
+
+ return rc;
+}
+
+static int ExprBool(Jim_Interp *interp, Jim_Obj *obj)
+{
+ long l;
+ double d;
+ int b;
+ int ret = -1;
+
+
+ Jim_IncrRefCount(obj);
+
+ if (Jim_GetLong(interp, obj, &l) == JIM_OK) {
+ ret = (l != 0);
+ }
+ else if (Jim_GetDouble(interp, obj, &d) == JIM_OK) {
+ ret = (d != 0);
+ }
+ else if (Jim_GetBoolean(interp, obj, &b) == JIM_OK) {
+ ret = (b != 0);
+ }
+
+ Jim_DecrRefCount(interp, obj);
+ return ret;
+}
+
+static int JimExprOpAnd(Jim_Interp *interp, struct JimExprNode *node)
+{
+
+ int result = JimExprGetTermBoolean(interp, node->left);
+
+ if (result == 1) {
+
+ result = JimExprGetTermBoolean(interp, node->right);
+ }
+ if (result == -1) {
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, result);
+ return JIM_OK;
+}
+
+static int JimExprOpOr(Jim_Interp *interp, struct JimExprNode *node)
+{
+
+ int result = JimExprGetTermBoolean(interp, node->left);
+
+ if (result == 0) {
+
+ result = JimExprGetTermBoolean(interp, node->right);
+ }
+ if (result == -1) {
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, result);
+ return JIM_OK;
+}
+
+static int JimExprOpTernary(Jim_Interp *interp, struct JimExprNode *node)
+{
+
+ int result = JimExprGetTermBoolean(interp, node->left);
+
+ if (result == 1) {
+
+ return JimExprEvalTermNode(interp, node->right);
+ }
+ else if (result == 0) {
+
+ return JimExprEvalTermNode(interp, node->ternary);
+ }
+
+ return JIM_ERR;
+}
+
+enum
+{
+ OP_FUNC = 0x0001,
+ OP_RIGHT_ASSOC = 0x0002,
+};
+
+#define OPRINIT_ATTR(N, P, ARITY, F, ATTR) {N, F, P, ARITY, ATTR, sizeof(N) - 1}
+#define OPRINIT(N, P, ARITY, F) OPRINIT_ATTR(N, P, ARITY, F, 0)
+
+static const struct Jim_ExprOperator Jim_ExprOperators[] = {
+ OPRINIT("*", 110, 2, JimExprOpBin),
+ OPRINIT("/", 110, 2, JimExprOpBin),
+ OPRINIT("%", 110, 2, JimExprOpIntBin),
+
+ OPRINIT("-", 100, 2, JimExprOpBin),
+ OPRINIT("+", 100, 2, JimExprOpBin),
+
+ OPRINIT("<<", 90, 2, JimExprOpIntBin),
+ OPRINIT(">>", 90, 2, JimExprOpIntBin),
+
+ OPRINIT("<<<", 90, 2, JimExprOpIntBin),
+ OPRINIT(">>>", 90, 2, JimExprOpIntBin),
+
+ OPRINIT("<", 80, 2, JimExprOpBin),
+ OPRINIT(">", 80, 2, JimExprOpBin),
+ OPRINIT("<=", 80, 2, JimExprOpBin),
+ OPRINIT(">=", 80, 2, JimExprOpBin),
+
+ OPRINIT("==", 70, 2, JimExprOpBin),
+ OPRINIT("!=", 70, 2, JimExprOpBin),
+
+ OPRINIT("&", 50, 2, JimExprOpIntBin),
+ OPRINIT("^", 49, 2, JimExprOpIntBin),
+ OPRINIT("|", 48, 2, JimExprOpIntBin),
+
+ OPRINIT("&&", 10, 2, JimExprOpAnd),
+ OPRINIT("||", 9, 2, JimExprOpOr),
+ OPRINIT_ATTR("?", 5, 3, JimExprOpTernary, OP_RIGHT_ASSOC),
+ OPRINIT_ATTR(":", 5, 3, NULL, OP_RIGHT_ASSOC),
+
+
+ OPRINIT_ATTR("**", 120, 2, JimExprOpBin, OP_RIGHT_ASSOC),
+
+ OPRINIT("eq", 60, 2, JimExprOpStrBin),
+ OPRINIT("ne", 60, 2, JimExprOpStrBin),
+
+ OPRINIT("in", 55, 2, JimExprOpStrBin),
+ OPRINIT("ni", 55, 2, JimExprOpStrBin),
+
+ OPRINIT_ATTR("!", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
+ OPRINIT_ATTR("~", 150, 1, JimExprOpIntUnary, OP_RIGHT_ASSOC),
+ OPRINIT_ATTR(" -", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
+ OPRINIT_ATTR(" +", 150, 1, JimExprOpNumUnary, OP_RIGHT_ASSOC),
+
+
+
+ OPRINIT_ATTR("int", 200, 1, JimExprOpNumUnary, OP_FUNC),
+ OPRINIT_ATTR("wide", 200, 1, JimExprOpNumUnary, OP_FUNC),
+ OPRINIT_ATTR("abs", 200, 1, JimExprOpNumUnary, OP_FUNC),
+ OPRINIT_ATTR("double", 200, 1, JimExprOpNumUnary, OP_FUNC),
+ OPRINIT_ATTR("round", 200, 1, JimExprOpNumUnary, OP_FUNC),
+ OPRINIT_ATTR("rand", 200, 0, JimExprOpNone, OP_FUNC),
+ OPRINIT_ATTR("srand", 200, 1, JimExprOpIntUnary, OP_FUNC),
+
+#ifdef JIM_MATH_FUNCTIONS
+ OPRINIT_ATTR("sin", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("cos", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("tan", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("asin", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("acos", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("atan", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("atan2", 200, 2, JimExprOpBin, OP_FUNC),
+ OPRINIT_ATTR("sinh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("cosh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("tanh", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("ceil", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("floor", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("exp", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("log", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("log10", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("sqrt", 200, 1, JimExprOpDoubleUnary, OP_FUNC),
+ OPRINIT_ATTR("pow", 200, 2, JimExprOpBin, OP_FUNC),
+ OPRINIT_ATTR("hypot", 200, 2, JimExprOpBin, OP_FUNC),
+ OPRINIT_ATTR("fmod", 200, 2, JimExprOpBin, OP_FUNC),
+#endif
+};
+#undef OPRINIT
+#undef OPRINIT_ATTR
+
+#define JIM_EXPR_OPERATORS_NUM \
+ (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
+
+static int JimParseExpression(struct JimParserCtx *pc)
+{
+
+ while (isspace(UCHAR(*pc->p)) || (*(pc->p) == '\\' && *(pc->p + 1) == '\n')) {
+ if (*pc->p == '\n') {
+ pc->linenr++;
+ }
+ pc->p++;
+ pc->len--;
+ }
+
+
+ pc->tline = pc->linenr;
+ pc->tstart = pc->p;
+
+ if (pc->len == 0) {
+ pc->tend = pc->p;
+ pc->tt = JIM_TT_EOL;
+ pc->eof = 1;
+ return JIM_OK;
+ }
+ switch (*(pc->p)) {
+ case '(':
+ pc->tt = JIM_TT_SUBEXPR_START;
+ goto singlechar;
+ case ')':
+ pc->tt = JIM_TT_SUBEXPR_END;
+ goto singlechar;
+ case ',':
+ pc->tt = JIM_TT_SUBEXPR_COMMA;
+singlechar:
+ pc->tend = pc->p;
+ pc->p++;
+ pc->len--;
+ break;
+ case '[':
+ return JimParseCmd(pc);
+ case '$':
+ if (JimParseVar(pc) == JIM_ERR)
+ return JimParseExprOperator(pc);
+ else {
+
+ if (pc->tt == JIM_TT_EXPRSUGAR) {
+ return JIM_ERR;
+ }
+ return JIM_OK;
+ }
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '.':
+ return JimParseExprNumber(pc);
+ case '"':
+ return JimParseQuote(pc);
+ case '{':
+ return JimParseBrace(pc);
+
+ case 'N':
+ case 'I':
+ case 'n':
+ case 'i':
+ if (JimParseExprIrrational(pc) == JIM_ERR)
+ if (JimParseExprBoolean(pc) == JIM_ERR)
+ return JimParseExprOperator(pc);
+ break;
+ case 't':
+ case 'f':
+ case 'o':
+ case 'y':
+ if (JimParseExprBoolean(pc) == JIM_ERR)
+ return JimParseExprOperator(pc);
+ break;
+ default:
+ return JimParseExprOperator(pc);
+ break;
+ }
+ return JIM_OK;
+}
+
+static int JimParseExprNumber(struct JimParserCtx *pc)
+{
+ char *end;
+
+
+ pc->tt = JIM_TT_EXPR_INT;
+
+ jim_strtoull(pc->p, (char **)&pc->p);
+
+ if (strchr("eENnIi.", *pc->p) || pc->p == pc->tstart) {
+ if (strtod(pc->tstart, &end)) { }
+ if (end == pc->tstart)
+ return JIM_ERR;
+ if (end > pc->p) {
+
+ pc->tt = JIM_TT_EXPR_DOUBLE;
+ pc->p = end;
+ }
+ }
+ pc->tend = pc->p - 1;
+ pc->len -= (pc->p - pc->tstart);
+ return JIM_OK;
+}
+
+static int JimParseExprIrrational(struct JimParserCtx *pc)
+{
+ const char *irrationals[] = { "NaN", "nan", "NAN", "Inf", "inf", "INF", NULL };
+ int i;
+
+ for (i = 0; irrationals[i]; i++) {
+ const char *irr = irrationals[i];
+
+ if (strncmp(irr, pc->p, 3) == 0) {
+ pc->p += 3;
+ pc->len -= 3;
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_EXPR_DOUBLE;
+ return JIM_OK;
+ }
+ }
+ return JIM_ERR;
+}
+
+static int JimParseExprBoolean(struct JimParserCtx *pc)
+{
+ const char *booleans[] = { "false", "no", "off", "true", "yes", "on", NULL };
+ const int lengths[] = { 5, 2, 3, 4, 3, 2, 0 };
+ int i;
+
+ for (i = 0; booleans[i]; i++) {
+ const char *boolean = booleans[i];
+ int length = lengths[i];
+
+ if (strncmp(boolean, pc->p, length) == 0) {
+ pc->p += length;
+ pc->len -= length;
+ pc->tend = pc->p - 1;
+ pc->tt = JIM_TT_EXPR_BOOLEAN;
+ return JIM_OK;
+ }
+ }
+ return JIM_ERR;
+}
+
+static const struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
+{
+ static Jim_ExprOperator dummy_op;
+ if (opcode < JIM_TT_EXPR_OP) {
+ return &dummy_op;
+ }
+ return &Jim_ExprOperators[opcode - JIM_TT_EXPR_OP];
+}
+
+static int JimParseExprOperator(struct JimParserCtx *pc)
+{
+ int i;
+ const struct Jim_ExprOperator *bestOp = NULL;
+ int bestLen = 0;
+
+
+ for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
+ const struct Jim_ExprOperator *op = &Jim_ExprOperators[i];
+
+ if (op->name[0] != pc->p[0]) {
+ continue;
+ }
+
+ if (op->namelen > bestLen && strncmp(op->name, pc->p, op->namelen) == 0) {
+ bestOp = op;
+ bestLen = op->namelen;
+ }
+ }
+ if (bestOp == NULL) {
+ return JIM_ERR;
+ }
+
+
+ if (bestOp->attr & OP_FUNC) {
+ const char *p = pc->p + bestLen;
+ int len = pc->len - bestLen;
+
+ while (len && isspace(UCHAR(*p))) {
+ len--;
+ p++;
+ }
+ if (*p != '(') {
+ return JIM_ERR;
+ }
+ }
+ pc->tend = pc->p + bestLen - 1;
+ pc->p += bestLen;
+ pc->len -= bestLen;
+
+ pc->tt = (bestOp - Jim_ExprOperators) + JIM_TT_EXPR_OP;
+ return JIM_OK;
+}
+
+const char *jim_tt_name(int type)
+{
+ static const char * const tt_names[JIM_TT_EXPR_OP] =
+ { "NIL", "STR", "ESC", "VAR", "ARY", "CMD", "SEP", "EOL", "EOF", "LIN", "WRD", "(((", ")))", ",,,", "INT",
+ "DBL", "BOO", "$()" };
+ if (type < JIM_TT_EXPR_OP) {
+ return tt_names[type];
+ }
+ else if (type == JIM_EXPROP_UNARYMINUS) {
+ return "-VE";
+ }
+ else if (type == JIM_EXPROP_UNARYPLUS) {
+ return "+VE";
+ }
+ else {
+ const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(type);
+ static char buf[20];
+
+ if (op->name) {
+ return op->name;
+ }
+ sprintf(buf, "(%d)", type);
+ return buf;
+ }
+}
+
+static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static const Jim_ObjType exprObjType = {
+ "expression",
+ FreeExprInternalRep,
+ DupExprInternalRep,
+ NULL,
+ JIM_TYPE_REFERENCES,
+};
+
+
+struct ExprTree
+{
+ struct JimExprNode *expr;
+ struct JimExprNode *nodes;
+ int len;
+ int inUse;
+};
+
+static void ExprTreeFreeNodes(Jim_Interp *interp, struct JimExprNode *nodes, int num)
+{
+ int i;
+ for (i = 0; i < num; i++) {
+ if (nodes[i].objPtr) {
+ Jim_DecrRefCount(interp, nodes[i].objPtr);
+ }
+ }
+ Jim_Free(nodes);
+}
+
+static void ExprTreeFree(Jim_Interp *interp, struct ExprTree *expr)
+{
+ ExprTreeFreeNodes(interp, expr->nodes, expr->len);
+ Jim_Free(expr);
+}
+
+static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ struct ExprTree *expr = (void *)objPtr->internalRep.ptr;
+
+ if (expr) {
+ if (--expr->inUse != 0) {
+ return;
+ }
+
+ ExprTreeFree(interp, expr);
+ }
+}
+
+static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ JIM_NOTUSED(interp);
+ JIM_NOTUSED(srcPtr);
+
+
+ dupPtr->typePtr = NULL;
+}
+
+struct ExprBuilder {
+ int parencount;
+ int level;
+ ParseToken *token;
+ ParseToken *first_token;
+ Jim_Stack stack;
+ Jim_Obj *exprObjPtr;
+ Jim_Obj *fileNameObj;
+ struct JimExprNode *nodes;
+ struct JimExprNode *next;
+};
+
+#ifdef DEBUG_SHOW_EXPR
+static void JimShowExprNode(struct JimExprNode *node, int level)
+{
+ int i;
+ for (i = 0; i < level; i++) {
+ printf(" ");
+ }
+ if (TOKEN_IS_EXPR_OP(node->type)) {
+ printf("%s\n", jim_tt_name(node->type));
+ if (node->left) {
+ JimShowExprNode(node->left, level + 1);
+ }
+ if (node->right) {
+ JimShowExprNode(node->right, level + 1);
+ }
+ if (node->ternary) {
+ JimShowExprNode(node->ternary, level + 1);
+ }
+ }
+ else {
+ printf("[%s] %s\n", jim_tt_name(node->type), Jim_String(node->objPtr));
+ }
+}
+#endif
+
+#define EXPR_UNTIL_CLOSE 0x0001
+#define EXPR_FUNC_ARGS 0x0002
+#define EXPR_TERNARY 0x0004
+
+static int ExprTreeBuildTree(Jim_Interp *interp, struct ExprBuilder *builder, int precedence, int flags, int exp_numterms)
+{
+ int rc;
+ struct JimExprNode *node;
+
+ int exp_stacklen = builder->stack.len + exp_numterms;
+
+ if (builder->level++ > 200) {
+ Jim_SetResultString(interp, "Expression too complex", -1);
+ return JIM_ERR;
+ }
+
+ while (builder->token->type != JIM_TT_EOL) {
+ ParseToken *t = builder->token++;
+ int prevtt;
+
+ if (t == builder->first_token) {
+ prevtt = JIM_TT_NONE;
+ }
+ else {
+ prevtt = t[-1].type;
+ }
+
+ if (t->type == JIM_TT_SUBEXPR_START) {
+ if (builder->stack.len == exp_stacklen) {
+ Jim_SetResultFormatted(interp, "unexpected open parenthesis in expression: \"%#s\"", builder->exprObjPtr);
+ return JIM_ERR;
+ }
+ builder->parencount++;
+ rc = ExprTreeBuildTree(interp, builder, 0, EXPR_UNTIL_CLOSE, 1);
+ if (rc != JIM_OK) {
+ return rc;
+ }
+
+ }
+ else if (t->type == JIM_TT_SUBEXPR_END) {
+ if (!(flags & EXPR_UNTIL_CLOSE)) {
+ if (builder->stack.len == exp_stacklen && builder->level > 1) {
+ builder->token--;
+ builder->level--;
+ return JIM_OK;
+ }
+ Jim_SetResultFormatted(interp, "unexpected closing parenthesis in expression: \"%#s\"", builder->exprObjPtr);
+ return JIM_ERR;
+ }
+ builder->parencount--;
+ if (builder->stack.len == exp_stacklen) {
+
+ break;
+ }
+ }
+ else if (t->type == JIM_TT_SUBEXPR_COMMA) {
+ if (!(flags & EXPR_FUNC_ARGS)) {
+ if (builder->stack.len == exp_stacklen) {
+
+ builder->token--;
+ builder->level--;
+ return JIM_OK;
+ }
+ Jim_SetResultFormatted(interp, "unexpected comma in expression: \"%#s\"", builder->exprObjPtr);
+ return JIM_ERR;
+ }
+ else {
+
+ if (builder->stack.len > exp_stacklen) {
+ Jim_SetResultFormatted(interp, "too many arguments to math function");
+ return JIM_ERR;
+ }
+ }
+
+ }
+ else if (t->type == JIM_EXPROP_COLON) {
+ if (!(flags & EXPR_TERNARY)) {
+ if (builder->level != 1) {
+
+ builder->token--;
+ builder->level--;
+ return JIM_OK;
+ }
+ Jim_SetResultFormatted(interp, ": without ? in expression: \"%#s\"", builder->exprObjPtr);
+ return JIM_ERR;
+ }
+ if (builder->stack.len == exp_stacklen) {
+
+ builder->token--;
+ builder->level--;
+ return JIM_OK;
+ }
+
+ }
+ else if (TOKEN_IS_EXPR_OP(t->type)) {
+ const struct Jim_ExprOperator *op;
+
+
+ if (TOKEN_IS_EXPR_OP(prevtt) || TOKEN_IS_EXPR_START(prevtt)) {
+ if (t->type == JIM_EXPROP_SUB) {
+ t->type = JIM_EXPROP_UNARYMINUS;
+ }
+ else if (t->type == JIM_EXPROP_ADD) {
+ t->type = JIM_EXPROP_UNARYPLUS;
+ }
+ }
+
+ op = JimExprOperatorInfoByOpcode(t->type);
+
+ if (op->precedence < precedence || (!(op->attr & OP_RIGHT_ASSOC) && op->precedence == precedence)) {
+
+ builder->token--;
+ break;
+ }
+
+ if (op->attr & OP_FUNC) {
+ if (builder->token->type != JIM_TT_SUBEXPR_START) {
+ Jim_SetResultString(interp, "missing arguments for math function", -1);
+ return JIM_ERR;
+ }
+ builder->token++;
+ if (op->arity == 0) {
+ if (builder->token->type != JIM_TT_SUBEXPR_END) {
+ Jim_SetResultString(interp, "too many arguments for math function", -1);
+ return JIM_ERR;
+ }
+ builder->token++;
+ goto noargs;
+ }
+ builder->parencount++;
+
+
+ rc = ExprTreeBuildTree(interp, builder, 0, EXPR_FUNC_ARGS | EXPR_UNTIL_CLOSE, op->arity);
+ }
+ else if (t->type == JIM_EXPROP_TERNARY) {
+
+ rc = ExprTreeBuildTree(interp, builder, op->precedence, EXPR_TERNARY, 2);
+ }
+ else {
+ rc = ExprTreeBuildTree(interp, builder, op->precedence, 0, 1);
+ }
+
+ if (rc != JIM_OK) {
+ return rc;
+ }
+
+noargs:
+ node = builder->next++;
+ node->type = t->type;
+
+ if (op->arity >= 3) {
+ node->ternary = Jim_StackPop(&builder->stack);
+ if (node->ternary == NULL) {
+ goto missingoperand;
+ }
+ }
+ if (op->arity >= 2) {
+ node->right = Jim_StackPop(&builder->stack);
+ if (node->right == NULL) {
+ goto missingoperand;
+ }
+ }
+ if (op->arity >= 1) {
+ node->left = Jim_StackPop(&builder->stack);
+ if (node->left == NULL) {
+missingoperand:
+ Jim_SetResultFormatted(interp, "missing operand to %s in expression: \"%#s\"", op->name, builder->exprObjPtr);
+ builder->next--;
+ return JIM_ERR;
+
+ }
+ }
+
+
+ Jim_StackPush(&builder->stack, node);
+ }
+ else {
+ Jim_Obj *objPtr = NULL;
+
+
+
+
+ if (!TOKEN_IS_EXPR_START(prevtt) && !TOKEN_IS_EXPR_OP(prevtt)) {
+ Jim_SetResultFormatted(interp, "missing operator in expression: \"%#s\"", builder->exprObjPtr);
+ return JIM_ERR;
+ }
+
+
+ if (t->type == JIM_TT_EXPR_INT || t->type == JIM_TT_EXPR_DOUBLE) {
+ char *endptr;
+ if (t->type == JIM_TT_EXPR_INT) {
+ objPtr = Jim_NewIntObj(interp, jim_strtoull(t->token, &endptr));
+ }
+ else {
+ objPtr = Jim_NewDoubleObj(interp, strtod(t->token, &endptr));
+ }
+ if (endptr != t->token + t->len) {
+
+ Jim_FreeNewObj(interp, objPtr);
+ objPtr = NULL;
+ }
+ }
+
+ if (!objPtr) {
+
+ objPtr = Jim_NewStringObj(interp, t->token, t->len);
+ if (t->type == JIM_TT_CMD) {
+
+ JimSetSourceInfo(interp, objPtr, builder->fileNameObj, t->line);
+ }
+ }
+
+
+ node = builder->next++;
+ node->objPtr = objPtr;
+ Jim_IncrRefCount(node->objPtr);
+ node->type = t->type;
+ Jim_StackPush(&builder->stack, node);
+ }
+ }
+
+ if (builder->stack.len == exp_stacklen) {
+ builder->level--;
+ return JIM_OK;
+ }
+
+ if ((flags & EXPR_FUNC_ARGS)) {
+ Jim_SetResultFormatted(interp, "too %s arguments for math function", (builder->stack.len < exp_stacklen) ? "few" : "many");
+ }
+ else {
+ if (builder->stack.len < exp_stacklen) {
+ if (builder->level == 0) {
+ Jim_SetResultFormatted(interp, "empty expression");
+ }
+ else {
+ Jim_SetResultFormatted(interp, "syntax error in expression \"%#s\": premature end of expression", builder->exprObjPtr);
+ }
+ }
+ else {
+ Jim_SetResultFormatted(interp, "extra terms after expression");
+ }
+ }
+
+ return JIM_ERR;
+}
+
+static struct ExprTree *ExprTreeCreateTree(Jim_Interp *interp, const ParseTokenList *tokenlist, Jim_Obj *exprObjPtr, Jim_Obj *fileNameObj)
+{
+ struct ExprTree *expr;
+ struct ExprBuilder builder;
+ int rc;
+ struct JimExprNode *top = NULL;
+
+ builder.parencount = 0;
+ builder.level = 0;
+ builder.token = builder.first_token = tokenlist->list;
+ builder.exprObjPtr = exprObjPtr;
+ builder.fileNameObj = fileNameObj;
+
+ builder.nodes = malloc(sizeof(struct JimExprNode) * (tokenlist->count - 1));
+ memset(builder.nodes, 0, sizeof(struct JimExprNode) * (tokenlist->count - 1));
+ builder.next = builder.nodes;
+ Jim_InitStack(&builder.stack);
+
+ rc = ExprTreeBuildTree(interp, &builder, 0, 0, 1);
+
+ if (rc == JIM_OK) {
+ top = Jim_StackPop(&builder.stack);
+
+ if (builder.parencount) {
+ Jim_SetResultString(interp, "missing close parenthesis", -1);
+ rc = JIM_ERR;
+ }
+ }
+
+
+ Jim_FreeStack(&builder.stack);
+
+ if (rc != JIM_OK) {
+ ExprTreeFreeNodes(interp, builder.nodes, builder.next - builder.nodes);
+ return NULL;
+ }
+
+ expr = Jim_Alloc(sizeof(*expr));
+ expr->inUse = 1;
+ expr->expr = top;
+ expr->nodes = builder.nodes;
+ expr->len = builder.next - builder.nodes;
+
+ assert(expr->len <= tokenlist->count - 1);
+
+ return expr;
+}
+
+static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+ int exprTextLen;
+ const char *exprText;
+ struct JimParserCtx parser;
+ struct ExprTree *expr;
+ ParseTokenList tokenlist;
+ int line;
+ Jim_Obj *fileNameObj;
+ int rc = JIM_ERR;
+
+
+ if (objPtr->typePtr == &sourceObjType) {
+ fileNameObj = objPtr->internalRep.sourceValue.fileNameObj;
+ line = objPtr->internalRep.sourceValue.lineNumber;
+ }
+ else {
+ fileNameObj = interp->emptyObj;
+ line = 1;
+ }
+ Jim_IncrRefCount(fileNameObj);
+
+ exprText = Jim_GetString(objPtr, &exprTextLen);
+
+
+ ScriptTokenListInit(&tokenlist);
+
+ JimParserInit(&parser, exprText, exprTextLen, line);
+ while (!parser.eof) {
+ if (JimParseExpression(&parser) != JIM_OK) {
+ ScriptTokenListFree(&tokenlist);
+ Jim_SetResultFormatted(interp, "syntax error in expression: \"%#s\"", objPtr);
+ expr = NULL;
+ goto err;
+ }
+
+ ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
+ parser.tline);
+ }
+
+#ifdef DEBUG_SHOW_EXPR_TOKENS
+ {
+ int i;
+ printf("==== Expr Tokens (%s) ====\n", Jim_String(fileNameObj));
+ for (i = 0; i < tokenlist.count; i++) {
+ printf("[%2d]@%d %s '%.*s'\n", i, tokenlist.list[i].line, jim_tt_name(tokenlist.list[i].type),
+ tokenlist.list[i].len, tokenlist.list[i].token);
+ }
+ }
+#endif
+
+ if (JimParseCheckMissing(interp, parser.missing.ch) == JIM_ERR) {
+ ScriptTokenListFree(&tokenlist);
+ Jim_DecrRefCount(interp, fileNameObj);
+ return JIM_ERR;
+ }
+
+
+ expr = ExprTreeCreateTree(interp, &tokenlist, objPtr, fileNameObj);
+
+
+ ScriptTokenListFree(&tokenlist);
+
+ if (!expr) {
+ goto err;
+ }
+
+#ifdef DEBUG_SHOW_EXPR
+ printf("==== Expr ====\n");
+ JimShowExprNode(expr->expr, 0);
+#endif
+
+ rc = JIM_OK;
+
+ err:
+
+ Jim_DecrRefCount(interp, fileNameObj);
+ Jim_FreeIntRep(interp, objPtr);
+ Jim_SetIntRepPtr(objPtr, expr);
+ objPtr->typePtr = &exprObjType;
+ return rc;
+}
+
+static struct ExprTree *JimGetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ if (objPtr->typePtr != &exprObjType) {
+ if (SetExprFromAny(interp, objPtr) != JIM_OK) {
+ return NULL;
+ }
+ }
+ return (struct ExprTree *) Jim_GetIntRepPtr(objPtr);
+}
+
+#ifdef JIM_OPTIMIZATION
+static Jim_Obj *JimExprIntValOrVar(Jim_Interp *interp, struct JimExprNode *node)
+{
+ if (node->type == JIM_TT_EXPR_INT)
+ return node->objPtr;
+ else if (node->type == JIM_TT_VAR)
+ return Jim_GetVariable(interp, node->objPtr, JIM_NONE);
+ else if (node->type == JIM_TT_DICTSUGAR)
+ return JimExpandDictSugar(interp, node->objPtr);
+ else
+ return NULL;
+}
+#endif
+
+
+static int JimExprEvalTermNode(Jim_Interp *interp, struct JimExprNode *node)
+{
+ if (TOKEN_IS_EXPR_OP(node->type)) {
+ const struct Jim_ExprOperator *op = JimExprOperatorInfoByOpcode(node->type);
+ return op->funcop(interp, node);
+ }
+ else {
+ Jim_Obj *objPtr;
+
+
+ switch (node->type) {
+ case JIM_TT_EXPR_INT:
+ case JIM_TT_EXPR_DOUBLE:
+ case JIM_TT_EXPR_BOOLEAN:
+ case JIM_TT_STR:
+ Jim_SetResult(interp, node->objPtr);
+ return JIM_OK;
+
+ case JIM_TT_VAR:
+ objPtr = Jim_GetVariable(interp, node->objPtr, JIM_ERRMSG);
+ if (objPtr) {
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+ return JIM_ERR;
+
+ case JIM_TT_DICTSUGAR:
+ objPtr = JimExpandDictSugar(interp, node->objPtr);
+ if (objPtr) {
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+ return JIM_ERR;
+
+ case JIM_TT_ESC:
+ if (Jim_SubstObj(interp, node->objPtr, &objPtr, JIM_NONE) == JIM_OK) {
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+ return JIM_ERR;
+
+ case JIM_TT_CMD:
+ return Jim_EvalObj(interp, node->objPtr);
+
+ default:
+
+ return JIM_ERR;
+ }
+ }
+}
+
+static int JimExprGetTerm(Jim_Interp *interp, struct JimExprNode *node, Jim_Obj **objPtrPtr)
+{
+ int rc = JimExprEvalTermNode(interp, node);
+ if (rc == JIM_OK) {
+ *objPtrPtr = Jim_GetResult(interp);
+ Jim_IncrRefCount(*objPtrPtr);
+ }
+ return rc;
+}
+
+static int JimExprGetTermBoolean(Jim_Interp *interp, struct JimExprNode *node)
+{
+ if (JimExprEvalTermNode(interp, node) == JIM_OK) {
+ return ExprBool(interp, Jim_GetResult(interp));
+ }
+ return -1;
+}
+
+int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr)
+{
+ struct ExprTree *expr;
+ int retcode = JIM_OK;
+
+ expr = JimGetExpression(interp, exprObjPtr);
+ if (!expr) {
+ return JIM_ERR;
+ }
+
+#ifdef JIM_OPTIMIZATION
+ {
+ Jim_Obj *objPtr;
+
+
+ switch (expr->len) {
+ case 1:
+ objPtr = JimExprIntValOrVar(interp, expr->expr);
+ if (objPtr) {
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+ break;
+
+ case 2:
+ if (expr->expr->type == JIM_EXPROP_NOT) {
+ objPtr = JimExprIntValOrVar(interp, expr->expr->left);
+
+ if (objPtr && JimIsWide(objPtr)) {
+ Jim_SetResult(interp, JimWideValue(objPtr) ? interp->falseObj : interp->trueObj);
+ return JIM_OK;
+ }
+ }
+ break;
+
+ case 3:
+ objPtr = JimExprIntValOrVar(interp, expr->expr->left);
+ if (objPtr && JimIsWide(objPtr)) {
+ Jim_Obj *objPtr2 = JimExprIntValOrVar(interp, expr->expr->right);
+ if (objPtr2 && JimIsWide(objPtr2)) {
+ jim_wide wideValueA = JimWideValue(objPtr);
+ jim_wide wideValueB = JimWideValue(objPtr2);
+ int cmpRes;
+ switch (expr->expr->type) {
+ case JIM_EXPROP_LT:
+ cmpRes = wideValueA < wideValueB;
+ break;
+ case JIM_EXPROP_LTE:
+ cmpRes = wideValueA <= wideValueB;
+ break;
+ case JIM_EXPROP_GT:
+ cmpRes = wideValueA > wideValueB;
+ break;
+ case JIM_EXPROP_GTE:
+ cmpRes = wideValueA >= wideValueB;
+ break;
+ case JIM_EXPROP_NUMEQ:
+ cmpRes = wideValueA == wideValueB;
+ break;
+ case JIM_EXPROP_NUMNE:
+ cmpRes = wideValueA != wideValueB;
+ break;
+ default:
+ goto noopt;
+ }
+ Jim_SetResult(interp, cmpRes ? interp->trueObj : interp->falseObj);
+ return JIM_OK;
+ }
+ }
+ break;
+ }
+ }
+noopt:
+#endif
+
+ expr->inUse++;
+
+
+ retcode = JimExprEvalTermNode(interp, expr->expr);
+
+ expr->inUse--;
+
+ return retcode;
+}
+
+int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
+{
+ int retcode = Jim_EvalExpression(interp, exprObjPtr);
+
+ if (retcode == JIM_OK) {
+ switch (ExprBool(interp, Jim_GetResult(interp))) {
+ case 0:
+ *boolPtr = 0;
+ break;
+
+ case 1:
+ *boolPtr = 1;
+ break;
+
+ case -1:
+ retcode = JIM_ERR;
+ break;
+ }
+ }
+ return retcode;
+}
+
+
+
+
+typedef struct ScanFmtPartDescr
+{
+ const char *arg;
+ const char *prefix;
+ size_t width;
+ int pos;
+ char type;
+ char modifier;
+} ScanFmtPartDescr;
+
+
+typedef struct ScanFmtStringObj
+{
+ jim_wide size;
+ char *stringRep;
+ size_t count;
+ size_t convCount;
+ size_t maxPos;
+ const char *error;
+ char *scratch;
+ ScanFmtPartDescr descr[1];
+} ScanFmtStringObj;
+
+
+static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
+
+static const Jim_ObjType scanFmtStringObjType = {
+ "scanformatstring",
+ FreeScanFmtInternalRep,
+ DupScanFmtInternalRep,
+ UpdateStringOfScanFmt,
+ JIM_TYPE_NONE,
+};
+
+void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ JIM_NOTUSED(interp);
+ Jim_Free((char *)objPtr->internalRep.ptr);
+ objPtr->internalRep.ptr = 0;
+}
+
+void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+ size_t size = (size_t) ((ScanFmtStringObj *) srcPtr->internalRep.ptr)->size;
+ ScanFmtStringObj *newVec = (ScanFmtStringObj *) Jim_Alloc(size);
+
+ JIM_NOTUSED(interp);
+ memcpy(newVec, srcPtr->internalRep.ptr, size);
+ dupPtr->internalRep.ptr = newVec;
+ dupPtr->typePtr = &scanFmtStringObjType;
+}
+
+static void UpdateStringOfScanFmt(Jim_Obj *objPtr)
+{
+ JimSetStringBytes(objPtr, ((ScanFmtStringObj *) objPtr->internalRep.ptr)->stringRep);
+}
+
+
+static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ ScanFmtStringObj *fmtObj;
+ char *buffer;
+ int maxCount, i, approxSize, lastPos = -1;
+ const char *fmt = Jim_String(objPtr);
+ int maxFmtLen = Jim_Length(objPtr);
+ const char *fmtEnd = fmt + maxFmtLen;
+ int curr;
+
+ Jim_FreeIntRep(interp, objPtr);
+
+ for (i = 0, maxCount = 0; i < maxFmtLen; ++i)
+ if (fmt[i] == '%')
+ ++maxCount;
+
+ approxSize = sizeof(ScanFmtStringObj)
+ +(maxCount + 1) * sizeof(ScanFmtPartDescr)
+ +maxFmtLen * sizeof(char) + 3 + 1
+ + maxFmtLen * sizeof(char) + 1
+ + maxFmtLen * sizeof(char)
+ +(maxCount + 1) * sizeof(char)
+ +1;
+ fmtObj = (ScanFmtStringObj *) Jim_Alloc(approxSize);
+ memset(fmtObj, 0, approxSize);
+ fmtObj->size = approxSize;
+ fmtObj->maxPos = 0;
+ fmtObj->scratch = (char *)&fmtObj->descr[maxCount + 1];
+ fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
+ memcpy(fmtObj->stringRep, fmt, maxFmtLen);
+ buffer = fmtObj->stringRep + maxFmtLen + 1;
+ objPtr->internalRep.ptr = fmtObj;
+ objPtr->typePtr = &scanFmtStringObjType;
+ for (i = 0, curr = 0; fmt < fmtEnd; ++fmt) {
+ int width = 0, skip;
+ ScanFmtPartDescr *descr = &fmtObj->descr[curr];
+
+ fmtObj->count++;
+ descr->width = 0;
+
+ if (*fmt != '%' || fmt[1] == '%') {
+ descr->type = 0;
+ descr->prefix = &buffer[i];
+ for (; fmt < fmtEnd; ++fmt) {
+ if (*fmt == '%') {
+ if (fmt[1] != '%')
+ break;
+ ++fmt;
+ }
+ buffer[i++] = *fmt;
+ }
+ buffer[i++] = 0;
+ }
+
+ ++fmt;
+
+ if (fmt >= fmtEnd)
+ goto done;
+ descr->pos = 0;
+ if (*fmt == '*') {
+ descr->pos = -1;
+ ++fmt;
+ }
+ else
+ fmtObj->convCount++;
+
+ if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
+ fmt += skip;
+
+ if (descr->pos != -1 && *fmt == '$') {
+ int prev;
+
+ ++fmt;
+ descr->pos = width;
+ width = 0;
+
+ if ((lastPos == 0 && descr->pos > 0)
+ || (lastPos > 0 && descr->pos == 0)) {
+ fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
+ return JIM_ERR;
+ }
+
+ for (prev = 0; prev < curr; ++prev) {
+ if (fmtObj->descr[prev].pos == -1)
+ continue;
+ if (fmtObj->descr[prev].pos == descr->pos) {
+ fmtObj->error =
+ "variable is assigned by multiple \"%n$\" conversion specifiers";
+ return JIM_ERR;
+ }
+ }
+ if (descr->pos < 0) {
+ fmtObj->error =
+ "\"%n$\" conversion specifier is negative";
+ return JIM_ERR;
+ }
+
+ if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
+ descr->width = width;
+ fmt += skip;
+ }
+ if (descr->pos > 0 && (size_t) descr->pos > fmtObj->maxPos)
+ fmtObj->maxPos = descr->pos;
+ }
+ else {
+
+ descr->width = width;
+ }
+ }
+
+ if (lastPos == -1)
+ lastPos = descr->pos;
+
+ if (*fmt == '[') {
+ int swapped = 1, beg = i, end, j;
+
+ descr->type = '[';
+ descr->arg = &buffer[i];
+ ++fmt;
+ if (*fmt == '^')
+ buffer[i++] = *fmt++;
+ if (*fmt == ']')
+ buffer[i++] = *fmt++;
+ while (*fmt && *fmt != ']')
+ buffer[i++] = *fmt++;
+ if (*fmt != ']') {
+ fmtObj->error = "unmatched [ in format string";
+ return JIM_ERR;
+ }
+ end = i;
+ buffer[i++] = 0;
+
+ while (swapped) {
+ swapped = 0;
+ for (j = beg + 1; j < end - 1; ++j) {
+ if (buffer[j] == '-' && buffer[j - 1] > buffer[j + 1]) {
+ char tmp = buffer[j - 1];
+
+ buffer[j - 1] = buffer[j + 1];
+ buffer[j + 1] = tmp;
+ swapped = 1;
+ }
+ }
+ }
+ }
+ else {
+
+ if (fmt < fmtEnd && strchr("hlL", *fmt))
+ descr->modifier = tolower((int)*fmt++);
+
+ if (fmt >= fmtEnd) {
+ fmtObj->error = "missing scan conversion character";
+ return JIM_ERR;
+ }
+
+ descr->type = *fmt;
+ if (strchr("efgcsndoxui", *fmt) == 0) {
+ fmtObj->error = "bad scan conversion character";
+ return JIM_ERR;
+ }
+ else if (*fmt == 'c' && descr->width != 0) {
+ fmtObj->error = "field width may not be specified in %c " "conversion";
+ return JIM_ERR;
+ }
+ else if (*fmt == 'u' && descr->modifier == 'l') {
+ fmtObj->error = "unsigned wide not supported";
+ return JIM_ERR;
+ }
+ }
+ curr++;
+ }
+ done:
+ return JIM_OK;
+}
+
+
+
+#define FormatGetCnvCount(_fo_) \
+ ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
+#define FormatGetMaxPos(_fo_) \
+ ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
+#define FormatGetError(_fo_) \
+ ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
+
+static Jim_Obj *JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
+{
+ char *buffer = Jim_StrDup(str);
+ char *p = buffer;
+
+ while (*str) {
+ int c;
+ int n;
+
+ if (!sdescr && isspace(UCHAR(*str)))
+ break;
+
+ n = utf8_tounicode(str, &c);
+ if (sdescr && !JimCharsetMatch(sdescr, c, JIM_CHARSET_SCAN))
+ break;
+ while (n--)
+ *p++ = *str++;
+ }
+ *p = 0;
+ return Jim_NewStringObjNoAlloc(interp, buffer, p - buffer);
+}
+
+
+static int ScanOneEntry(Jim_Interp *interp, const char *str, int pos, int strLen,
+ ScanFmtStringObj * fmtObj, long idx, Jim_Obj **valObjPtr)
+{
+ const char *tok;
+ const ScanFmtPartDescr *descr = &fmtObj->descr[idx];
+ size_t scanned = 0;
+ size_t anchor = pos;
+ int i;
+ Jim_Obj *tmpObj = NULL;
+
+
+ *valObjPtr = 0;
+ if (descr->prefix) {
+ for (i = 0; pos < strLen && descr->prefix[i]; ++i) {
+
+ if (isspace(UCHAR(descr->prefix[i])))
+ while (pos < strLen && isspace(UCHAR(str[pos])))
+ ++pos;
+ else if (descr->prefix[i] != str[pos])
+ break;
+ else
+ ++pos;
+ }
+ if (pos >= strLen) {
+ return -1;
+ }
+ else if (descr->prefix[i] != 0)
+ return 0;
+ }
+
+ if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
+ while (isspace(UCHAR(str[pos])))
+ ++pos;
+
+ scanned = pos - anchor;
+
+
+ if (descr->type == 'n') {
+
+ *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
+ }
+ else if (pos >= strLen) {
+
+ return -1;
+ }
+ else if (descr->type == 'c') {
+ int c;
+ scanned += utf8_tounicode(&str[pos], &c);
+ *valObjPtr = Jim_NewIntObj(interp, c);
+ return scanned;
+ }
+ else {
+
+ if (descr->width > 0) {
+ size_t sLen = utf8_strlen(&str[pos], strLen - pos);
+ size_t tLen = descr->width > sLen ? sLen : descr->width;
+
+ tmpObj = Jim_NewStringObjUtf8(interp, str + pos, tLen);
+ tok = tmpObj->bytes;
+ }
+ else {
+
+ tok = &str[pos];
+ }
+ switch (descr->type) {
+ case 'd':
+ case 'o':
+ case 'x':
+ case 'u':
+ case 'i':{
+ char *endp;
+ jim_wide w;
+
+ int base = descr->type == 'o' ? 8
+ : descr->type == 'x' ? 16 : descr->type == 'i' ? 0 : 10;
+
+
+ if (base == 0) {
+ w = jim_strtoull(tok, &endp);
+ }
+ else {
+ w = strtoull(tok, &endp, base);
+ }
+
+ if (endp != tok) {
+
+ *valObjPtr = Jim_NewIntObj(interp, w);
+
+
+ scanned += endp - tok;
+ }
+ else {
+ scanned = *tok ? 0 : -1;
+ }
+ break;
+ }
+ case 's':
+ case '[':{
+ *valObjPtr = JimScanAString(interp, descr->arg, tok);
+ scanned += Jim_Length(*valObjPtr);
+ break;
+ }
+ case 'e':
+ case 'f':
+ case 'g':{
+ char *endp;
+ double value = strtod(tok, &endp);
+
+ if (endp != tok) {
+
+ *valObjPtr = Jim_NewDoubleObj(interp, value);
+
+ scanned += endp - tok;
+ }
+ else {
+ scanned = *tok ? 0 : -1;
+ }
+ break;
+ }
+ }
+ if (tmpObj) {
+ Jim_FreeNewObj(interp, tmpObj);
+ }
+ }
+ return scanned;
+}
+
+
+Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr, Jim_Obj *fmtObjPtr, int flags)
+{
+ size_t i, pos;
+ int scanned = 1;
+ const char *str = Jim_String(strObjPtr);
+ int strLen = Jim_Utf8Length(interp, strObjPtr);
+ Jim_Obj *resultList = 0;
+ Jim_Obj **resultVec = 0;
+ int resultc;
+ Jim_Obj *emptyStr = 0;
+ ScanFmtStringObj *fmtObj;
+
+
+ JimPanic((fmtObjPtr->typePtr != &scanFmtStringObjType, "Jim_ScanString() for non-scan format"));
+
+ fmtObj = (ScanFmtStringObj *) fmtObjPtr->internalRep.ptr;
+
+ if (fmtObj->error != 0) {
+ if (flags & JIM_ERRMSG)
+ Jim_SetResultString(interp, fmtObj->error, -1);
+ return 0;
+ }
+
+ emptyStr = Jim_NewEmptyStringObj(interp);
+ Jim_IncrRefCount(emptyStr);
+
+ resultList = Jim_NewListObj(interp, NULL, 0);
+ if (fmtObj->maxPos > 0) {
+ for (i = 0; i < fmtObj->maxPos; ++i)
+ Jim_ListAppendElement(interp, resultList, emptyStr);
+ JimListGetElements(interp, resultList, &resultc, &resultVec);
+ }
+
+ for (i = 0, pos = 0; i < fmtObj->count; ++i) {
+ ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
+ Jim_Obj *value = 0;
+
+
+ if (descr->type == 0)
+ continue;
+
+ if (scanned > 0)
+ scanned = ScanOneEntry(interp, str, pos, strLen, fmtObj, i, &value);
+
+ if (scanned == -1 && i == 0)
+ goto eof;
+
+ pos += scanned;
+
+
+ if (value == 0)
+ value = Jim_NewEmptyStringObj(interp);
+
+ if (descr->pos == -1) {
+ Jim_FreeNewObj(interp, value);
+ }
+ else if (descr->pos == 0)
+
+ Jim_ListAppendElement(interp, resultList, value);
+ else if (resultVec[descr->pos - 1] == emptyStr) {
+
+ Jim_DecrRefCount(interp, resultVec[descr->pos - 1]);
+ Jim_IncrRefCount(value);
+ resultVec[descr->pos - 1] = value;
+ }
+ else {
+
+ Jim_FreeNewObj(interp, value);
+ goto err;
+ }
+ }
+ Jim_DecrRefCount(interp, emptyStr);
+ return resultList;
+ eof:
+ Jim_DecrRefCount(interp, emptyStr);
+ Jim_FreeNewObj(interp, resultList);
+ return (Jim_Obj *)EOF;
+ err:
+ Jim_DecrRefCount(interp, emptyStr);
+ Jim_FreeNewObj(interp, resultList);
+ return 0;
+}
+
+
+static void JimPrngInit(Jim_Interp *interp)
+{
+#define PRNG_SEED_SIZE 256
+ int i;
+ unsigned int *seed;
+ time_t t = time(NULL);
+
+ interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
+
+ seed = Jim_Alloc(PRNG_SEED_SIZE * sizeof(*seed));
+ for (i = 0; i < PRNG_SEED_SIZE; i++) {
+ seed[i] = (rand() ^ t ^ clock());
+ }
+ JimPrngSeed(interp, (unsigned char *)seed, PRNG_SEED_SIZE * sizeof(*seed));
+ Jim_Free(seed);
+}
+
+
+static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
+{
+ Jim_PrngState *prng;
+ unsigned char *destByte = (unsigned char *)dest;
+ unsigned int si, sj, x;
+
+
+ if (interp->prngState == NULL)
+ JimPrngInit(interp);
+ prng = interp->prngState;
+
+ for (x = 0; x < len; x++) {
+ prng->i = (prng->i + 1) & 0xff;
+ si = prng->sbox[prng->i];
+ prng->j = (prng->j + si) & 0xff;
+ sj = prng->sbox[prng->j];
+ prng->sbox[prng->i] = sj;
+ prng->sbox[prng->j] = si;
+ *destByte++ = prng->sbox[(si + sj) & 0xff];
+ }
+}
+
+
+static void JimPrngSeed(Jim_Interp *interp, unsigned char *seed, int seedLen)
+{
+ int i;
+ Jim_PrngState *prng;
+
+
+ if (interp->prngState == NULL)
+ JimPrngInit(interp);
+ prng = interp->prngState;
+
+
+ for (i = 0; i < 256; i++)
+ prng->sbox[i] = i;
+
+ for (i = 0; i < seedLen; i++) {
+ unsigned char t;
+
+ t = prng->sbox[i & 0xFF];
+ prng->sbox[i & 0xFF] = prng->sbox[seed[i]];
+ prng->sbox[seed[i]] = t;
+ }
+ prng->i = prng->j = 0;
+
+ for (i = 0; i < 256; i += seedLen) {
+ JimRandomBytes(interp, seed, seedLen);
+ }
+}
+
+
+static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ jim_wide wideValue, increment = 1;
+ Jim_Obj *intObjPtr;
+
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
+ return JIM_ERR;
+ }
+ if (argc == 3) {
+ if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)
+ return JIM_ERR;
+ }
+ intObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
+ if (!intObjPtr) {
+
+ wideValue = 0;
+ }
+ else if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (!intObjPtr || Jim_IsShared(intObjPtr)) {
+ intObjPtr = Jim_NewIntObj(interp, wideValue + increment);
+ if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
+ Jim_FreeNewObj(interp, intObjPtr);
+ return JIM_ERR;
+ }
+ }
+ else {
+
+ Jim_InvalidateStringRep(intObjPtr);
+ JimWideValue(intObjPtr) = wideValue + increment;
+
+ if (argv[1]->typePtr != &variableObjType) {
+
+ Jim_SetVariable(interp, argv[1], intObjPtr);
+ }
+ }
+ Jim_SetResult(interp, intObjPtr);
+ return JIM_OK;
+}
+
+
+#define JIM_EVAL_SARGV_LEN 8
+#define JIM_EVAL_SINTV_LEN 8
+
+
+static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int retcode;
+
+ if (interp->unknown_called > 50) {
+ return JIM_ERR;
+ }
+
+
+
+ if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
+ return JIM_ERR;
+
+ interp->unknown_called++;
+
+ retcode = Jim_EvalObjPrefix(interp, interp->unknown, argc, argv);
+ interp->unknown_called--;
+
+ return retcode;
+}
+
+static int JimInvokeCommand(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+{
+ int retcode;
+ Jim_Cmd *cmdPtr;
+ void *prevPrivData;
+
+#if 0
+ printf("invoke");
+ int j;
+ for (j = 0; j < objc; j++) {
+ printf(" '%s'", Jim_String(objv[j]));
+ }
+ printf("\n");
+#endif
+
+ if (interp->framePtr->tailcallCmd) {
+
+ cmdPtr = interp->framePtr->tailcallCmd;
+ interp->framePtr->tailcallCmd = NULL;
+ }
+ else {
+ cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
+ if (cmdPtr == NULL) {
+ return JimUnknown(interp, objc, objv);
+ }
+ JimIncrCmdRefCount(cmdPtr);
+ }
+
+ if (interp->evalDepth == interp->maxEvalDepth) {
+ Jim_SetResultString(interp, "Infinite eval recursion", -1);
+ retcode = JIM_ERR;
+ goto out;
+ }
+ interp->evalDepth++;
+ prevPrivData = interp->cmdPrivData;
+
+
+ Jim_SetEmptyResult(interp);
+ if (cmdPtr->isproc) {
+ retcode = JimCallProcedure(interp, cmdPtr, objc, objv);
+ }
+ else {
+ interp->cmdPrivData = cmdPtr->u.native.privData;
+ retcode = cmdPtr->u.native.cmdProc(interp, objc, objv);
+ }
+ interp->cmdPrivData = prevPrivData;
+ interp->evalDepth--;
+
+out:
+ JimDecrCmdRefCount(interp, cmdPtr);
+
+ return retcode;
+}
+
+int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+{
+ int i, retcode;
+
+
+ for (i = 0; i < objc; i++)
+ Jim_IncrRefCount(objv[i]);
+
+ retcode = JimInvokeCommand(interp, objc, objv);
+
+
+ for (i = 0; i < objc; i++)
+ Jim_DecrRefCount(interp, objv[i]);
+
+ return retcode;
+}
+
+int Jim_EvalObjPrefix(Jim_Interp *interp, Jim_Obj *prefix, int objc, Jim_Obj *const *objv)
+{
+ int ret;
+ Jim_Obj **nargv = Jim_Alloc((objc + 1) * sizeof(*nargv));
+
+ nargv[0] = prefix;
+ memcpy(&nargv[1], &objv[0], sizeof(nargv[0]) * objc);
+ ret = Jim_EvalObjVector(interp, objc + 1, nargv);
+ Jim_Free(nargv);
+ return ret;
+}
+
+static void JimAddErrorToStack(Jim_Interp *interp, ScriptObj *script)
+{
+ if (!interp->errorFlag) {
+
+ interp->errorFlag = 1;
+ Jim_IncrRefCount(script->fileNameObj);
+ Jim_DecrRefCount(interp, interp->errorFileNameObj);
+ interp->errorFileNameObj = script->fileNameObj;
+ interp->errorLine = script->linenr;
+
+ JimResetStackTrace(interp);
+
+ interp->addStackTrace++;
+ }
+
+
+ if (interp->addStackTrace > 0) {
+
+
+ JimAppendStackTrace(interp, Jim_String(interp->errorProc), script->fileNameObj, script->linenr);
+
+ if (Jim_Length(script->fileNameObj)) {
+ interp->addStackTrace = 0;
+ }
+
+ Jim_DecrRefCount(interp, interp->errorProc);
+ interp->errorProc = interp->emptyObj;
+ Jim_IncrRefCount(interp->errorProc);
+ }
+}
+
+static int JimSubstOneToken(Jim_Interp *interp, const ScriptToken *token, Jim_Obj **objPtrPtr)
+{
+ Jim_Obj *objPtr;
+
+ switch (token->type) {
+ case JIM_TT_STR:
+ case JIM_TT_ESC:
+ objPtr = token->objPtr;
+ break;
+ case JIM_TT_VAR:
+ objPtr = Jim_GetVariable(interp, token->objPtr, JIM_ERRMSG);
+ break;
+ case JIM_TT_DICTSUGAR:
+ objPtr = JimExpandDictSugar(interp, token->objPtr);
+ break;
+ case JIM_TT_EXPRSUGAR:
+ objPtr = JimExpandExprSugar(interp, token->objPtr);
+ break;
+ case JIM_TT_CMD:
+ switch (Jim_EvalObj(interp, token->objPtr)) {
+ case JIM_OK:
+ case JIM_RETURN:
+ objPtr = interp->result;
+ break;
+ case JIM_BREAK:
+
+ return JIM_BREAK;
+ case JIM_CONTINUE:
+
+ return JIM_CONTINUE;
+ default:
+ return JIM_ERR;
+ }
+ break;
+ default:
+ JimPanic((1,
+ "default token type (%d) reached " "in Jim_SubstObj().", token->type));
+ objPtr = NULL;
+ break;
+ }
+ if (objPtr) {
+ *objPtrPtr = objPtr;
+ return JIM_OK;
+ }
+ return JIM_ERR;
+}
+
+static Jim_Obj *JimInterpolateTokens(Jim_Interp *interp, const ScriptToken * token, int tokens, int flags)
+{
+ int totlen = 0, i;
+ Jim_Obj **intv;
+ Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
+ Jim_Obj *objPtr;
+ char *s;
+
+ if (tokens <= JIM_EVAL_SINTV_LEN)
+ intv = sintv;
+ else
+ intv = Jim_Alloc(sizeof(Jim_Obj *) * tokens);
+
+ for (i = 0; i < tokens; i++) {
+ switch (JimSubstOneToken(interp, &token[i], &intv[i])) {
+ case JIM_OK:
+ case JIM_RETURN:
+ break;
+ case JIM_BREAK:
+ if (flags & JIM_SUBST_FLAG) {
+
+ tokens = i;
+ continue;
+ }
+
+
+ case JIM_CONTINUE:
+ if (flags & JIM_SUBST_FLAG) {
+ intv[i] = NULL;
+ continue;
+ }
+
+
+ default:
+ while (i--) {
+ Jim_DecrRefCount(interp, intv[i]);
+ }
+ if (intv != sintv) {
+ Jim_Free(intv);
+ }
+ return NULL;
+ }
+ Jim_IncrRefCount(intv[i]);
+ Jim_String(intv[i]);
+ totlen += intv[i]->length;
+ }
+
+
+ if (tokens == 1 && intv[0] && intv == sintv) {
+
+ intv[0]->refCount--;
+ return intv[0];
+ }
+
+ objPtr = Jim_NewStringObjNoAlloc(interp, NULL, 0);
+
+ if (tokens == 4 && token[0].type == JIM_TT_ESC && token[1].type == JIM_TT_ESC
+ && token[2].type == JIM_TT_VAR) {
+
+ objPtr->typePtr = &interpolatedObjType;
+ objPtr->internalRep.dictSubstValue.varNameObjPtr = token[0].objPtr;
+ objPtr->internalRep.dictSubstValue.indexObjPtr = intv[2];
+ Jim_IncrRefCount(intv[2]);
+ }
+ else if (tokens && intv[0] && intv[0]->typePtr == &sourceObjType) {
+
+ JimSetSourceInfo(interp, objPtr, intv[0]->internalRep.sourceValue.fileNameObj, intv[0]->internalRep.sourceValue.lineNumber);
+ }
+
+
+ s = objPtr->bytes = Jim_Alloc(totlen + 1);
+ objPtr->length = totlen;
+ for (i = 0; i < tokens; i++) {
+ if (intv[i]) {
+ memcpy(s, intv[i]->bytes, intv[i]->length);
+ s += intv[i]->length;
+ Jim_DecrRefCount(interp, intv[i]);
+ }
+ }
+ objPtr->bytes[totlen] = '\0';
+
+ if (intv != sintv) {
+ Jim_Free(intv);
+ }
+
+ return objPtr;
+}
+
+
+static int JimEvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
+{
+ int retcode = JIM_OK;
+
+ JimPanic((Jim_IsList(listPtr) == 0, "JimEvalObjList() invoked on non-list."));
+
+ if (listPtr->internalRep.listValue.len) {
+ Jim_IncrRefCount(listPtr);
+ retcode = JimInvokeCommand(interp,
+ listPtr->internalRep.listValue.len,
+ listPtr->internalRep.listValue.ele);
+ Jim_DecrRefCount(interp, listPtr);
+ }
+ return retcode;
+}
+
+int Jim_EvalObjList(Jim_Interp *interp, Jim_Obj *listPtr)
+{
+ SetListFromAny(interp, listPtr);
+ return JimEvalObjList(interp, listPtr);
+}
+
+int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
+{
+ int i;
+ ScriptObj *script;
+ ScriptToken *token;
+ int retcode = JIM_OK;
+ Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL;
+ Jim_Obj *prevScriptObj;
+
+ if (Jim_IsList(scriptObjPtr) && scriptObjPtr->bytes == NULL) {
+ return JimEvalObjList(interp, scriptObjPtr);
+ }
+
+ Jim_IncrRefCount(scriptObjPtr);
+ script = JimGetScript(interp, scriptObjPtr);
+ if (!JimScriptValid(interp, script)) {
+ Jim_DecrRefCount(interp, scriptObjPtr);
+ return JIM_ERR;
+ }
+
+ Jim_SetEmptyResult(interp);
+
+ token = script->token;
+
+#ifdef JIM_OPTIMIZATION
+ if (script->len == 0) {
+ Jim_DecrRefCount(interp, scriptObjPtr);
+ return JIM_OK;
+ }
+ if (script->len == 3
+ && token[1].objPtr->typePtr == &commandObjType
+ && token[1].objPtr->internalRep.cmdValue.cmdPtr->isproc == 0
+ && token[1].objPtr->internalRep.cmdValue.cmdPtr->u.native.cmdProc == Jim_IncrCoreCommand
+ && token[2].objPtr->typePtr == &variableObjType) {
+
+ Jim_Obj *objPtr = Jim_GetVariable(interp, token[2].objPtr, JIM_NONE);
+
+ if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
+ JimWideValue(objPtr)++;
+ Jim_InvalidateStringRep(objPtr);
+ Jim_DecrRefCount(interp, scriptObjPtr);
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+ }
+#endif
+
+ script->inUse++;
+
+
+ prevScriptObj = interp->currentScriptObj;
+ interp->currentScriptObj = scriptObjPtr;
+
+ interp->errorFlag = 0;
+ argv = sargv;
+
+ for (i = 0; i < script->len && retcode == JIM_OK; ) {
+ int argc;
+ int j;
+
+
+ argc = token[i].objPtr->internalRep.scriptLineValue.argc;
+ script->linenr = token[i].objPtr->internalRep.scriptLineValue.line;
+
+
+ if (argc > JIM_EVAL_SARGV_LEN)
+ argv = Jim_Alloc(sizeof(Jim_Obj *) * argc);
+
+
+ i++;
+
+ for (j = 0; j < argc; j++) {
+ long wordtokens = 1;
+ int expand = 0;
+ Jim_Obj *wordObjPtr = NULL;
+
+ if (token[i].type == JIM_TT_WORD) {
+ wordtokens = JimWideValue(token[i++].objPtr);
+ if (wordtokens < 0) {
+ expand = 1;
+ wordtokens = -wordtokens;
+ }
+ }
+
+ if (wordtokens == 1) {
+
+ switch (token[i].type) {
+ case JIM_TT_ESC:
+ case JIM_TT_STR:
+ wordObjPtr = token[i].objPtr;
+ break;
+ case JIM_TT_VAR:
+ wordObjPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
+ break;
+ case JIM_TT_EXPRSUGAR:
+ wordObjPtr = JimExpandExprSugar(interp, token[i].objPtr);
+ break;
+ case JIM_TT_DICTSUGAR:
+ wordObjPtr = JimExpandDictSugar(interp, token[i].objPtr);
+ break;
+ case JIM_TT_CMD:
+ retcode = Jim_EvalObj(interp, token[i].objPtr);
+ if (retcode == JIM_OK) {
+ wordObjPtr = Jim_GetResult(interp);
+ }
+ break;
+ default:
+ JimPanic((1, "default token type reached " "in Jim_EvalObj()."));
+ }
+ }
+ else {
+ wordObjPtr = JimInterpolateTokens(interp, token + i, wordtokens, JIM_NONE);
+ }
+
+ if (!wordObjPtr) {
+ if (retcode == JIM_OK) {
+ retcode = JIM_ERR;
+ }
+ break;
+ }
+
+ Jim_IncrRefCount(wordObjPtr);
+ i += wordtokens;
+
+ if (!expand) {
+ argv[j] = wordObjPtr;
+ }
+ else {
+
+ int len = Jim_ListLength(interp, wordObjPtr);
+ int newargc = argc + len - 1;
+ int k;
+
+ if (len > 1) {
+ if (argv == sargv) {
+ if (newargc > JIM_EVAL_SARGV_LEN) {
+ argv = Jim_Alloc(sizeof(*argv) * newargc);
+ memcpy(argv, sargv, sizeof(*argv) * j);
+ }
+ }
+ else {
+
+ argv = Jim_Realloc(argv, sizeof(*argv) * newargc);
+ }
+ }
+
+
+ for (k = 0; k < len; k++) {
+ argv[j++] = wordObjPtr->internalRep.listValue.ele[k];
+ Jim_IncrRefCount(wordObjPtr->internalRep.listValue.ele[k]);
+ }
+
+ Jim_DecrRefCount(interp, wordObjPtr);
+
+
+ j--;
+ argc += len - 1;
+ }
+ }
+
+ if (retcode == JIM_OK && argc) {
+
+ retcode = JimInvokeCommand(interp, argc, argv);
+
+ if (Jim_CheckSignal(interp)) {
+ retcode = JIM_SIGNAL;
+ }
+ }
+
+
+ while (j-- > 0) {
+ Jim_DecrRefCount(interp, argv[j]);
+ }
+
+ if (argv != sargv) {
+ Jim_Free(argv);
+ argv = sargv;
+ }
+ }
+
+
+ if (retcode == JIM_ERR) {
+ JimAddErrorToStack(interp, script);
+ }
+
+ else if (retcode != JIM_RETURN || interp->returnCode != JIM_ERR) {
+
+ interp->addStackTrace = 0;
+ }
+
+
+ interp->currentScriptObj = prevScriptObj;
+
+ Jim_FreeIntRep(interp, scriptObjPtr);
+ scriptObjPtr->typePtr = &scriptObjType;
+ Jim_SetIntRepPtr(scriptObjPtr, script);
+ Jim_DecrRefCount(interp, scriptObjPtr);
+
+ return retcode;
+}
+
+static int JimSetProcArg(Jim_Interp *interp, Jim_Obj *argNameObj, Jim_Obj *argValObj)
+{
+ int retcode;
+
+ const char *varname = Jim_String(argNameObj);
+ if (*varname == '&') {
+
+ Jim_Obj *objPtr;
+ Jim_CallFrame *savedCallFrame = interp->framePtr;
+
+ interp->framePtr = interp->framePtr->parent;
+ objPtr = Jim_GetVariable(interp, argValObj, JIM_ERRMSG);
+ interp->framePtr = savedCallFrame;
+ if (!objPtr) {
+ return JIM_ERR;
+ }
+
+
+ objPtr = Jim_NewStringObj(interp, varname + 1, -1);
+ Jim_IncrRefCount(objPtr);
+ retcode = Jim_SetVariableLink(interp, objPtr, argValObj, interp->framePtr->parent);
+ Jim_DecrRefCount(interp, objPtr);
+ }
+ else {
+ retcode = Jim_SetVariable(interp, argNameObj, argValObj);
+ }
+ return retcode;
+}
+
+static void JimSetProcWrongArgs(Jim_Interp *interp, Jim_Obj *procNameObj, Jim_Cmd *cmd)
+{
+
+ Jim_Obj *argmsg = Jim_NewStringObj(interp, "", 0);
+ int i;
+
+ for (i = 0; i < cmd->u.proc.argListLen; i++) {
+ Jim_AppendString(interp, argmsg, " ", 1);
+
+ if (i == cmd->u.proc.argsPos) {
+ if (cmd->u.proc.arglist[i].defaultObjPtr) {
+
+ Jim_AppendString(interp, argmsg, "?", 1);
+ Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].defaultObjPtr);
+ Jim_AppendString(interp, argmsg, " ...?", -1);
+ }
+ else {
+
+ Jim_AppendString(interp, argmsg, "?arg...?", -1);
+ }
+ }
+ else {
+ if (cmd->u.proc.arglist[i].defaultObjPtr) {
+ Jim_AppendString(interp, argmsg, "?", 1);
+ Jim_AppendObj(interp, argmsg, cmd->u.proc.arglist[i].nameObjPtr);
+ Jim_AppendString(interp, argmsg, "?", 1);
+ }
+ else {
+ const char *arg = Jim_String(cmd->u.proc.arglist[i].nameObjPtr);
+ if (*arg == '&') {
+ arg++;
+ }
+ Jim_AppendString(interp, argmsg, arg, -1);
+ }
+ }
+ }
+ Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s%#s\"", procNameObj, argmsg);
+}
+
+#ifdef jim_ext_namespace
+int Jim_EvalNamespace(Jim_Interp *interp, Jim_Obj *scriptObj, Jim_Obj *nsObj)
+{
+ Jim_CallFrame *callFramePtr;
+ int retcode;
+
+
+ callFramePtr = JimCreateCallFrame(interp, interp->framePtr, nsObj);
+ callFramePtr->argv = &interp->emptyObj;
+ callFramePtr->argc = 0;
+ callFramePtr->procArgsObjPtr = NULL;
+ callFramePtr->procBodyObjPtr = scriptObj;
+ callFramePtr->staticVars = NULL;
+ callFramePtr->fileNameObj = interp->emptyObj;
+ callFramePtr->line = 0;
+ Jim_IncrRefCount(scriptObj);
+ interp->framePtr = callFramePtr;
+
+
+ if (interp->framePtr->level == interp->maxCallFrameDepth) {
+ Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
+ retcode = JIM_ERR;
+ }
+ else {
+
+ retcode = Jim_EvalObj(interp, scriptObj);
+ }
+
+
+ interp->framePtr = interp->framePtr->parent;
+ JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
+
+ return retcode;
+}
+#endif
+
+static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc, Jim_Obj *const *argv)
+{
+ Jim_CallFrame *callFramePtr;
+ int i, d, retcode, optargs;
+ ScriptObj *script;
+
+
+ if (argc - 1 < cmd->u.proc.reqArity ||
+ (cmd->u.proc.argsPos < 0 && argc - 1 > cmd->u.proc.reqArity + cmd->u.proc.optArity)) {
+ JimSetProcWrongArgs(interp, argv[0], cmd);
+ return JIM_ERR;
+ }
+
+ if (Jim_Length(cmd->u.proc.bodyObjPtr) == 0) {
+
+ return JIM_OK;
+ }
+
+
+ if (interp->framePtr->level == interp->maxCallFrameDepth) {
+ Jim_SetResultString(interp, "Too many nested calls. Infinite recursion?", -1);
+ return JIM_ERR;
+ }
+
+
+ callFramePtr = JimCreateCallFrame(interp, interp->framePtr, cmd->u.proc.nsObj);
+ callFramePtr->argv = argv;
+ callFramePtr->argc = argc;
+ callFramePtr->procArgsObjPtr = cmd->u.proc.argListObjPtr;
+ callFramePtr->procBodyObjPtr = cmd->u.proc.bodyObjPtr;
+ callFramePtr->staticVars = cmd->u.proc.staticVars;
+
+
+ script = JimGetScript(interp, interp->currentScriptObj);
+ callFramePtr->fileNameObj = script->fileNameObj;
+ callFramePtr->line = script->linenr;
+
+ Jim_IncrRefCount(cmd->u.proc.argListObjPtr);
+ Jim_IncrRefCount(cmd->u.proc.bodyObjPtr);
+ interp->framePtr = callFramePtr;
+
+
+ optargs = (argc - 1 - cmd->u.proc.reqArity);
+
+
+ i = 1;
+ for (d = 0; d < cmd->u.proc.argListLen; d++) {
+ Jim_Obj *nameObjPtr = cmd->u.proc.arglist[d].nameObjPtr;
+ if (d == cmd->u.proc.argsPos) {
+
+ Jim_Obj *listObjPtr;
+ int argsLen = 0;
+ if (cmd->u.proc.reqArity + cmd->u.proc.optArity < argc - 1) {
+ argsLen = argc - 1 - (cmd->u.proc.reqArity + cmd->u.proc.optArity);
+ }
+ listObjPtr = Jim_NewListObj(interp, &argv[i], argsLen);
+
+
+ if (cmd->u.proc.arglist[d].defaultObjPtr) {
+ nameObjPtr =cmd->u.proc.arglist[d].defaultObjPtr;
+ }
+ retcode = Jim_SetVariable(interp, nameObjPtr, listObjPtr);
+ if (retcode != JIM_OK) {
+ goto badargset;
+ }
+
+ i += argsLen;
+ continue;
+ }
+
+
+ if (cmd->u.proc.arglist[d].defaultObjPtr == NULL || optargs-- > 0) {
+ retcode = JimSetProcArg(interp, nameObjPtr, argv[i++]);
+ }
+ else {
+
+ retcode = Jim_SetVariable(interp, nameObjPtr, cmd->u.proc.arglist[d].defaultObjPtr);
+ }
+ if (retcode != JIM_OK) {
+ goto badargset;
+ }
+ }
+
+
+ retcode = Jim_EvalObj(interp, cmd->u.proc.bodyObjPtr);
+
+badargset:
+
+
+ retcode = JimInvokeDefer(interp, retcode);
+ interp->framePtr = interp->framePtr->parent;
+ JimFreeCallFrame(interp, callFramePtr, JIM_FCF_REUSE);
+
+
+ if (interp->framePtr->tailcallObj) {
+ do {
+ Jim_Obj *tailcallObj = interp->framePtr->tailcallObj;
+
+ interp->framePtr->tailcallObj = NULL;
+
+ if (retcode == JIM_EVAL) {
+ retcode = Jim_EvalObjList(interp, tailcallObj);
+ if (retcode == JIM_RETURN) {
+ interp->returnLevel++;
+ }
+ }
+ Jim_DecrRefCount(interp, tailcallObj);
+ } while (interp->framePtr->tailcallObj);
+
+
+ if (interp->framePtr->tailcallCmd) {
+ JimDecrCmdRefCount(interp, interp->framePtr->tailcallCmd);
+ interp->framePtr->tailcallCmd = NULL;
+ }
+ }
+
+
+ if (retcode == JIM_RETURN) {
+ if (--interp->returnLevel <= 0) {
+ retcode = interp->returnCode;
+ interp->returnCode = JIM_OK;
+ interp->returnLevel = 0;
+ }
+ }
+ else if (retcode == JIM_ERR) {
+ interp->addStackTrace++;
+ Jim_DecrRefCount(interp, interp->errorProc);
+ interp->errorProc = argv[0];
+ Jim_IncrRefCount(interp->errorProc);
+ }
+
+ return retcode;
+}
+
+int Jim_EvalSource(Jim_Interp *interp, const char *filename, int lineno, const char *script)
+{
+ int retval;
+ Jim_Obj *scriptObjPtr;
+
+ scriptObjPtr = Jim_NewStringObj(interp, script, -1);
+ Jim_IncrRefCount(scriptObjPtr);
+
+ if (filename) {
+ Jim_Obj *prevScriptObj;
+
+ JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), lineno);
+
+ prevScriptObj = interp->currentScriptObj;
+ interp->currentScriptObj = scriptObjPtr;
+
+ retval = Jim_EvalObj(interp, scriptObjPtr);
+
+ interp->currentScriptObj = prevScriptObj;
+ }
+ else {
+ retval = Jim_EvalObj(interp, scriptObjPtr);
+ }
+ Jim_DecrRefCount(interp, scriptObjPtr);
+ return retval;
+}
+
+int Jim_Eval(Jim_Interp *interp, const char *script)
+{
+ return Jim_EvalObj(interp, Jim_NewStringObj(interp, script, -1));
+}
+
+
+int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
+{
+ int retval;
+ Jim_CallFrame *savedFramePtr = interp->framePtr;
+
+ interp->framePtr = interp->topFramePtr;
+ retval = Jim_Eval(interp, script);
+ interp->framePtr = savedFramePtr;
+
+ return retval;
+}
+
+int Jim_EvalFileGlobal(Jim_Interp *interp, const char *filename)
+{
+ int retval;
+ Jim_CallFrame *savedFramePtr = interp->framePtr;
+
+ interp->framePtr = interp->topFramePtr;
+ retval = Jim_EvalFile(interp, filename);
+ interp->framePtr = savedFramePtr;
+
+ return retval;
+}
+
+#include
+
+int Jim_EvalFile(Jim_Interp *interp, const char *filename)
+{
+ FILE *fp;
+ char *buf;
+ Jim_Obj *scriptObjPtr;
+ Jim_Obj *prevScriptObj;
+ struct stat sb;
+ int retcode;
+ int readlen;
+
+ if (stat(filename, &sb) != 0 || (fp = fopen(filename, "rt")) == NULL) {
+ Jim_SetResultFormatted(interp, "couldn't read file \"%s\": %s", filename, strerror(errno));
+ return JIM_ERR;
+ }
+ if (sb.st_size == 0) {
+ fclose(fp);
+ return JIM_OK;
+ }
+
+ buf = Jim_Alloc(sb.st_size + 1);
+ readlen = fread(buf, 1, sb.st_size, fp);
+ if (ferror(fp)) {
+ fclose(fp);
+ Jim_Free(buf);
+ Jim_SetResultFormatted(interp, "failed to load file \"%s\": %s", filename, strerror(errno));
+ return JIM_ERR;
+ }
+ fclose(fp);
+ buf[readlen] = 0;
+
+ scriptObjPtr = Jim_NewStringObjNoAlloc(interp, buf, readlen);
+ JimSetSourceInfo(interp, scriptObjPtr, Jim_NewStringObj(interp, filename, -1), 1);
+ Jim_IncrRefCount(scriptObjPtr);
+
+ prevScriptObj = interp->currentScriptObj;
+ interp->currentScriptObj = scriptObjPtr;
+
+ retcode = Jim_EvalObj(interp, scriptObjPtr);
+
+
+ if (retcode == JIM_RETURN) {
+ if (--interp->returnLevel <= 0) {
+ retcode = interp->returnCode;
+ interp->returnCode = JIM_OK;
+ interp->returnLevel = 0;
+ }
+ }
+ if (retcode == JIM_ERR) {
+
+ interp->addStackTrace++;
+ }
+
+ interp->currentScriptObj = prevScriptObj;
+
+ Jim_DecrRefCount(interp, scriptObjPtr);
+
+ return retcode;
+}
+
+static void JimParseSubst(struct JimParserCtx *pc, int flags)
+{
+ pc->tstart = pc->p;
+ pc->tline = pc->linenr;
+
+ if (pc->len == 0) {
+ pc->tend = pc->p;
+ pc->tt = JIM_TT_EOL;
+ pc->eof = 1;
+ return;
+ }
+ if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
+ JimParseCmd(pc);
+ return;
+ }
+ if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
+ if (JimParseVar(pc) == JIM_OK) {
+ return;
+ }
+
+ pc->tstart = pc->p;
+ flags |= JIM_SUBST_NOVAR;
+ }
+ while (pc->len) {
+ if (*pc->p == '$' && !(flags & JIM_SUBST_NOVAR)) {
+ break;
+ }
+ if (*pc->p == '[' && !(flags & JIM_SUBST_NOCMD)) {
+ break;
+ }
+ if (*pc->p == '\\' && pc->len > 1) {
+ pc->p++;
+ pc->len--;
+ }
+ pc->p++;
+ pc->len--;
+ }
+ pc->tend = pc->p - 1;
+ pc->tt = (flags & JIM_SUBST_NOESC) ? JIM_TT_STR : JIM_TT_ESC;
+}
+
+
+static int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
+{
+ int scriptTextLen;
+ const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
+ struct JimParserCtx parser;
+ struct ScriptObj *script = Jim_Alloc(sizeof(*script));
+ ParseTokenList tokenlist;
+
+
+ ScriptTokenListInit(&tokenlist);
+
+ JimParserInit(&parser, scriptText, scriptTextLen, 1);
+ while (1) {
+ JimParseSubst(&parser, flags);
+ if (parser.eof) {
+
+ break;
+ }
+ ScriptAddToken(&tokenlist, parser.tstart, parser.tend - parser.tstart + 1, parser.tt,
+ parser.tline);
+ }
+
+
+ script->inUse = 1;
+ script->substFlags = flags;
+ script->fileNameObj = interp->emptyObj;
+ Jim_IncrRefCount(script->fileNameObj);
+ SubstObjAddTokens(interp, script, &tokenlist);
+
+
+ ScriptTokenListFree(&tokenlist);
+
+#ifdef DEBUG_SHOW_SUBST
+ {
+ int i;
+
+ printf("==== Subst ====\n");
+ for (i = 0; i < script->len; i++) {
+ printf("[%2d] %s '%s'\n", i, jim_tt_name(script->token[i].type),
+ Jim_String(script->token[i].objPtr));
+ }
+ }
+#endif
+
+
+ Jim_FreeIntRep(interp, objPtr);
+ Jim_SetIntRepPtr(objPtr, script);
+ objPtr->typePtr = &scriptObjType;
+ return JIM_OK;
+}
+
+static ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+ if (objPtr->typePtr != &scriptObjType || ((ScriptObj *)Jim_GetIntRepPtr(objPtr))->substFlags != flags)
+ SetSubstFromAny(interp, objPtr, flags);
+ return (ScriptObj *) Jim_GetIntRepPtr(objPtr);
+}
+
+int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr, Jim_Obj **resObjPtrPtr, int flags)
+{
+ ScriptObj *script = Jim_GetSubst(interp, substObjPtr, flags);
+
+ Jim_IncrRefCount(substObjPtr);
+ script->inUse++;
+
+ *resObjPtrPtr = JimInterpolateTokens(interp, script->token, script->len, flags);
+
+ script->inUse--;
+ Jim_DecrRefCount(interp, substObjPtr);
+ if (*resObjPtrPtr == NULL) {
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, const char *msg)
+{
+ Jim_Obj *objPtr;
+ Jim_Obj *listObjPtr;
+
+ JimPanic((argc == 0, "Jim_WrongNumArgs() called with argc=0"));
+
+ listObjPtr = Jim_NewListObj(interp, argv, argc);
+
+ if (msg && *msg) {
+ Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, msg, -1));
+ }
+ Jim_IncrRefCount(listObjPtr);
+ objPtr = Jim_ListJoin(interp, listObjPtr, " ", 1);
+ Jim_DecrRefCount(interp, listObjPtr);
+
+ Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s\"", objPtr);
+}
+
+typedef void JimHashtableIteratorCallbackType(Jim_Interp *interp, Jim_Obj *listObjPtr,
+ Jim_HashEntry *he, int type);
+
+#define JimTrivialMatch(pattern) (strpbrk((pattern), "*[?\\") == NULL)
+
+static Jim_Obj *JimHashtablePatternMatch(Jim_Interp *interp, Jim_HashTable *ht, Jim_Obj *patternObjPtr,
+ JimHashtableIteratorCallbackType *callback, int type)
+{
+ Jim_HashEntry *he;
+ Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+
+
+ if (patternObjPtr && JimTrivialMatch(Jim_String(patternObjPtr))) {
+ he = Jim_FindHashEntry(ht, Jim_String(patternObjPtr));
+ if (he) {
+ callback(interp, listObjPtr, he, type);
+ }
+ }
+ else {
+ Jim_HashTableIterator htiter;
+ JimInitHashTableIterator(ht, &htiter);
+ while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+ if (patternObjPtr == NULL || JimGlobMatch(Jim_String(patternObjPtr), he->key, 0)) {
+ callback(interp, listObjPtr, he, type);
+ }
+ }
+ }
+ return listObjPtr;
+}
+
+
+#define JIM_CMDLIST_COMMANDS 0
+#define JIM_CMDLIST_PROCS 1
+#define JIM_CMDLIST_CHANNELS 2
+
+static void JimCommandMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
+ Jim_HashEntry *he, int type)
+{
+ Jim_Cmd *cmdPtr = Jim_GetHashEntryVal(he);
+ Jim_Obj *objPtr;
+
+ if (type == JIM_CMDLIST_PROCS && !cmdPtr->isproc) {
+
+ return;
+ }
+
+ objPtr = Jim_NewStringObj(interp, he->key, -1);
+ Jim_IncrRefCount(objPtr);
+
+ if (type != JIM_CMDLIST_CHANNELS || Jim_AioFilehandle(interp, objPtr)) {
+ Jim_ListAppendElement(interp, listObjPtr, objPtr);
+ }
+ Jim_DecrRefCount(interp, objPtr);
+}
+
+
+static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int type)
+{
+ return JimHashtablePatternMatch(interp, &interp->commands, patternObjPtr, JimCommandMatch, type);
+}
+
+
+#define JIM_VARLIST_GLOBALS 0
+#define JIM_VARLIST_LOCALS 1
+#define JIM_VARLIST_VARS 2
+
+#define JIM_VARLIST_VALUES 0x1000
+
+static void JimVariablesMatch(Jim_Interp *interp, Jim_Obj *listObjPtr,
+ Jim_HashEntry *he, int type)
+{
+ Jim_Var *varPtr = Jim_GetHashEntryVal(he);
+
+ if (type != JIM_VARLIST_LOCALS || varPtr->linkFramePtr == NULL) {
+ Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, he->key, -1));
+ if (type & JIM_VARLIST_VALUES) {
+ Jim_ListAppendElement(interp, listObjPtr, varPtr->objPtr);
+ }
+ }
+}
+
+
+static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr, int mode)
+{
+ if (mode == JIM_VARLIST_LOCALS && interp->framePtr == interp->topFramePtr) {
+ return interp->emptyObj;
+ }
+ else {
+ Jim_CallFrame *framePtr = (mode == JIM_VARLIST_GLOBALS) ? interp->topFramePtr : interp->framePtr;
+ return JimHashtablePatternMatch(interp, &framePtr->vars, patternObjPtr, JimVariablesMatch, mode);
+ }
+}
+
+static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
+ Jim_Obj **objPtrPtr, int info_level_cmd)
+{
+ Jim_CallFrame *targetCallFrame;
+
+ targetCallFrame = JimGetCallFrameByInteger(interp, levelObjPtr);
+ if (targetCallFrame == NULL) {
+ return JIM_ERR;
+ }
+
+ if (targetCallFrame == interp->topFramePtr) {
+ Jim_SetResultFormatted(interp, "bad level \"%#s\"", levelObjPtr);
+ return JIM_ERR;
+ }
+ if (info_level_cmd) {
+ *objPtrPtr = Jim_NewListObj(interp, targetCallFrame->argv, targetCallFrame->argc);
+ }
+ else {
+ Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+
+ Jim_ListAppendElement(interp, listObj, targetCallFrame->argv[0]);
+ Jim_ListAppendElement(interp, listObj, targetCallFrame->fileNameObj);
+ Jim_ListAppendElement(interp, listObj, Jim_NewIntObj(interp, targetCallFrame->line));
+ *objPtrPtr = listObj;
+ }
+ return JIM_OK;
+}
+
+
+
+static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "?-nonewline? string");
+ return JIM_ERR;
+ }
+ if (argc == 3) {
+ if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline")) {
+ Jim_SetResultString(interp, "The second argument must " "be -nonewline", -1);
+ return JIM_ERR;
+ }
+ else {
+ fputs(Jim_String(argv[2]), stdout);
+ }
+ }
+ else {
+ puts(Jim_String(argv[1]));
+ }
+ return JIM_OK;
+}
+
+
+static int JimAddMulHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
+{
+ jim_wide wideValue, res;
+ double doubleValue, doubleRes;
+ int i;
+
+ res = (op == JIM_EXPROP_ADD) ? 0 : 1;
+
+ for (i = 1; i < argc; i++) {
+ if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
+ goto trydouble;
+ if (op == JIM_EXPROP_ADD)
+ res += wideValue;
+ else
+ res *= wideValue;
+ }
+ Jim_SetResultInt(interp, res);
+ return JIM_OK;
+ trydouble:
+ doubleRes = (double)res;
+ for (; i < argc; i++) {
+ if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
+ return JIM_ERR;
+ if (op == JIM_EXPROP_ADD)
+ doubleRes += doubleValue;
+ else
+ doubleRes *= doubleValue;
+ }
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+ return JIM_OK;
+}
+
+
+static int JimSubDivHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int op)
+{
+ jim_wide wideValue, res = 0;
+ double doubleValue, doubleRes = 0;
+ int i = 2;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
+ return JIM_ERR;
+ }
+ else if (argc == 2) {
+ if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
+ if (Jim_GetDouble(interp, argv[1], &doubleValue) != JIM_OK) {
+ return JIM_ERR;
+ }
+ else {
+ if (op == JIM_EXPROP_SUB)
+ doubleRes = -doubleValue;
+ else
+ doubleRes = 1.0 / doubleValue;
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+ return JIM_OK;
+ }
+ }
+ if (op == JIM_EXPROP_SUB) {
+ res = -wideValue;
+ Jim_SetResultInt(interp, res);
+ }
+ else {
+ doubleRes = 1.0 / wideValue;
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+ }
+ return JIM_OK;
+ }
+ else {
+ if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
+ if (Jim_GetDouble(interp, argv[1], &doubleRes)
+ != JIM_OK) {
+ return JIM_ERR;
+ }
+ else {
+ goto trydouble;
+ }
+ }
+ }
+ for (i = 2; i < argc; i++) {
+ if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
+ doubleRes = (double)res;
+ goto trydouble;
+ }
+ if (op == JIM_EXPROP_SUB)
+ res -= wideValue;
+ else {
+ if (wideValue == 0) {
+ Jim_SetResultString(interp, "Division by zero", -1);
+ return JIM_ERR;
+ }
+ res /= wideValue;
+ }
+ }
+ Jim_SetResultInt(interp, res);
+ return JIM_OK;
+ trydouble:
+ for (; i < argc; i++) {
+ if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
+ return JIM_ERR;
+ if (op == JIM_EXPROP_SUB)
+ doubleRes -= doubleValue;
+ else
+ doubleRes /= doubleValue;
+ }
+ Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+ return JIM_OK;
+}
+
+
+
+static int Jim_AddCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
+}
+
+
+static int Jim_MulCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return JimAddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
+}
+
+
+static int Jim_SubCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
+}
+
+
+static int Jim_DivCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return JimSubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
+}
+
+
+static int Jim_SetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
+ return JIM_ERR;
+ }
+ if (argc == 2) {
+ Jim_Obj *objPtr;
+
+ objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+ if (!objPtr)
+ return JIM_ERR;
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+
+ if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
+ return JIM_ERR;
+ Jim_SetResult(interp, argv[2]);
+ return JIM_OK;
+}
+
+static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int i = 1;
+ int complain = 1;
+
+ while (i < argc) {
+ if (Jim_CompareStringImmediate(interp, argv[i], "--")) {
+ i++;
+ break;
+ }
+ if (Jim_CompareStringImmediate(interp, argv[i], "-nocomplain")) {
+ complain = 0;
+ i++;
+ continue;
+ }
+ break;
+ }
+
+ while (i < argc) {
+ if (Jim_UnsetVariable(interp, argv[i], complain ? JIM_ERRMSG : JIM_NONE) != JIM_OK
+ && complain) {
+ return JIM_ERR;
+ }
+ i++;
+ }
+ return JIM_OK;
+}
+
+
+static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "condition body");
+ return JIM_ERR;
+ }
+
+
+ while (1) {
+ int boolean, retval;
+
+ if ((retval = Jim_GetBoolFromExpr(interp, argv[1], &boolean)) != JIM_OK)
+ return retval;
+ if (!boolean)
+ break;
+
+ if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
+ switch (retval) {
+ case JIM_BREAK:
+ goto out;
+ break;
+ case JIM_CONTINUE:
+ continue;
+ break;
+ default:
+ return retval;
+ }
+ }
+ }
+ out:
+ Jim_SetEmptyResult(interp);
+ return JIM_OK;
+}
+
+
+static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int retval;
+ int boolean = 1;
+ Jim_Obj *varNamePtr = NULL;
+ Jim_Obj *stopVarNamePtr = NULL;
+
+ if (argc != 5) {
+ Jim_WrongNumArgs(interp, 1, argv, "start test next body");
+ return JIM_ERR;
+ }
+
+
+ if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK) {
+ return retval;
+ }
+
+ retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
+
+
+#ifdef JIM_OPTIMIZATION
+ if (retval == JIM_OK && boolean) {
+ ScriptObj *incrScript;
+ struct ExprTree *expr;
+ jim_wide stop, currentVal;
+ Jim_Obj *objPtr;
+ int cmpOffset;
+
+
+ expr = JimGetExpression(interp, argv[2]);
+ incrScript = JimGetScript(interp, argv[3]);
+
+
+ if (incrScript == NULL || incrScript->len != 3 || !expr || expr->len != 3) {
+ goto evalstart;
+ }
+
+ if (incrScript->token[1].type != JIM_TT_ESC) {
+ goto evalstart;
+ }
+
+ if (expr->expr->type == JIM_EXPROP_LT) {
+ cmpOffset = 0;
+ }
+ else if (expr->expr->type == JIM_EXPROP_LTE) {
+ cmpOffset = 1;
+ }
+ else {
+ goto evalstart;
+ }
+
+ if (expr->expr->left->type != JIM_TT_VAR) {
+ goto evalstart;
+ }
+
+ if (expr->expr->right->type != JIM_TT_VAR && expr->expr->right->type != JIM_TT_EXPR_INT) {
+ goto evalstart;
+ }
+
+
+ if (!Jim_CompareStringImmediate(interp, incrScript->token[1].objPtr, "incr")) {
+ goto evalstart;
+ }
+
+
+ if (!Jim_StringEqObj(incrScript->token[2].objPtr, expr->expr->left->objPtr)) {
+ goto evalstart;
+ }
+
+
+ if (expr->expr->right->type == JIM_TT_EXPR_INT) {
+ if (Jim_GetWide(interp, expr->expr->right->objPtr, &stop) == JIM_ERR) {
+ goto evalstart;
+ }
+ }
+ else {
+ stopVarNamePtr = expr->expr->right->objPtr;
+ Jim_IncrRefCount(stopVarNamePtr);
+
+ stop = 0;
+ }
+
+
+ varNamePtr = expr->expr->left->objPtr;
+ Jim_IncrRefCount(varNamePtr);
+
+ objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
+ if (objPtr == NULL || Jim_GetWide(interp, objPtr, ¤tVal) != JIM_OK) {
+ goto testcond;
+ }
+
+
+ while (retval == JIM_OK) {
+
+
+
+
+ if (stopVarNamePtr) {
+ objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
+ if (objPtr == NULL || Jim_GetWide(interp, objPtr, &stop) != JIM_OK) {
+ goto testcond;
+ }
+ }
+
+ if (currentVal >= stop + cmpOffset) {
+ break;
+ }
+
+
+ retval = Jim_EvalObj(interp, argv[4]);
+ if (retval == JIM_OK || retval == JIM_CONTINUE) {
+ retval = JIM_OK;
+
+ objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
+
+
+ if (objPtr == NULL) {
+ retval = JIM_ERR;
+ goto out;
+ }
+ if (!Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
+ currentVal = ++JimWideValue(objPtr);
+ Jim_InvalidateStringRep(objPtr);
+ }
+ else {
+ if (Jim_GetWide(interp, objPtr, ¤tVal) != JIM_OK ||
+ Jim_SetVariable(interp, varNamePtr, Jim_NewIntObj(interp,
+ ++currentVal)) != JIM_OK) {
+ goto evalnext;
+ }
+ }
+ }
+ }
+ goto out;
+ }
+ evalstart:
+#endif
+
+ while (boolean && (retval == JIM_OK || retval == JIM_CONTINUE)) {
+
+ retval = Jim_EvalObj(interp, argv[4]);
+
+ if (retval == JIM_OK || retval == JIM_CONTINUE) {
+
+JIM_IF_OPTIM(evalnext:)
+ retval = Jim_EvalObj(interp, argv[3]);
+ if (retval == JIM_OK || retval == JIM_CONTINUE) {
+
+JIM_IF_OPTIM(testcond:)
+ retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean);
+ }
+ }
+ }
+JIM_IF_OPTIM(out:)
+ if (stopVarNamePtr) {
+ Jim_DecrRefCount(interp, stopVarNamePtr);
+ }
+ if (varNamePtr) {
+ Jim_DecrRefCount(interp, varNamePtr);
+ }
+
+ if (retval == JIM_CONTINUE || retval == JIM_BREAK || retval == JIM_OK) {
+ Jim_SetEmptyResult(interp);
+ return JIM_OK;
+ }
+
+ return retval;
+}
+
+
+static int Jim_LoopCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int retval;
+ jim_wide i;
+ jim_wide limit;
+ jim_wide incr = 1;
+ Jim_Obj *bodyObjPtr;
+
+ if (argc != 5 && argc != 6) {
+ Jim_WrongNumArgs(interp, 1, argv, "var first limit ?incr? body");
+ return JIM_ERR;
+ }
+
+ if (Jim_GetWide(interp, argv[2], &i) != JIM_OK ||
+ Jim_GetWide(interp, argv[3], &limit) != JIM_OK ||
+ (argc == 6 && Jim_GetWide(interp, argv[4], &incr) != JIM_OK)) {
+ return JIM_ERR;
+ }
+ bodyObjPtr = (argc == 5) ? argv[4] : argv[5];
+
+ retval = Jim_SetVariable(interp, argv[1], argv[2]);
+
+ while (((i < limit && incr > 0) || (i > limit && incr < 0)) && retval == JIM_OK) {
+ retval = Jim_EvalObj(interp, bodyObjPtr);
+ if (retval == JIM_OK || retval == JIM_CONTINUE) {
+ Jim_Obj *objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+
+ retval = JIM_OK;
+
+
+ i += incr;
+
+ if (objPtr && !Jim_IsShared(objPtr) && objPtr->typePtr == &intObjType) {
+ if (argv[1]->typePtr != &variableObjType) {
+ if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+ }
+ JimWideValue(objPtr) = i;
+ Jim_InvalidateStringRep(objPtr);
+
+ if (argv[1]->typePtr != &variableObjType) {
+ if (Jim_SetVariable(interp, argv[1], objPtr) != JIM_OK) {
+ retval = JIM_ERR;
+ break;
+ }
+ }
+ }
+ else {
+ objPtr = Jim_NewIntObj(interp, i);
+ retval = Jim_SetVariable(interp, argv[1], objPtr);
+ if (retval != JIM_OK) {
+ Jim_FreeNewObj(interp, objPtr);
+ }
+ }
+ }
+ }
+
+ if (retval == JIM_OK || retval == JIM_CONTINUE || retval == JIM_BREAK) {
+ Jim_SetEmptyResult(interp);
+ return JIM_OK;
+ }
+ return retval;
+}
+
+typedef struct {
+ Jim_Obj *objPtr;
+ int idx;
+} Jim_ListIter;
+
+static void JimListIterInit(Jim_ListIter *iter, Jim_Obj *objPtr)
+{
+ iter->objPtr = objPtr;
+ iter->idx = 0;
+}
+
+static Jim_Obj *JimListIterNext(Jim_Interp *interp, Jim_ListIter *iter)
+{
+ if (iter->idx >= Jim_ListLength(interp, iter->objPtr)) {
+ return NULL;
+ }
+ return iter->objPtr->internalRep.listValue.ele[iter->idx++];
+}
+
+static int JimListIterDone(Jim_Interp *interp, Jim_ListIter *iter)
+{
+ return iter->idx >= Jim_ListLength(interp, iter->objPtr);
+}
+
+
+static int JimForeachMapHelper(Jim_Interp *interp, int argc, Jim_Obj *const *argv, int doMap)
+{
+ int result = JIM_OK;
+ int i, numargs;
+ Jim_ListIter twoiters[2];
+ Jim_ListIter *iters;
+ Jim_Obj *script;
+ Jim_Obj *resultObj;
+
+ if (argc < 4 || argc % 2 != 0) {
+ Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
+ return JIM_ERR;
+ }
+ script = argv[argc - 1];
+ numargs = (argc - 1 - 1);
+
+ if (numargs == 2) {
+ iters = twoiters;
+ }
+ else {
+ iters = Jim_Alloc(numargs * sizeof(*iters));
+ }
+ for (i = 0; i < numargs; i++) {
+ JimListIterInit(&iters[i], argv[i + 1]);
+ if (i % 2 == 0 && JimListIterDone(interp, &iters[i])) {
+ result = JIM_ERR;
+ }
+ }
+ if (result != JIM_OK) {
+ Jim_SetResultString(interp, "foreach varlist is empty", -1);
+ goto empty_varlist;
+ }
+
+ if (doMap) {
+ resultObj = Jim_NewListObj(interp, NULL, 0);
+ }
+ else {
+ resultObj = interp->emptyObj;
+ }
+ Jim_IncrRefCount(resultObj);
+
+ while (1) {
+
+ for (i = 0; i < numargs; i += 2) {
+ if (!JimListIterDone(interp, &iters[i + 1])) {
+ break;
+ }
+ }
+ if (i == numargs) {
+
+ break;
+ }
+
+
+ for (i = 0; i < numargs; i += 2) {
+ Jim_Obj *varName;
+
+
+ JimListIterInit(&iters[i], argv[i + 1]);
+ while ((varName = JimListIterNext(interp, &iters[i])) != NULL) {
+ Jim_Obj *valObj = JimListIterNext(interp, &iters[i + 1]);
+ if (!valObj) {
+
+ valObj = interp->emptyObj;
+ }
+
+ Jim_IncrRefCount(valObj);
+ result = Jim_SetVariable(interp, varName, valObj);
+ Jim_DecrRefCount(interp, valObj);
+ if (result != JIM_OK) {
+ goto err;
+ }
+ }
+ }
+ switch (result = Jim_EvalObj(interp, script)) {
+ case JIM_OK:
+ if (doMap) {
+ Jim_ListAppendElement(interp, resultObj, interp->result);
+ }
+ break;
+ case JIM_CONTINUE:
+ break;
+ case JIM_BREAK:
+ goto out;
+ default:
+ goto err;
+ }
+ }
+ out:
+ result = JIM_OK;
+ Jim_SetResult(interp, resultObj);
+ err:
+ Jim_DecrRefCount(interp, resultObj);
+ empty_varlist:
+ if (numargs > 2) {
+ Jim_Free(iters);
+ }
+ return result;
+}
+
+
+static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return JimForeachMapHelper(interp, argc, argv, 0);
+}
+
+
+static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ return JimForeachMapHelper(interp, argc, argv, 1);
+}
+
+
+static int Jim_LassignCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int result = JIM_ERR;
+ int i;
+ Jim_ListIter iter;
+ Jim_Obj *resultObj;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "varList list ?varName ...?");
+ return JIM_ERR;
+ }
+
+ JimListIterInit(&iter, argv[1]);
+
+ for (i = 2; i < argc; i++) {
+ Jim_Obj *valObj = JimListIterNext(interp, &iter);
+ result = Jim_SetVariable(interp, argv[i], valObj ? valObj : interp->emptyObj);
+ if (result != JIM_OK) {
+ return result;
+ }
+ }
+
+ resultObj = Jim_NewListObj(interp, NULL, 0);
+ while (!JimListIterDone(interp, &iter)) {
+ Jim_ListAppendElement(interp, resultObj, JimListIterNext(interp, &iter));
+ }
+
+ Jim_SetResult(interp, resultObj);
+
+ return JIM_OK;
+}
+
+
+static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int boolean, retval, current = 1, falsebody = 0;
+
+ if (argc >= 3) {
+ while (1) {
+
+ if (current >= argc)
+ goto err;
+ if ((retval = Jim_GetBoolFromExpr(interp, argv[current++], &boolean))
+ != JIM_OK)
+ return retval;
+
+ if (current >= argc)
+ goto err;
+ if (Jim_CompareStringImmediate(interp, argv[current], "then"))
+ current++;
+
+ if (current >= argc)
+ goto err;
+ if (boolean)
+ return Jim_EvalObj(interp, argv[current]);
+
+ if (++current >= argc) {
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+ return JIM_OK;
+ }
+ falsebody = current++;
+ if (Jim_CompareStringImmediate(interp, argv[falsebody], "else")) {
+
+ if (current != argc - 1)
+ goto err;
+ return Jim_EvalObj(interp, argv[current]);
+ }
+ else if (Jim_CompareStringImmediate(interp, argv[falsebody], "elseif"))
+ continue;
+
+ else if (falsebody != argc - 1)
+ goto err;
+ return Jim_EvalObj(interp, argv[falsebody]);
+ }
+ return JIM_OK;
+ }
+ err:
+ Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
+ return JIM_ERR;
+}
+
+
+
+int Jim_CommandMatchObj(Jim_Interp *interp, Jim_Obj *commandObj, Jim_Obj *patternObj,
+ Jim_Obj *stringObj, int nocase)
+{
+ Jim_Obj *parms[4];
+ int argc = 0;
+ long eq;
+ int rc;
+
+ parms[argc++] = commandObj;
+ if (nocase) {
+ parms[argc++] = Jim_NewStringObj(interp, "-nocase", -1);
+ }
+ parms[argc++] = patternObj;
+ parms[argc++] = stringObj;
+
+ rc = Jim_EvalObjVector(interp, argc, parms);
+
+ if (rc != JIM_OK || Jim_GetLong(interp, Jim_GetResult(interp), &eq) != JIM_OK) {
+ eq = -rc;
+ }
+
+ return eq;
+}
+
+
+static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ enum { SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD };
+ int matchOpt = SWITCH_EXACT, opt = 1, patCount, i;
+ Jim_Obj *command = NULL, *scriptObj = NULL, *strObj;
+ Jim_Obj **caseList;
+
+ if (argc < 3) {
+ wrongnumargs:
+ Jim_WrongNumArgs(interp, 1, argv, "?options? string "
+ "pattern body ... ?default body? or " "{pattern body ?pattern body ...?}");
+ return JIM_ERR;
+ }
+ for (opt = 1; opt < argc; ++opt) {
+ const char *option = Jim_String(argv[opt]);
+
+ if (*option != '-')
+ break;
+ else if (strncmp(option, "--", 2) == 0) {
+ ++opt;
+ break;
+ }
+ else if (strncmp(option, "-exact", 2) == 0)
+ matchOpt = SWITCH_EXACT;
+ else if (strncmp(option, "-glob", 2) == 0)
+ matchOpt = SWITCH_GLOB;
+ else if (strncmp(option, "-regexp", 2) == 0)
+ matchOpt = SWITCH_RE;
+ else if (strncmp(option, "-command", 2) == 0) {
+ matchOpt = SWITCH_CMD;
+ if ((argc - opt) < 2)
+ goto wrongnumargs;
+ command = argv[++opt];
+ }
+ else {
+ Jim_SetResultFormatted(interp,
+ "bad option \"%#s\": must be -exact, -glob, -regexp, -command procname or --",
+ argv[opt]);
+ return JIM_ERR;
+ }
+ if ((argc - opt) < 2)
+ goto wrongnumargs;
+ }
+ strObj = argv[opt++];
+ patCount = argc - opt;
+ if (patCount == 1) {
+ JimListGetElements(interp, argv[opt], &patCount, &caseList);
+ }
+ else
+ caseList = (Jim_Obj **)&argv[opt];
+ if (patCount == 0 || patCount % 2 != 0)
+ goto wrongnumargs;
+ for (i = 0; scriptObj == NULL && i < patCount; i += 2) {
+ Jim_Obj *patObj = caseList[i];
+
+ if (!Jim_CompareStringImmediate(interp, patObj, "default")
+ || i < (patCount - 2)) {
+ switch (matchOpt) {
+ case SWITCH_EXACT:
+ if (Jim_StringEqObj(strObj, patObj))
+ scriptObj = caseList[i + 1];
+ break;
+ case SWITCH_GLOB:
+ if (Jim_StringMatchObj(interp, patObj, strObj, 0))
+ scriptObj = caseList[i + 1];
+ break;
+ case SWITCH_RE:
+ command = Jim_NewStringObj(interp, "regexp", -1);
+
+ case SWITCH_CMD:{
+ int rc = Jim_CommandMatchObj(interp, command, patObj, strObj, 0);
+
+ if (argc - opt == 1) {
+ JimListGetElements(interp, argv[opt], &patCount, &caseList);
+ }
+
+ if (rc < 0) {
+ return -rc;
+ }
+ if (rc)
+ scriptObj = caseList[i + 1];
+ break;
+ }
+ }
+ }
+ else {
+ scriptObj = caseList[i + 1];
+ }
+ }
+ for (; i < patCount && Jim_CompareStringImmediate(interp, scriptObj, "-"); i += 2)
+ scriptObj = caseList[i + 1];
+ if (scriptObj && Jim_CompareStringImmediate(interp, scriptObj, "-")) {
+ Jim_SetResultFormatted(interp, "no body specified for pattern \"%#s\"", caseList[i - 2]);
+ return JIM_ERR;
+ }
+ Jim_SetEmptyResult(interp);
+ if (scriptObj) {
+ return Jim_EvalObj(interp, scriptObj);
+ }
+ return JIM_OK;
+}
+
+
+static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *listObjPtr;
+
+ listObjPtr = Jim_NewListObj(interp, argv + 1, argc - 1);
+ Jim_SetResult(interp, listObjPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr, *listObjPtr;
+ int i;
+ int idx;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "list ?index ...?");
+ return JIM_ERR;
+ }
+ objPtr = argv[1];
+ Jim_IncrRefCount(objPtr);
+ for (i = 2; i < argc; i++) {
+ listObjPtr = objPtr;
+ if (Jim_GetIndex(interp, argv[i], &idx) != JIM_OK) {
+ Jim_DecrRefCount(interp, listObjPtr);
+ return JIM_ERR;
+ }
+ if (Jim_ListIndex(interp, listObjPtr, idx, &objPtr, JIM_NONE) != JIM_OK) {
+ Jim_DecrRefCount(interp, listObjPtr);
+ Jim_SetEmptyResult(interp);
+ return JIM_OK;
+ }
+ Jim_IncrRefCount(objPtr);
+ Jim_DecrRefCount(interp, listObjPtr);
+ }
+ Jim_SetResult(interp, objPtr);
+ Jim_DecrRefCount(interp, objPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "list");
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, Jim_ListLength(interp, argv[1]));
+ return JIM_OK;
+}
+
+
+static int Jim_LsearchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ static const char * const options[] = {
+ "-bool", "-not", "-nocase", "-exact", "-glob", "-regexp", "-all", "-inline", "-command",
+ NULL
+ };
+ enum
+ { OPT_BOOL, OPT_NOT, OPT_NOCASE, OPT_EXACT, OPT_GLOB, OPT_REGEXP, OPT_ALL, OPT_INLINE,
+ OPT_COMMAND };
+ int i;
+ int opt_bool = 0;
+ int opt_not = 0;
+ int opt_nocase = 0;
+ int opt_all = 0;
+ int opt_inline = 0;
+ int opt_match = OPT_EXACT;
+ int listlen;
+ int rc = JIM_OK;
+ Jim_Obj *listObjPtr = NULL;
+ Jim_Obj *commandObj = NULL;
+
+ if (argc < 3) {
+ wrongargs:
+ Jim_WrongNumArgs(interp, 1, argv,
+ "?-exact|-glob|-regexp|-command 'command'? ?-bool|-inline? ?-not? ?-nocase? ?-all? list value");
+ return JIM_ERR;
+ }
+
+ for (i = 1; i < argc - 2; i++) {
+ int option;
+
+ if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ERRMSG) != JIM_OK) {
+ return JIM_ERR;
+ }
+ switch (option) {
+ case OPT_BOOL:
+ opt_bool = 1;
+ opt_inline = 0;
+ break;
+ case OPT_NOT:
+ opt_not = 1;
+ break;
+ case OPT_NOCASE:
+ opt_nocase = 1;
+ break;
+ case OPT_INLINE:
+ opt_inline = 1;
+ opt_bool = 0;
+ break;
+ case OPT_ALL:
+ opt_all = 1;
+ break;
+ case OPT_COMMAND:
+ if (i >= argc - 2) {
+ goto wrongargs;
+ }
+ commandObj = argv[++i];
+
+ case OPT_EXACT:
+ case OPT_GLOB:
+ case OPT_REGEXP:
+ opt_match = option;
+ break;
+ }
+ }
+
+ argv += i;
+
+ if (opt_all) {
+ listObjPtr = Jim_NewListObj(interp, NULL, 0);
+ }
+ if (opt_match == OPT_REGEXP) {
+ commandObj = Jim_NewStringObj(interp, "regexp", -1);
+ }
+ if (commandObj) {
+ Jim_IncrRefCount(commandObj);
+ }
+
+ listlen = Jim_ListLength(interp, argv[0]);
+ for (i = 0; i < listlen; i++) {
+ int eq = 0;
+ Jim_Obj *objPtr = Jim_ListGetIndex(interp, argv[0], i);
+
+ switch (opt_match) {
+ case OPT_EXACT:
+ eq = Jim_StringCompareObj(interp, argv[1], objPtr, opt_nocase) == 0;
+ break;
+
+ case OPT_GLOB:
+ eq = Jim_StringMatchObj(interp, argv[1], objPtr, opt_nocase);
+ break;
+
+ case OPT_REGEXP:
+ case OPT_COMMAND:
+ eq = Jim_CommandMatchObj(interp, commandObj, argv[1], objPtr, opt_nocase);
+ if (eq < 0) {
+ if (listObjPtr) {
+ Jim_FreeNewObj(interp, listObjPtr);
+ }
+ rc = JIM_ERR;
+ goto done;
+ }
+ break;
+ }
+
+
+ if (!eq && opt_bool && opt_not && !opt_all) {
+ continue;
+ }
+
+ if ((!opt_bool && eq == !opt_not) || (opt_bool && (eq || opt_all))) {
+
+ Jim_Obj *resultObj;
+
+ if (opt_bool) {
+ resultObj = Jim_NewIntObj(interp, eq ^ opt_not);
+ }
+ else if (!opt_inline) {
+ resultObj = Jim_NewIntObj(interp, i);
+ }
+ else {
+ resultObj = objPtr;
+ }
+
+ if (opt_all) {
+ Jim_ListAppendElement(interp, listObjPtr, resultObj);
+ }
+ else {
+ Jim_SetResult(interp, resultObj);
+ goto done;
+ }
+ }
+ }
+
+ if (opt_all) {
+ Jim_SetResult(interp, listObjPtr);
+ }
+ else {
+
+ if (opt_bool) {
+ Jim_SetResultBool(interp, opt_not);
+ }
+ else if (!opt_inline) {
+ Jim_SetResultInt(interp, -1);
+ }
+ }
+
+ done:
+ if (commandObj) {
+ Jim_DecrRefCount(interp, commandObj);
+ }
+ return rc;
+}
+
+
+static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *listObjPtr;
+ int new_obj = 0;
+ int i;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
+ return JIM_ERR;
+ }
+ listObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
+ if (!listObjPtr) {
+
+ listObjPtr = Jim_NewListObj(interp, NULL, 0);
+ new_obj = 1;
+ }
+ else if (Jim_IsShared(listObjPtr)) {
+ listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
+ new_obj = 1;
+ }
+ for (i = 2; i < argc; i++)
+ Jim_ListAppendElement(interp, listObjPtr, argv[i]);
+ if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
+ if (new_obj)
+ Jim_FreeNewObj(interp, listObjPtr);
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, listObjPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int idx, len;
+ Jim_Obj *listPtr;
+
+ if (argc < 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "list index ?element ...?");
+ return JIM_ERR;
+ }
+ listPtr = argv[1];
+ if (Jim_IsShared(listPtr))
+ listPtr = Jim_DuplicateObj(interp, listPtr);
+ if (Jim_GetIndex(interp, argv[2], &idx) != JIM_OK)
+ goto err;
+ len = Jim_ListLength(interp, listPtr);
+ if (idx >= len)
+ idx = len;
+ else if (idx < 0)
+ idx = len + idx + 1;
+ Jim_ListInsertElements(interp, listPtr, idx, argc - 3, &argv[3]);
+ Jim_SetResult(interp, listPtr);
+ return JIM_OK;
+ err:
+ if (listPtr != argv[1]) {
+ Jim_FreeNewObj(interp, listPtr);
+ }
+ return JIM_ERR;
+}
+
+
+static int Jim_LreplaceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int first, last, len, rangeLen;
+ Jim_Obj *listObj;
+ Jim_Obj *newListObj;
+
+ if (argc < 4) {
+ Jim_WrongNumArgs(interp, 1, argv, "list first last ?element ...?");
+ return JIM_ERR;
+ }
+ if (Jim_GetIndex(interp, argv[2], &first) != JIM_OK ||
+ Jim_GetIndex(interp, argv[3], &last) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ listObj = argv[1];
+ len = Jim_ListLength(interp, listObj);
+
+ first = JimRelToAbsIndex(len, first);
+ last = JimRelToAbsIndex(len, last);
+ JimRelToAbsRange(len, &first, &last, &rangeLen);
+
+
+ if (first > len) {
+ first = len;
+ }
+
+
+ newListObj = Jim_NewListObj(interp, listObj->internalRep.listValue.ele, first);
+
+
+ ListInsertElements(newListObj, -1, argc - 4, argv + 4);
+
+
+ ListInsertElements(newListObj, -1, len - first - rangeLen, listObj->internalRep.listValue.ele + first + rangeLen);
+
+ Jim_SetResult(interp, newListObj);
+ return JIM_OK;
+}
+
+
+static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc < 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");
+ return JIM_ERR;
+ }
+ else if (argc == 3) {
+
+ if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
+ return JIM_ERR;
+ Jim_SetResult(interp, argv[2]);
+ return JIM_OK;
+ }
+ return Jim_ListSetIndex(interp, argv[1], argv + 2, argc - 3, argv[argc - 1]);
+}
+
+
+static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
+{
+ static const char * const options[] = {
+ "-ascii", "-nocase", "-increasing", "-decreasing", "-command", "-integer", "-real", "-index", "-unique", NULL
+ };
+ enum
+ { OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING, OPT_COMMAND, OPT_INTEGER, OPT_REAL, OPT_INDEX, OPT_UNIQUE };
+ Jim_Obj *resObj;
+ int i;
+ int retCode;
+ int shared;
+
+ struct lsort_info info;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "?options? list");
+ return JIM_ERR;
+ }
+
+ info.type = JIM_LSORT_ASCII;
+ info.order = 1;
+ info.indexed = 0;
+ info.unique = 0;
+ info.command = NULL;
+ info.interp = interp;
+
+ for (i = 1; i < (argc - 1); i++) {
+ int option;
+
+ if (Jim_GetEnum(interp, argv[i], options, &option, NULL, JIM_ENUM_ABBREV | JIM_ERRMSG)
+ != JIM_OK)
+ return JIM_ERR;
+ switch (option) {
+ case OPT_ASCII:
+ info.type = JIM_LSORT_ASCII;
+ break;
+ case OPT_NOCASE:
+ info.type = JIM_LSORT_NOCASE;
+ break;
+ case OPT_INTEGER:
+ info.type = JIM_LSORT_INTEGER;
+ break;
+ case OPT_REAL:
+ info.type = JIM_LSORT_REAL;
+ break;
+ case OPT_INCREASING:
+ info.order = 1;
+ break;
+ case OPT_DECREASING:
+ info.order = -1;
+ break;
+ case OPT_UNIQUE:
+ info.unique = 1;
+ break;
+ case OPT_COMMAND:
+ if (i >= (argc - 2)) {
+ Jim_SetResultString(interp, "\"-command\" option must be followed by comparison command", -1);
+ return JIM_ERR;
+ }
+ info.type = JIM_LSORT_COMMAND;
+ info.command = argv[i + 1];
+ i++;
+ break;
+ case OPT_INDEX:
+ if (i >= (argc - 2)) {
+ Jim_SetResultString(interp, "\"-index\" option must be followed by list index", -1);
+ return JIM_ERR;
+ }
+ if (Jim_GetIndex(interp, argv[i + 1], &info.index) != JIM_OK) {
+ return JIM_ERR;
+ }
+ info.indexed = 1;
+ i++;
+ break;
+ }
+ }
+ resObj = argv[argc - 1];
+ if ((shared = Jim_IsShared(resObj)))
+ resObj = Jim_DuplicateObj(interp, resObj);
+ retCode = ListSortElements(interp, resObj, &info);
+ if (retCode == JIM_OK) {
+ Jim_SetResult(interp, resObj);
+ }
+ else if (shared) {
+ Jim_FreeNewObj(interp, resObj);
+ }
+ return retCode;
+}
+
+
+static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *stringObjPtr;
+ int i;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?value ...?");
+ return JIM_ERR;
+ }
+ if (argc == 2) {
+ stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+ if (!stringObjPtr)
+ return JIM_ERR;
+ }
+ else {
+ int new_obj = 0;
+ stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_UNSHARED);
+ if (!stringObjPtr) {
+
+ stringObjPtr = Jim_NewEmptyStringObj(interp);
+ new_obj = 1;
+ }
+ else if (Jim_IsShared(stringObjPtr)) {
+ new_obj = 1;
+ stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
+ }
+ for (i = 2; i < argc; i++) {
+ Jim_AppendObj(interp, stringObjPtr, argv[i]);
+ }
+ if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
+ if (new_obj) {
+ Jim_FreeNewObj(interp, stringObjPtr);
+ }
+ return JIM_ERR;
+ }
+ }
+ Jim_SetResult(interp, stringObjPtr);
+ return JIM_OK;
+}
+
+
+
+static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+#if !defined(JIM_DEBUG_COMMAND)
+ Jim_SetResultString(interp, "unsupported", -1);
+ return JIM_ERR;
+#endif
+}
+
+
+static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int rc;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "arg ?arg ...?");
+ return JIM_ERR;
+ }
+
+ if (argc == 2) {
+ rc = Jim_EvalObj(interp, argv[1]);
+ }
+ else {
+ rc = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
+ }
+
+ if (rc == JIM_ERR) {
+
+ interp->addStackTrace++;
+ }
+ return rc;
+}
+
+
+static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc >= 2) {
+ int retcode;
+ Jim_CallFrame *savedCallFrame, *targetCallFrame;
+ const char *str;
+
+
+ savedCallFrame = interp->framePtr;
+
+
+ str = Jim_String(argv[1]);
+ if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#') {
+ targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
+ argc--;
+ argv++;
+ }
+ else {
+ targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
+ }
+ if (targetCallFrame == NULL) {
+ return JIM_ERR;
+ }
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv - 1, "?level? command ?arg ...?");
+ return JIM_ERR;
+ }
+
+ interp->framePtr = targetCallFrame;
+ if (argc == 2) {
+ retcode = Jim_EvalObj(interp, argv[1]);
+ }
+ else {
+ retcode = Jim_EvalObj(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
+ }
+ interp->framePtr = savedCallFrame;
+ return retcode;
+ }
+ else {
+ Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
+ return JIM_ERR;
+ }
+}
+
+
+static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int retcode;
+
+ if (argc == 2) {
+ retcode = Jim_EvalExpression(interp, argv[1]);
+ }
+ else if (argc > 2) {
+ Jim_Obj *objPtr;
+
+ objPtr = Jim_ConcatObj(interp, argc - 1, argv + 1);
+ Jim_IncrRefCount(objPtr);
+ retcode = Jim_EvalExpression(interp, objPtr);
+ Jim_DecrRefCount(interp, objPtr);
+ }
+ else {
+ Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
+ return JIM_ERR;
+ }
+ if (retcode != JIM_OK)
+ return retcode;
+ return JIM_OK;
+}
+
+
+static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 1) {
+ Jim_WrongNumArgs(interp, 1, argv, "");
+ return JIM_ERR;
+ }
+ return JIM_BREAK;
+}
+
+
+static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 1) {
+ Jim_WrongNumArgs(interp, 1, argv, "");
+ return JIM_ERR;
+ }
+ return JIM_CONTINUE;
+}
+
+
+static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int i;
+ Jim_Obj *stackTraceObj = NULL;
+ Jim_Obj *errorCodeObj = NULL;
+ int returnCode = JIM_OK;
+ long level = 1;
+
+ for (i = 1; i < argc - 1; i += 2) {
+ if (Jim_CompareStringImmediate(interp, argv[i], "-code")) {
+ if (Jim_GetReturnCode(interp, argv[i + 1], &returnCode) == JIM_ERR) {
+ return JIM_ERR;
+ }
+ }
+ else if (Jim_CompareStringImmediate(interp, argv[i], "-errorinfo")) {
+ stackTraceObj = argv[i + 1];
+ }
+ else if (Jim_CompareStringImmediate(interp, argv[i], "-errorcode")) {
+ errorCodeObj = argv[i + 1];
+ }
+ else if (Jim_CompareStringImmediate(interp, argv[i], "-level")) {
+ if (Jim_GetLong(interp, argv[i + 1], &level) != JIM_OK || level < 0) {
+ Jim_SetResultFormatted(interp, "bad level \"%#s\"", argv[i + 1]);
+ return JIM_ERR;
+ }
+ }
+ else {
+ break;
+ }
+ }
+
+ if (i != argc - 1 && i != argc) {
+ Jim_WrongNumArgs(interp, 1, argv,
+ "?-code code? ?-errorinfo stacktrace? ?-level level? ?result?");
+ }
+
+
+ if (stackTraceObj && returnCode == JIM_ERR) {
+ JimSetStackTrace(interp, stackTraceObj);
+ }
+
+ if (errorCodeObj && returnCode == JIM_ERR) {
+ Jim_SetGlobalVariableStr(interp, "errorCode", errorCodeObj);
+ }
+ interp->returnCode = returnCode;
+ interp->returnLevel = level;
+
+ if (i == argc - 1) {
+ Jim_SetResult(interp, argv[i]);
+ }
+ return JIM_RETURN;
+}
+
+
+static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (interp->framePtr->level == 0) {
+ Jim_SetResultString(interp, "tailcall can only be called from a proc or lambda", -1);
+ return JIM_ERR;
+ }
+ else if (argc >= 2) {
+
+ Jim_CallFrame *cf = interp->framePtr->parent;
+
+ Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
+ if (cmdPtr == NULL) {
+ return JIM_ERR;
+ }
+
+ JimPanic((cf->tailcallCmd != NULL, "Already have a tailcallCmd"));
+
+
+ JimIncrCmdRefCount(cmdPtr);
+ cf->tailcallCmd = cmdPtr;
+
+
+ JimPanic((cf->tailcallObj != NULL, "Already have a tailcallobj"));
+
+ cf->tailcallObj = Jim_NewListObj(interp, argv + 1, argc - 1);
+ Jim_IncrRefCount(cf->tailcallObj);
+
+
+ return JIM_EVAL;
+ }
+ return JIM_OK;
+}
+
+static int JimAliasCmd(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *cmdList;
+ Jim_Obj *prefixListObj = Jim_CmdPrivData(interp);
+
+
+ cmdList = Jim_DuplicateObj(interp, prefixListObj);
+ Jim_ListInsertElements(interp, cmdList, Jim_ListLength(interp, cmdList), argc - 1, argv + 1);
+
+ return JimEvalObjList(interp, cmdList);
+}
+
+static void JimAliasCmdDelete(Jim_Interp *interp, void *privData)
+{
+ Jim_Obj *prefixListObj = privData;
+ Jim_DecrRefCount(interp, prefixListObj);
+}
+
+static int Jim_AliasCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *prefixListObj;
+ const char *newname;
+
+ if (argc < 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "newname command ?args ...?");
+ return JIM_ERR;
+ }
+
+ prefixListObj = Jim_NewListObj(interp, argv + 2, argc - 2);
+ Jim_IncrRefCount(prefixListObj);
+ newname = Jim_String(argv[1]);
+ if (newname[0] == ':' && newname[1] == ':') {
+ while (*++newname == ':') {
+ }
+ }
+
+ Jim_SetResult(interp, argv[1]);
+
+ return Jim_CreateCommand(interp, newname, JimAliasCmd, prefixListObj, JimAliasCmdDelete);
+}
+
+
+static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Cmd *cmd;
+
+ if (argc != 4 && argc != 5) {
+ Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
+ return JIM_ERR;
+ }
+
+ if (JimValidName(interp, "procedure", argv[1]) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ if (argc == 4) {
+ cmd = JimCreateProcedureCmd(interp, argv[2], NULL, argv[3], NULL);
+ }
+ else {
+ cmd = JimCreateProcedureCmd(interp, argv[2], argv[3], argv[4], NULL);
+ }
+
+ if (cmd) {
+
+ Jim_Obj *qualifiedCmdNameObj;
+ const char *cmdname = JimQualifyName(interp, Jim_String(argv[1]), &qualifiedCmdNameObj);
+
+ JimCreateCommand(interp, cmdname, cmd);
+
+
+ JimUpdateProcNamespace(interp, cmd, cmdname);
+
+ JimFreeQualifiedName(interp, qualifiedCmdNameObj);
+
+
+ Jim_SetResult(interp, argv[1]);
+ return JIM_OK;
+ }
+ return JIM_ERR;
+}
+
+
+static int Jim_LocalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int retcode;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
+ return JIM_ERR;
+ }
+
+
+ interp->local++;
+ retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
+ interp->local--;
+
+
+
+ if (retcode == 0) {
+ Jim_Obj *cmdNameObj = Jim_GetResult(interp);
+
+ if (Jim_GetCommand(interp, cmdNameObj, JIM_ERRMSG) == NULL) {
+ return JIM_ERR;
+ }
+ if (interp->framePtr->localCommands == NULL) {
+ interp->framePtr->localCommands = Jim_Alloc(sizeof(*interp->framePtr->localCommands));
+ Jim_InitStack(interp->framePtr->localCommands);
+ }
+ Jim_IncrRefCount(cmdNameObj);
+ Jim_StackPush(interp->framePtr->localCommands, cmdNameObj);
+ }
+
+ return retcode;
+}
+
+
+static int Jim_UpcallCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "cmd ?args ...?");
+ return JIM_ERR;
+ }
+ else {
+ int retcode;
+
+ Jim_Cmd *cmdPtr = Jim_GetCommand(interp, argv[1], JIM_ERRMSG);
+ if (cmdPtr == NULL || !cmdPtr->isproc || !cmdPtr->prevCmd) {
+ Jim_SetResultFormatted(interp, "no previous command: \"%#s\"", argv[1]);
+ return JIM_ERR;
+ }
+
+ cmdPtr->u.proc.upcall++;
+ JimIncrCmdRefCount(cmdPtr);
+
+
+ retcode = Jim_EvalObjVector(interp, argc - 1, argv + 1);
+
+
+ cmdPtr->u.proc.upcall--;
+ JimDecrCmdRefCount(interp, cmdPtr);
+
+ return retcode;
+ }
+}
+
+
+static int Jim_ApplyCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "lambdaExpr ?arg ...?");
+ return JIM_ERR;
+ }
+ else {
+ int ret;
+ Jim_Cmd *cmd;
+ Jim_Obj *argListObjPtr;
+ Jim_Obj *bodyObjPtr;
+ Jim_Obj *nsObj = NULL;
+ Jim_Obj **nargv;
+
+ int len = Jim_ListLength(interp, argv[1]);
+ if (len != 2 && len != 3) {
+ Jim_SetResultFormatted(interp, "can't interpret \"%#s\" as a lambda expression", argv[1]);
+ return JIM_ERR;
+ }
+
+ if (len == 3) {
+#ifdef jim_ext_namespace
+
+ nsObj = JimQualifyNameObj(interp, Jim_ListGetIndex(interp, argv[1], 2));
+#else
+ Jim_SetResultString(interp, "namespaces not enabled", -1);
+ return JIM_ERR;
+#endif
+ }
+ argListObjPtr = Jim_ListGetIndex(interp, argv[1], 0);
+ bodyObjPtr = Jim_ListGetIndex(interp, argv[1], 1);
+
+ cmd = JimCreateProcedureCmd(interp, argListObjPtr, NULL, bodyObjPtr, nsObj);
+
+ if (cmd) {
+
+ nargv = Jim_Alloc((argc - 2 + 1) * sizeof(*nargv));
+ nargv[0] = Jim_NewStringObj(interp, "apply lambdaExpr", -1);
+ Jim_IncrRefCount(nargv[0]);
+ memcpy(&nargv[1], argv + 2, (argc - 2) * sizeof(*nargv));
+ ret = JimCallProcedure(interp, cmd, argc - 2 + 1, nargv);
+ Jim_DecrRefCount(interp, nargv[0]);
+ Jim_Free(nargv);
+
+ JimDecrCmdRefCount(interp, cmd);
+ return ret;
+ }
+ return JIM_ERR;
+ }
+}
+
+
+
+static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_SetResult(interp, Jim_ConcatObj(interp, argc - 1, argv + 1));
+ return JIM_OK;
+}
+
+
+static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int i;
+ Jim_CallFrame *targetCallFrame;
+
+
+ if (argc > 3 && (argc % 2 == 0)) {
+ targetCallFrame = Jim_GetCallFrameByLevel(interp, argv[1]);
+ argc--;
+ argv++;
+ }
+ else {
+ targetCallFrame = Jim_GetCallFrameByLevel(interp, NULL);
+ }
+ if (targetCallFrame == NULL) {
+ return JIM_ERR;
+ }
+
+
+ if (argc < 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
+ return JIM_ERR;
+ }
+
+
+ for (i = 1; i < argc; i += 2) {
+ if (Jim_SetVariableLink(interp, argv[i + 1], argv[i], targetCallFrame) != JIM_OK)
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+
+static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int i;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
+ return JIM_ERR;
+ }
+
+ if (interp->framePtr->level == 0)
+ return JIM_OK;
+ for (i = 1; i < argc; i++) {
+
+ const char *name = Jim_String(argv[i]);
+ if (name[0] != ':' || name[1] != ':') {
+ if (Jim_SetVariableLink(interp, argv[i], argv[i], interp->topFramePtr) != JIM_OK)
+ return JIM_ERR;
+ }
+ }
+ return JIM_OK;
+}
+
+static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
+ Jim_Obj *objPtr, int nocase)
+{
+ int numMaps;
+ const char *str, *noMatchStart = NULL;
+ int strLen, i;
+ Jim_Obj *resultObjPtr;
+
+ numMaps = Jim_ListLength(interp, mapListObjPtr);
+ if (numMaps % 2) {
+ Jim_SetResultString(interp, "list must contain an even number of elements", -1);
+ return NULL;
+ }
+
+ str = Jim_String(objPtr);
+ strLen = Jim_Utf8Length(interp, objPtr);
+
+
+ resultObjPtr = Jim_NewStringObj(interp, "", 0);
+ while (strLen) {
+ for (i = 0; i < numMaps; i += 2) {
+ Jim_Obj *eachObjPtr;
+ const char *k;
+ int kl;
+
+ eachObjPtr = Jim_ListGetIndex(interp, mapListObjPtr, i);
+ k = Jim_String(eachObjPtr);
+ kl = Jim_Utf8Length(interp, eachObjPtr);
+
+ if (strLen >= kl && kl) {
+ int rc;
+ rc = JimStringCompareLen(str, k, kl, nocase);
+ if (rc == 0) {
+ if (noMatchStart) {
+ Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
+ noMatchStart = NULL;
+ }
+ Jim_AppendObj(interp, resultObjPtr, Jim_ListGetIndex(interp, mapListObjPtr, i + 1));
+ str += utf8_index(str, kl);
+ strLen -= kl;
+ break;
+ }
+ }
+ }
+ if (i == numMaps) {
+ int c;
+ if (noMatchStart == NULL)
+ noMatchStart = str;
+ str += utf8_tounicode(str, &c);
+ strLen--;
+ }
+ }
+ if (noMatchStart) {
+ Jim_AppendString(interp, resultObjPtr, noMatchStart, str - noMatchStart);
+ }
+ return resultObjPtr;
+}
+
+
+static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int len;
+ int opt_case = 1;
+ int option;
+ static const char * const options[] = {
+ "bytelength", "length", "compare", "match", "equal", "is", "byterange", "range", "replace",
+ "map", "repeat", "reverse", "index", "first", "last", "cat",
+ "trim", "trimleft", "trimright", "tolower", "toupper", "totitle", NULL
+ };
+ enum
+ {
+ OPT_BYTELENGTH, OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_IS, OPT_BYTERANGE, OPT_RANGE, OPT_REPLACE,
+ OPT_MAP, OPT_REPEAT, OPT_REVERSE, OPT_INDEX, OPT_FIRST, OPT_LAST, OPT_CAT,
+ OPT_TRIM, OPT_TRIMLEFT, OPT_TRIMRIGHT, OPT_TOLOWER, OPT_TOUPPER, OPT_TOTITLE
+ };
+ static const char * const nocase_options[] = {
+ "-nocase", NULL
+ };
+ static const char * const nocase_length_options[] = {
+ "-nocase", "-length", NULL
+ };
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
+ return JIM_ERR;
+ }
+ if (Jim_GetEnum(interp, argv[1], options, &option, NULL,
+ JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK)
+ return Jim_CheckShowCommands(interp, argv[1], options);
+
+ switch (option) {
+ case OPT_LENGTH:
+ case OPT_BYTELENGTH:
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "string");
+ return JIM_ERR;
+ }
+ if (option == OPT_LENGTH) {
+ len = Jim_Utf8Length(interp, argv[2]);
+ }
+ else {
+ len = Jim_Length(argv[2]);
+ }
+ Jim_SetResultInt(interp, len);
+ return JIM_OK;
+
+ case OPT_CAT:{
+ Jim_Obj *objPtr;
+ if (argc == 3) {
+
+ objPtr = argv[2];
+ }
+ else {
+ int i;
+
+ objPtr = Jim_NewStringObj(interp, "", 0);
+
+ for (i = 2; i < argc; i++) {
+ Jim_AppendObj(interp, objPtr, argv[i]);
+ }
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+
+ case OPT_COMPARE:
+ case OPT_EQUAL:
+ {
+
+ long opt_length = -1;
+ int n = argc - 4;
+ int i = 2;
+ while (n > 0) {
+ int subopt;
+ if (Jim_GetEnum(interp, argv[i++], nocase_length_options, &subopt, NULL,
+ JIM_ENUM_ABBREV) != JIM_OK) {
+badcompareargs:
+ Jim_WrongNumArgs(interp, 2, argv, "?-nocase? ?-length int? string1 string2");
+ return JIM_ERR;
+ }
+ if (subopt == 0) {
+
+ opt_case = 0;
+ n--;
+ }
+ else {
+
+ if (n < 2) {
+ goto badcompareargs;
+ }
+ if (Jim_GetLong(interp, argv[i++], &opt_length) != JIM_OK) {
+ return JIM_ERR;
+ }
+ n -= 2;
+ }
+ }
+ if (n) {
+ goto badcompareargs;
+ }
+ argv += argc - 2;
+ if (opt_length < 0 && option != OPT_COMPARE && opt_case) {
+
+ Jim_SetResultBool(interp, Jim_StringEqObj(argv[0], argv[1]));
+ }
+ else {
+ if (opt_length >= 0) {
+ n = JimStringCompareLen(Jim_String(argv[0]), Jim_String(argv[1]), opt_length, !opt_case);
+ }
+ else {
+ n = Jim_StringCompareObj(interp, argv[0], argv[1], !opt_case);
+ }
+ Jim_SetResultInt(interp, option == OPT_COMPARE ? n : n == 0);
+ }
+ return JIM_OK;
+ }
+
+ case OPT_MATCH:
+ if (argc != 4 &&
+ (argc != 5 ||
+ Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
+ JIM_ENUM_ABBREV) != JIM_OK)) {
+ Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern string");
+ return JIM_ERR;
+ }
+ if (opt_case == 0) {
+ argv++;
+ }
+ Jim_SetResultBool(interp, Jim_StringMatchObj(interp, argv[2], argv[3], !opt_case));
+ return JIM_OK;
+
+ case OPT_MAP:{
+ Jim_Obj *objPtr;
+
+ if (argc != 4 &&
+ (argc != 5 ||
+ Jim_GetEnum(interp, argv[2], nocase_options, &opt_case, NULL,
+ JIM_ENUM_ABBREV) != JIM_OK)) {
+ Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList string");
+ return JIM_ERR;
+ }
+
+ if (opt_case == 0) {
+ argv++;
+ }
+ objPtr = JimStringMap(interp, argv[2], argv[3], !opt_case);
+ if (objPtr == NULL) {
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+
+ case OPT_RANGE:
+ case OPT_BYTERANGE:{
+ Jim_Obj *objPtr;
+
+ if (argc != 5) {
+ Jim_WrongNumArgs(interp, 2, argv, "string first last");
+ return JIM_ERR;
+ }
+ if (option == OPT_RANGE) {
+ objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
+ }
+ else
+ {
+ objPtr = Jim_StringByteRangeObj(interp, argv[2], argv[3], argv[4]);
+ }
+
+ if (objPtr == NULL) {
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+
+ case OPT_REPLACE:{
+ Jim_Obj *objPtr;
+
+ if (argc != 5 && argc != 6) {
+ Jim_WrongNumArgs(interp, 2, argv, "string first last ?string?");
+ return JIM_ERR;
+ }
+ objPtr = JimStringReplaceObj(interp, argv[2], argv[3], argv[4], argc == 6 ? argv[5] : NULL);
+ if (objPtr == NULL) {
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+
+
+ case OPT_REPEAT:{
+ Jim_Obj *objPtr;
+ jim_wide count;
+
+ if (argc != 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "string count");
+ return JIM_ERR;
+ }
+ if (Jim_GetWide(interp, argv[3], &count) != JIM_OK) {
+ return JIM_ERR;
+ }
+ objPtr = Jim_NewStringObj(interp, "", 0);
+ if (count > 0) {
+ while (count--) {
+ Jim_AppendObj(interp, objPtr, argv[2]);
+ }
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+ }
+
+ case OPT_REVERSE:{
+ char *buf, *p;
+ const char *str;
+ int i;
+
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "string");
+ return JIM_ERR;
+ }
+
+ str = Jim_GetString(argv[2], &len);
+ buf = Jim_Alloc(len + 1);
+ p = buf + len;
+ *p = 0;
+ for (i = 0; i < len; ) {
+ int c;
+ int l = utf8_tounicode(str, &c);
+ memcpy(p - l, str, l);
+ p -= l;
+ i += l;
+ str += l;
+ }
+ Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
+ return JIM_OK;
+ }
+
+ case OPT_INDEX:{
+ int idx;
+ const char *str;
+
+ if (argc != 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "string index");
+ return JIM_ERR;
+ }
+ if (Jim_GetIndex(interp, argv[3], &idx) != JIM_OK) {
+ return JIM_ERR;
+ }
+ str = Jim_String(argv[2]);
+ len = Jim_Utf8Length(interp, argv[2]);
+ if (idx != INT_MIN && idx != INT_MAX) {
+ idx = JimRelToAbsIndex(len, idx);
+ }
+ if (idx < 0 || idx >= len || str == NULL) {
+ Jim_SetResultString(interp, "", 0);
+ }
+ else if (len == Jim_Length(argv[2])) {
+
+ Jim_SetResultString(interp, str + idx, 1);
+ }
+ else {
+ int c;
+ int i = utf8_index(str, idx);
+ Jim_SetResultString(interp, str + i, utf8_tounicode(str + i, &c));
+ }
+ return JIM_OK;
+ }
+
+ case OPT_FIRST:
+ case OPT_LAST:{
+ int idx = 0, l1, l2;
+ const char *s1, *s2;
+
+ if (argc != 4 && argc != 5) {
+ Jim_WrongNumArgs(interp, 2, argv, "subString string ?index?");
+ return JIM_ERR;
+ }
+ s1 = Jim_String(argv[2]);
+ s2 = Jim_String(argv[3]);
+ l1 = Jim_Utf8Length(interp, argv[2]);
+ l2 = Jim_Utf8Length(interp, argv[3]);
+ if (argc == 5) {
+ if (Jim_GetIndex(interp, argv[4], &idx) != JIM_OK) {
+ return JIM_ERR;
+ }
+ idx = JimRelToAbsIndex(l2, idx);
+ }
+ else if (option == OPT_LAST) {
+ idx = l2;
+ }
+ if (option == OPT_FIRST) {
+ Jim_SetResultInt(interp, JimStringFirst(s1, l1, s2, l2, idx));
+ }
+ else {
+#ifdef JIM_UTF8
+ Jim_SetResultInt(interp, JimStringLastUtf8(s1, l1, s2, idx));
+#else
+ Jim_SetResultInt(interp, JimStringLast(s1, l1, s2, idx));
+#endif
+ }
+ return JIM_OK;
+ }
+
+ case OPT_TRIM:
+ case OPT_TRIMLEFT:
+ case OPT_TRIMRIGHT:{
+ Jim_Obj *trimchars;
+
+ if (argc != 3 && argc != 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "string ?trimchars?");
+ return JIM_ERR;
+ }
+ trimchars = (argc == 4 ? argv[3] : NULL);
+ if (option == OPT_TRIM) {
+ Jim_SetResult(interp, JimStringTrim(interp, argv[2], trimchars));
+ }
+ else if (option == OPT_TRIMLEFT) {
+ Jim_SetResult(interp, JimStringTrimLeft(interp, argv[2], trimchars));
+ }
+ else if (option == OPT_TRIMRIGHT) {
+ Jim_SetResult(interp, JimStringTrimRight(interp, argv[2], trimchars));
+ }
+ return JIM_OK;
+ }
+
+ case OPT_TOLOWER:
+ case OPT_TOUPPER:
+ case OPT_TOTITLE:
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "string");
+ return JIM_ERR;
+ }
+ if (option == OPT_TOLOWER) {
+ Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
+ }
+ else if (option == OPT_TOUPPER) {
+ Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
+ }
+ else {
+ Jim_SetResult(interp, JimStringToTitle(interp, argv[2]));
+ }
+ return JIM_OK;
+
+ case OPT_IS:
+ if (argc == 4 || (argc == 5 && Jim_CompareStringImmediate(interp, argv[3], "-strict"))) {
+ return JimStringIs(interp, argv[argc - 1], argv[2], argc == 5);
+ }
+ Jim_WrongNumArgs(interp, 2, argv, "class ?-strict? str");
+ return JIM_ERR;
+ }
+ return JIM_OK;
+}
+
+
+static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ long i, count = 1;
+ jim_wide start, elapsed;
+ char buf[60];
+ const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
+ return JIM_ERR;
+ }
+ if (argc == 3) {
+ if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
+ return JIM_ERR;
+ }
+ if (count < 0)
+ return JIM_OK;
+ i = count;
+ start = JimClock();
+ while (i-- > 0) {
+ int retval;
+
+ retval = Jim_EvalObj(interp, argv[1]);
+ if (retval != JIM_OK) {
+ return retval;
+ }
+ }
+ elapsed = JimClock() - start;
+ sprintf(buf, fmt, count == 0 ? 0 : elapsed / count);
+ Jim_SetResultString(interp, buf, -1);
+ return JIM_OK;
+}
+
+
+static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ long exitCode = 0;
+
+ if (argc > 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
+ return JIM_ERR;
+ }
+ if (argc == 2) {
+ if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
+ return JIM_ERR;
+ }
+ interp->exitCode = exitCode;
+ return JIM_EXIT;
+}
+
+
+static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int exitCode = 0;
+ int i;
+ int sig = 0;
+
+
+ jim_wide ignore_mask = (1 << JIM_EXIT) | (1 << JIM_EVAL) | (1 << JIM_SIGNAL);
+ static const int max_ignore_code = sizeof(ignore_mask) * 8;
+
+ Jim_SetGlobalVariableStr(interp, "errorCode", Jim_NewStringObj(interp, "NONE", -1));
+
+ for (i = 1; i < argc - 1; i++) {
+ const char *arg = Jim_String(argv[i]);
+ jim_wide option;
+ int ignore;
+
+
+ if (strcmp(arg, "--") == 0) {
+ i++;
+ break;
+ }
+ if (*arg != '-') {
+ break;
+ }
+
+ if (strncmp(arg, "-no", 3) == 0) {
+ arg += 3;
+ ignore = 1;
+ }
+ else {
+ arg++;
+ ignore = 0;
+ }
+
+ if (Jim_StringToWide(arg, &option, 10) != JIM_OK) {
+ option = -1;
+ }
+ if (option < 0) {
+ option = Jim_FindByName(arg, jimReturnCodes, jimReturnCodesSize);
+ }
+ if (option < 0) {
+ goto wrongargs;
+ }
+
+ if (ignore) {
+ ignore_mask |= ((jim_wide)1 << option);
+ }
+ else {
+ ignore_mask &= (~((jim_wide)1 << option));
+ }
+ }
+
+ argc -= i;
+ if (argc < 1 || argc > 3) {
+ wrongargs:
+ Jim_WrongNumArgs(interp, 1, argv,
+ "?-?no?code ... --? script ?resultVarName? ?optionVarName?");
+ return JIM_ERR;
+ }
+ argv += i;
+
+ if ((ignore_mask & (1 << JIM_SIGNAL)) == 0) {
+ sig++;
+ }
+
+ interp->signal_level += sig;
+ if (Jim_CheckSignal(interp)) {
+
+ exitCode = JIM_SIGNAL;
+ }
+ else {
+ exitCode = Jim_EvalObj(interp, argv[0]);
+
+ interp->errorFlag = 0;
+ }
+ interp->signal_level -= sig;
+
+
+ if (exitCode >= 0 && exitCode < max_ignore_code && (((unsigned jim_wide)1 << exitCode) & ignore_mask)) {
+
+ return exitCode;
+ }
+
+ if (sig && exitCode == JIM_SIGNAL) {
+
+ if (interp->signal_set_result) {
+ interp->signal_set_result(interp, interp->sigmask);
+ }
+ else {
+ Jim_SetResultInt(interp, interp->sigmask);
+ }
+ interp->sigmask = 0;
+ }
+
+ if (argc >= 2) {
+ if (Jim_SetVariable(interp, argv[1], Jim_GetResult(interp)) != JIM_OK) {
+ return JIM_ERR;
+ }
+ if (argc == 3) {
+ Jim_Obj *optListObj = Jim_NewListObj(interp, NULL, 0);
+
+ Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-code", -1));
+ Jim_ListAppendElement(interp, optListObj,
+ Jim_NewIntObj(interp, exitCode == JIM_RETURN ? interp->returnCode : exitCode));
+ Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-level", -1));
+ Jim_ListAppendElement(interp, optListObj, Jim_NewIntObj(interp, interp->returnLevel));
+ if (exitCode == JIM_ERR) {
+ Jim_Obj *errorCode;
+ Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorinfo",
+ -1));
+ Jim_ListAppendElement(interp, optListObj, interp->stackTrace);
+
+ errorCode = Jim_GetGlobalVariableStr(interp, "errorCode", JIM_NONE);
+ if (errorCode) {
+ Jim_ListAppendElement(interp, optListObj, Jim_NewStringObj(interp, "-errorcode", -1));
+ Jim_ListAppendElement(interp, optListObj, errorCode);
+ }
+ }
+ if (Jim_SetVariable(interp, argv[2], optListObj) != JIM_OK) {
+ return JIM_ERR;
+ }
+ }
+ }
+ Jim_SetResultInt(interp, exitCode);
+ return JIM_OK;
+}
+
+
+
+static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
+ return JIM_ERR;
+ }
+
+ if (JimValidName(interp, "new procedure", argv[2])) {
+ return JIM_ERR;
+ }
+
+ return Jim_RenameCommand(interp, Jim_String(argv[1]), Jim_String(argv[2]));
+}
+
+#define JIM_DICTMATCH_KEYS 0x0001
+#define JIM_DICTMATCH_VALUES 0x002
+
+int Jim_DictMatchTypes(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *patternObj, int match_type, int return_types)
+{
+ Jim_HashEntry *he;
+ Jim_Obj *listObjPtr;
+ Jim_HashTableIterator htiter;
+
+ if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ listObjPtr = Jim_NewListObj(interp, NULL, 0);
+
+ JimInitHashTableIterator(objPtr->internalRep.ptr, &htiter);
+ while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+ if (patternObj) {
+ Jim_Obj *matchObj = (match_type == JIM_DICTMATCH_KEYS) ? (Jim_Obj *)he->key : Jim_GetHashEntryVal(he);
+ if (!JimGlobMatch(Jim_String(patternObj), Jim_String(matchObj), 0)) {
+
+ continue;
+ }
+ }
+ if (return_types & JIM_DICTMATCH_KEYS) {
+ Jim_ListAppendElement(interp, listObjPtr, (Jim_Obj *)he->key);
+ }
+ if (return_types & JIM_DICTMATCH_VALUES) {
+ Jim_ListAppendElement(interp, listObjPtr, Jim_GetHashEntryVal(he));
+ }
+ }
+
+ Jim_SetResult(interp, listObjPtr);
+ return JIM_OK;
+}
+
+int Jim_DictSize(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+ return -1;
+ }
+ return ((Jim_HashTable *)objPtr->internalRep.ptr)->used;
+}
+
+Jim_Obj *Jim_DictMerge(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+{
+ Jim_Obj *objPtr = Jim_NewDictObj(interp, NULL, 0);
+ int i;
+
+ JimPanic((objc == 0, "Jim_DictMerge called with objc=0"));
+
+
+
+ for (i = 0; i < objc; i++) {
+ Jim_HashTable *ht;
+ Jim_HashTableIterator htiter;
+ Jim_HashEntry *he;
+
+ if (SetDictFromAny(interp, objv[i]) != JIM_OK) {
+ Jim_FreeNewObj(interp, objPtr);
+ return NULL;
+ }
+ ht = objv[i]->internalRep.ptr;
+ JimInitHashTableIterator(ht, &htiter);
+ while ((he = Jim_NextHashEntry(&htiter)) != NULL) {
+ Jim_ReplaceHashEntry(objPtr->internalRep.ptr, Jim_GetHashEntryKey(he), Jim_GetHashEntryVal(he));
+ }
+ }
+ return objPtr;
+}
+
+int Jim_DictInfo(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+ Jim_HashTable *ht;
+ unsigned int i;
+ char buffer[100];
+ int sum = 0;
+ int nonzero_count = 0;
+ Jim_Obj *output;
+ int bucket_counts[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+
+ if (SetDictFromAny(interp, objPtr) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ ht = (Jim_HashTable *)objPtr->internalRep.ptr;
+
+
+ snprintf(buffer, sizeof(buffer), "%d entries in table, %d buckets\n", ht->used, ht->size);
+ output = Jim_NewStringObj(interp, buffer, -1);
+
+ for (i = 0; i < ht->size; i++) {
+ Jim_HashEntry *he = ht->table[i];
+ int entries = 0;
+ while (he) {
+ entries++;
+ he = he->next;
+ }
+ if (entries > 9) {
+ bucket_counts[10]++;
+ }
+ else {
+ bucket_counts[entries]++;
+ }
+ if (entries) {
+ sum += entries;
+ nonzero_count++;
+ }
+ }
+ for (i = 0; i < 10; i++) {
+ snprintf(buffer, sizeof(buffer), "number of buckets with %d entries: %d\n", i, bucket_counts[i]);
+ Jim_AppendString(interp, output, buffer, -1);
+ }
+ snprintf(buffer, sizeof(buffer), "number of buckets with 10 or more entries: %d\n", bucket_counts[10]);
+ Jim_AppendString(interp, output, buffer, -1);
+ snprintf(buffer, sizeof(buffer), "average search distance for entry: %.1f", nonzero_count ? (double)sum / nonzero_count : 0.0);
+ Jim_AppendString(interp, output, buffer, -1);
+ Jim_SetResult(interp, output);
+ return JIM_OK;
+}
+
+static int Jim_EvalEnsemble(Jim_Interp *interp, const char *basecmd, const char *subcmd, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *prefixObj = Jim_NewStringObj(interp, basecmd, -1);
+
+ Jim_AppendString(interp, prefixObj, " ", 1);
+ Jim_AppendString(interp, prefixObj, subcmd, -1);
+
+ return Jim_EvalObjPrefix(interp, prefixObj, argc, argv);
+}
+
+static int JimDictWith(Jim_Interp *interp, Jim_Obj *dictVarName, Jim_Obj *const *keyv, int keyc, Jim_Obj *scriptObj)
+{
+ int i;
+ Jim_Obj *objPtr;
+ Jim_Obj *dictObj;
+ Jim_Obj **dictValues;
+ int len;
+ int ret = JIM_OK;
+
+
+ dictObj = Jim_GetVariable(interp, dictVarName, JIM_ERRMSG);
+ if (dictObj == NULL || Jim_DictKeysVector(interp, dictObj, keyv, keyc, &objPtr, JIM_ERRMSG) != JIM_OK) {
+ return JIM_ERR;
+ }
+
+ if (Jim_DictPairs(interp, objPtr, &dictValues, &len) == JIM_ERR) {
+ return JIM_ERR;
+ }
+ for (i = 0; i < len; i += 2) {
+ if (Jim_SetVariable(interp, dictValues[i], dictValues[i + 1]) == JIM_ERR) {
+ Jim_Free(dictValues);
+ return JIM_ERR;
+ }
+ }
+
+
+ if (Jim_Length(scriptObj)) {
+ ret = Jim_EvalObj(interp, scriptObj);
+
+
+ if (ret == JIM_OK && Jim_GetVariable(interp, dictVarName, 0) != NULL) {
+
+ Jim_Obj **newkeyv = Jim_Alloc(sizeof(*newkeyv) * (keyc + 1));
+ for (i = 0; i < keyc; i++) {
+ newkeyv[i] = keyv[i];
+ }
+
+ for (i = 0; i < len; i += 2) {
+
+ objPtr = Jim_GetVariable(interp, dictValues[i], 0);
+ newkeyv[keyc] = dictValues[i];
+ Jim_SetDictKeysVector(interp, dictVarName, newkeyv, keyc + 1, objPtr, 0);
+ }
+ Jim_Free(newkeyv);
+ }
+ }
+
+ Jim_Free(dictValues);
+
+ return ret;
+}
+
+
+static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr;
+ int types = JIM_DICTMATCH_KEYS;
+ int option;
+ static const char * const options[] = {
+ "create", "get", "set", "unset", "exists", "keys", "size", "info",
+ "merge", "with", "append", "lappend", "incr", "remove", "values", "for",
+ "replace", "update", NULL
+ };
+ enum
+ {
+ OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXISTS, OPT_KEYS, OPT_SIZE, OPT_INFO,
+ OPT_MERGE, OPT_WITH, OPT_APPEND, OPT_LAPPEND, OPT_INCR, OPT_REMOVE, OPT_VALUES, OPT_FOR,
+ OPT_REPLACE, OPT_UPDATE,
+ };
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "subcommand ?arguments ...?");
+ return JIM_ERR;
+ }
+
+ if (Jim_GetEnum(interp, argv[1], options, &option, "subcommand", JIM_ERRMSG) != JIM_OK) {
+ return Jim_CheckShowCommands(interp, argv[1], options);
+ }
+
+ switch (option) {
+ case OPT_GET:
+ if (argc < 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "dictionary ?key ...?");
+ return JIM_ERR;
+ }
+ if (Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr,
+ JIM_ERRMSG) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+
+ case OPT_SET:
+ if (argc < 5) {
+ Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");
+ return JIM_ERR;
+ }
+ return Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 4, argv[argc - 1], JIM_ERRMSG);
+
+ case OPT_EXISTS:
+ if (argc < 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "dictionary key ?key ...?");
+ return JIM_ERR;
+ }
+ else {
+ int rc = Jim_DictKeysVector(interp, argv[2], argv + 3, argc - 3, &objPtr, JIM_ERRMSG);
+ if (rc < 0) {
+ return JIM_ERR;
+ }
+ Jim_SetResultBool(interp, rc == JIM_OK);
+ return JIM_OK;
+ }
+
+ case OPT_UNSET:
+ if (argc < 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");
+ return JIM_ERR;
+ }
+ if (Jim_SetDictKeysVector(interp, argv[2], argv + 3, argc - 3, NULL, 0) != JIM_OK) {
+ return JIM_ERR;
+ }
+ return JIM_OK;
+
+ case OPT_VALUES:
+ types = JIM_DICTMATCH_VALUES;
+
+ case OPT_KEYS:
+ if (argc != 3 && argc != 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "dictionary ?pattern?");
+ return JIM_ERR;
+ }
+ return Jim_DictMatchTypes(interp, argv[2], argc == 4 ? argv[3] : NULL, types, types);
+
+ case OPT_SIZE:
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "dictionary");
+ return JIM_ERR;
+ }
+ else if (Jim_DictSize(interp, argv[2]) < 0) {
+ return JIM_ERR;
+ }
+ Jim_SetResultInt(interp, Jim_DictSize(interp, argv[2]));
+ return JIM_OK;
+
+ case OPT_MERGE:
+ if (argc == 2) {
+ return JIM_OK;
+ }
+ objPtr = Jim_DictMerge(interp, argc - 2, argv + 2);
+ if (objPtr == NULL) {
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+
+ case OPT_UPDATE:
+ if (argc < 6 || argc % 2) {
+
+ argc = 2;
+ }
+ break;
+
+ case OPT_CREATE:
+ if (argc % 2) {
+ Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");
+ return JIM_ERR;
+ }
+ objPtr = Jim_NewDictObj(interp, argv + 2, argc - 2);
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+
+ case OPT_INFO:
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "dictionary");
+ return JIM_ERR;
+ }
+ return Jim_DictInfo(interp, argv[2]);
+
+ case OPT_WITH:
+ if (argc < 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "dictVar ?key ...? script");
+ return JIM_ERR;
+ }
+ return JimDictWith(interp, argv[2], argv + 3, argc - 4, argv[argc - 1]);
+ }
+
+ return Jim_EvalEnsemble(interp, "dict", options[option], argc - 2, argv + 2);
+}
+
+
+static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ static const char * const options[] = {
+ "-nobackslashes", "-nocommands", "-novariables", NULL
+ };
+ enum
+ { OPT_NOBACKSLASHES, OPT_NOCOMMANDS, OPT_NOVARIABLES };
+ int i;
+ int flags = JIM_SUBST_FLAG;
+ Jim_Obj *objPtr;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "?options? string");
+ return JIM_ERR;
+ }
+ for (i = 1; i < (argc - 1); i++) {
+ int option;
+
+ if (Jim_GetEnum(interp, argv[i], options, &option, NULL,
+ JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+ return JIM_ERR;
+ }
+ switch (option) {
+ case OPT_NOBACKSLASHES:
+ flags |= JIM_SUBST_NOESC;
+ break;
+ case OPT_NOCOMMANDS:
+ flags |= JIM_SUBST_NOCMD;
+ break;
+ case OPT_NOVARIABLES:
+ flags |= JIM_SUBST_NOVAR;
+ break;
+ }
+ }
+ if (Jim_SubstObj(interp, argv[argc - 1], &objPtr, flags) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int cmd;
+ Jim_Obj *objPtr;
+ int mode = 0;
+
+ static const char * const commands[] = {
+ "body", "statics", "commands", "procs", "channels", "exists", "globals", "level", "frame", "locals",
+ "vars", "version", "patchlevel", "complete", "args", "hostname",
+ "script", "source", "stacktrace", "nameofexecutable", "returncodes",
+ "references", "alias", NULL
+ };
+ enum
+ { INFO_BODY, INFO_STATICS, INFO_COMMANDS, INFO_PROCS, INFO_CHANNELS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,
+ INFO_FRAME, INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_PATCHLEVEL, INFO_COMPLETE, INFO_ARGS,
+ INFO_HOSTNAME, INFO_SCRIPT, INFO_SOURCE, INFO_STACKTRACE, INFO_NAMEOFEXECUTABLE,
+ INFO_RETURNCODES, INFO_REFERENCES, INFO_ALIAS,
+ };
+
+#ifdef jim_ext_namespace
+ int nons = 0;
+
+ if (argc > 2 && Jim_CompareStringImmediate(interp, argv[1], "-nons")) {
+
+ argc--;
+ argv++;
+ nons = 1;
+ }
+#endif
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "subcommand ?args ...?");
+ return JIM_ERR;
+ }
+ if (Jim_GetEnum(interp, argv[1], commands, &cmd, "subcommand", JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+ return Jim_CheckShowCommands(interp, argv[1], commands);
+ }
+
+
+ switch (cmd) {
+ case INFO_EXISTS:
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "varName");
+ return JIM_ERR;
+ }
+ Jim_SetResultBool(interp, Jim_GetVariable(interp, argv[2], 0) != NULL);
+ break;
+
+ case INFO_ALIAS:{
+ Jim_Cmd *cmdPtr;
+
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "command");
+ return JIM_ERR;
+ }
+ if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
+ return JIM_ERR;
+ }
+ if (cmdPtr->isproc || cmdPtr->u.native.cmdProc != JimAliasCmd) {
+ Jim_SetResultFormatted(interp, "command \"%#s\" is not an alias", argv[2]);
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, (Jim_Obj *)cmdPtr->u.native.privData);
+ return JIM_OK;
+ }
+
+ case INFO_CHANNELS:
+ mode++;
+#ifndef jim_ext_aio
+ Jim_SetResultString(interp, "aio not enabled", -1);
+ return JIM_ERR;
+#endif
+
+ case INFO_PROCS:
+ mode++;
+
+ case INFO_COMMANDS:
+
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
+ return JIM_ERR;
+ }
+#ifdef jim_ext_namespace
+ if (!nons) {
+ if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimGlobMatch("::*", Jim_String(argv[2]), 0))) {
+ return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
+ }
+ }
+#endif
+ Jim_SetResult(interp, JimCommandsList(interp, (argc == 3) ? argv[2] : NULL, mode));
+ break;
+
+ case INFO_VARS:
+ mode++;
+
+ case INFO_LOCALS:
+ mode++;
+
+ case INFO_GLOBALS:
+
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
+ return JIM_ERR;
+ }
+#ifdef jim_ext_namespace
+ if (!nons) {
+ if (Jim_Length(interp->framePtr->nsObj) || (argc == 3 && JimGlobMatch("::*", Jim_String(argv[2]), 0))) {
+ return Jim_EvalPrefix(interp, "namespace info", argc - 1, argv + 1);
+ }
+ }
+#endif
+ Jim_SetResult(interp, JimVariablesList(interp, argc == 3 ? argv[2] : NULL, mode));
+ break;
+
+ case INFO_SCRIPT:
+ if (argc != 2) {
+ Jim_WrongNumArgs(interp, 2, argv, "");
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, JimGetScript(interp, interp->currentScriptObj)->fileNameObj);
+ break;
+
+ case INFO_SOURCE:{
+ jim_wide line;
+ Jim_Obj *resObjPtr;
+ Jim_Obj *fileNameObj;
+
+ if (argc != 3 && argc != 5) {
+ Jim_WrongNumArgs(interp, 2, argv, "source ?filename line?");
+ return JIM_ERR;
+ }
+ if (argc == 5) {
+ if (Jim_GetWide(interp, argv[4], &line) != JIM_OK) {
+ return JIM_ERR;
+ }
+ resObjPtr = Jim_NewStringObj(interp, Jim_String(argv[2]), Jim_Length(argv[2]));
+ JimSetSourceInfo(interp, resObjPtr, argv[3], line);
+ }
+ else {
+ if (argv[2]->typePtr == &sourceObjType) {
+ fileNameObj = argv[2]->internalRep.sourceValue.fileNameObj;
+ line = argv[2]->internalRep.sourceValue.lineNumber;
+ }
+ else if (argv[2]->typePtr == &scriptObjType) {
+ ScriptObj *script = JimGetScript(interp, argv[2]);
+ fileNameObj = script->fileNameObj;
+ line = script->firstline;
+ }
+ else {
+ fileNameObj = interp->emptyObj;
+ line = 1;
+ }
+ resObjPtr = Jim_NewListObj(interp, NULL, 0);
+ Jim_ListAppendElement(interp, resObjPtr, fileNameObj);
+ Jim_ListAppendElement(interp, resObjPtr, Jim_NewIntObj(interp, line));
+ }
+ Jim_SetResult(interp, resObjPtr);
+ break;
+ }
+
+ case INFO_STACKTRACE:
+ Jim_SetResult(interp, interp->stackTrace);
+ break;
+
+ case INFO_LEVEL:
+ case INFO_FRAME:
+ switch (argc) {
+ case 2:
+ Jim_SetResultInt(interp, interp->framePtr->level);
+ break;
+
+ case 3:
+ if (JimInfoLevel(interp, argv[2], &objPtr, cmd == INFO_LEVEL) != JIM_OK) {
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, objPtr);
+ break;
+
+ default:
+ Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");
+ return JIM_ERR;
+ }
+ break;
+
+ case INFO_BODY:
+ case INFO_STATICS:
+ case INFO_ARGS:{
+ Jim_Cmd *cmdPtr;
+
+ if (argc != 3) {
+ Jim_WrongNumArgs(interp, 2, argv, "procname");
+ return JIM_ERR;
+ }
+ if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL) {
+ return JIM_ERR;
+ }
+ if (!cmdPtr->isproc) {
+ Jim_SetResultFormatted(interp, "command \"%#s\" is not a procedure", argv[2]);
+ return JIM_ERR;
+ }
+ switch (cmd) {
+ case INFO_BODY:
+ Jim_SetResult(interp, cmdPtr->u.proc.bodyObjPtr);
+ break;
+ case INFO_ARGS:
+ Jim_SetResult(interp, cmdPtr->u.proc.argListObjPtr);
+ break;
+ case INFO_STATICS:
+ if (cmdPtr->u.proc.staticVars) {
+ Jim_SetResult(interp, JimHashtablePatternMatch(interp, cmdPtr->u.proc.staticVars,
+ NULL, JimVariablesMatch, JIM_VARLIST_LOCALS | JIM_VARLIST_VALUES));
+ }
+ break;
+ }
+ break;
+ }
+
+ case INFO_VERSION:
+ case INFO_PATCHLEVEL:{
+ char buf[(JIM_INTEGER_SPACE * 2) + 1];
+
+ sprintf(buf, "%d.%d", JIM_VERSION / 100, JIM_VERSION % 100);
+ Jim_SetResultString(interp, buf, -1);
+ break;
+ }
+
+ case INFO_COMPLETE:
+ if (argc != 3 && argc != 4) {
+ Jim_WrongNumArgs(interp, 2, argv, "script ?missing?");
+ return JIM_ERR;
+ }
+ else {
+ char missing;
+
+ Jim_SetResultBool(interp, Jim_ScriptIsComplete(interp, argv[2], &missing));
+ if (missing != ' ' && argc == 4) {
+ Jim_SetVariable(interp, argv[3], Jim_NewStringObj(interp, &missing, 1));
+ }
+ }
+ break;
+
+ case INFO_HOSTNAME:
+
+ return Jim_Eval(interp, "os.gethostname");
+
+ case INFO_NAMEOFEXECUTABLE:
+
+ return Jim_Eval(interp, "{info nameofexecutable}");
+
+ case INFO_RETURNCODES:
+ if (argc == 2) {
+ int i;
+ Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+
+ for (i = 0; jimReturnCodes[i]; i++) {
+ Jim_ListAppendElement(interp, listObjPtr, Jim_NewIntObj(interp, i));
+ Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp,
+ jimReturnCodes[i], -1));
+ }
+
+ Jim_SetResult(interp, listObjPtr);
+ }
+ else if (argc == 3) {
+ long code;
+ const char *name;
+
+ if (Jim_GetLong(interp, argv[2], &code) != JIM_OK) {
+ return JIM_ERR;
+ }
+ name = Jim_ReturnCode(code);
+ if (*name == '?') {
+ Jim_SetResultInt(interp, code);
+ }
+ else {
+ Jim_SetResultString(interp, name, -1);
+ }
+ }
+ else {
+ Jim_WrongNumArgs(interp, 2, argv, "?code?");
+ return JIM_ERR;
+ }
+ break;
+ case INFO_REFERENCES:
+#ifdef JIM_REFERENCES
+ return JimInfoReferences(interp, argc, argv);
+#else
+ Jim_SetResultString(interp, "not supported", -1);
+ return JIM_ERR;
+#endif
+ }
+ return JIM_OK;
+}
+
+
+static int Jim_ExistsCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr;
+ int result = 0;
+
+ static const char * const options[] = {
+ "-command", "-proc", "-alias", "-var", NULL
+ };
+ enum
+ {
+ OPT_COMMAND, OPT_PROC, OPT_ALIAS, OPT_VAR
+ };
+ int option;
+
+ if (argc == 2) {
+ option = OPT_VAR;
+ objPtr = argv[1];
+ }
+ else if (argc == 3) {
+ if (Jim_GetEnum(interp, argv[1], options, &option, NULL, JIM_ERRMSG | JIM_ENUM_ABBREV) != JIM_OK) {
+ return JIM_ERR;
+ }
+ objPtr = argv[2];
+ }
+ else {
+ Jim_WrongNumArgs(interp, 1, argv, "?option? name");
+ return JIM_ERR;
+ }
+
+ if (option == OPT_VAR) {
+ result = Jim_GetVariable(interp, objPtr, 0) != NULL;
+ }
+ else {
+
+ Jim_Cmd *cmd = Jim_GetCommand(interp, objPtr, JIM_NONE);
+
+ if (cmd) {
+ switch (option) {
+ case OPT_COMMAND:
+ result = 1;
+ break;
+
+ case OPT_ALIAS:
+ result = cmd->isproc == 0 && cmd->u.native.cmdProc == JimAliasCmd;
+ break;
+
+ case OPT_PROC:
+ result = cmd->isproc;
+ break;
+ }
+ }
+ }
+ Jim_SetResultBool(interp, result);
+ return JIM_OK;
+}
+
+
+static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *str, *splitChars, *noMatchStart;
+ int splitLen, strLen;
+ Jim_Obj *resObjPtr;
+ int c;
+ int len;
+
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
+ return JIM_ERR;
+ }
+
+ str = Jim_GetString(argv[1], &len);
+ if (len == 0) {
+ return JIM_OK;
+ }
+ strLen = Jim_Utf8Length(interp, argv[1]);
+
+
+ if (argc == 2) {
+ splitChars = " \n\t\r";
+ splitLen = 4;
+ }
+ else {
+ splitChars = Jim_String(argv[2]);
+ splitLen = Jim_Utf8Length(interp, argv[2]);
+ }
+
+ noMatchStart = str;
+ resObjPtr = Jim_NewListObj(interp, NULL, 0);
+
+
+ if (splitLen) {
+ Jim_Obj *objPtr;
+ while (strLen--) {
+ const char *sc = splitChars;
+ int scLen = splitLen;
+ int sl = utf8_tounicode(str, &c);
+ while (scLen--) {
+ int pc;
+ sc += utf8_tounicode(sc, &pc);
+ if (c == pc) {
+ objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
+ Jim_ListAppendElement(interp, resObjPtr, objPtr);
+ noMatchStart = str + sl;
+ break;
+ }
+ }
+ str += sl;
+ }
+ objPtr = Jim_NewStringObj(interp, noMatchStart, (str - noMatchStart));
+ Jim_ListAppendElement(interp, resObjPtr, objPtr);
+ }
+ else {
+ Jim_Obj **commonObj = NULL;
+#define NUM_COMMON (128 - 9)
+ while (strLen--) {
+ int n = utf8_tounicode(str, &c);
+#ifdef JIM_OPTIMIZATION
+ if (c >= 9 && c < 128) {
+
+ c -= 9;
+ if (!commonObj) {
+ commonObj = Jim_Alloc(sizeof(*commonObj) * NUM_COMMON);
+ memset(commonObj, 0, sizeof(*commonObj) * NUM_COMMON);
+ }
+ if (!commonObj[c]) {
+ commonObj[c] = Jim_NewStringObj(interp, str, 1);
+ }
+ Jim_ListAppendElement(interp, resObjPtr, commonObj[c]);
+ str++;
+ continue;
+ }
+#endif
+ Jim_ListAppendElement(interp, resObjPtr, Jim_NewStringObjUtf8(interp, str, 1));
+ str += n;
+ }
+ Jim_Free(commonObj);
+ }
+
+ Jim_SetResult(interp, resObjPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *joinStr;
+ int joinStrLen;
+
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
+ return JIM_ERR;
+ }
+
+ if (argc == 2) {
+ joinStr = " ";
+ joinStrLen = 1;
+ }
+ else {
+ joinStr = Jim_GetString(argv[2], &joinStrLen);
+ }
+ Jim_SetResult(interp, Jim_ListJoin(interp, argv[1], joinStr, joinStrLen));
+ return JIM_OK;
+}
+
+
+static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr;
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
+ return JIM_ERR;
+ }
+ objPtr = Jim_FormatString(interp, argv[1], argc - 2, argv + 2);
+ if (objPtr == NULL)
+ return JIM_ERR;
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *listPtr, **outVec;
+ int outc, i;
+
+ if (argc < 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "string format ?varName varName ...?");
+ return JIM_ERR;
+ }
+ if (argv[2]->typePtr != &scanFmtStringObjType)
+ SetScanFmtFromAny(interp, argv[2]);
+ if (FormatGetError(argv[2]) != 0) {
+ Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
+ return JIM_ERR;
+ }
+ if (argc > 3) {
+ int maxPos = FormatGetMaxPos(argv[2]);
+ int count = FormatGetCnvCount(argv[2]);
+
+ if (maxPos > argc - 3) {
+ Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
+ return JIM_ERR;
+ }
+ else if (count > argc - 3) {
+ Jim_SetResultString(interp, "different numbers of variable names and "
+ "field specifiers", -1);
+ return JIM_ERR;
+ }
+ else if (count < argc - 3) {
+ Jim_SetResultString(interp, "variable is not assigned by any "
+ "conversion specifiers", -1);
+ return JIM_ERR;
+ }
+ }
+ listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
+ if (listPtr == 0)
+ return JIM_ERR;
+ if (argc > 3) {
+ int rc = JIM_OK;
+ int count = 0;
+
+ if (listPtr != 0 && listPtr != (Jim_Obj *)EOF) {
+ int len = Jim_ListLength(interp, listPtr);
+
+ if (len != 0) {
+ JimListGetElements(interp, listPtr, &outc, &outVec);
+ for (i = 0; i < outc; ++i) {
+ if (Jim_Length(outVec[i]) > 0) {
+ ++count;
+ if (Jim_SetVariable(interp, argv[3 + i], outVec[i]) != JIM_OK) {
+ rc = JIM_ERR;
+ }
+ }
+ }
+ }
+ Jim_FreeNewObj(interp, listPtr);
+ }
+ else {
+ count = -1;
+ }
+ if (rc == JIM_OK) {
+ Jim_SetResultInt(interp, count);
+ }
+ return rc;
+ }
+ else {
+ if (listPtr == (Jim_Obj *)EOF) {
+ Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
+ return JIM_OK;
+ }
+ Jim_SetResult(interp, listPtr);
+ }
+ return JIM_OK;
+}
+
+
+static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ if (argc != 2 && argc != 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "message ?stacktrace?");
+ return JIM_ERR;
+ }
+ Jim_SetResult(interp, argv[1]);
+ if (argc == 3) {
+ JimSetStackTrace(interp, argv[2]);
+ return JIM_ERR;
+ }
+ interp->addStackTrace++;
+ return JIM_ERR;
+}
+
+
+static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr;
+
+ if (argc != 4) {
+ Jim_WrongNumArgs(interp, 1, argv, "list first last");
+ return JIM_ERR;
+ }
+ if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
+ return JIM_ERR;
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_LrepeatCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *objPtr;
+ long count;
+
+ if (argc < 2 || Jim_GetLong(interp, argv[1], &count) != JIM_OK || count < 0) {
+ Jim_WrongNumArgs(interp, 1, argv, "count ?value ...?");
+ return JIM_ERR;
+ }
+
+ if (count == 0 || argc == 2) {
+ return JIM_OK;
+ }
+
+ argc -= 2;
+ argv += 2;
+
+ objPtr = Jim_NewListObj(interp, argv, argc);
+ while (--count) {
+ ListInsertElements(objPtr, -1, argc, argv);
+ }
+
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+}
+
+char **Jim_GetEnviron(void)
+{
+#if defined(HAVE__NSGETENVIRON)
+ return *_NSGetEnviron();
+#else
+ #if !defined(NO_ENVIRON_EXTERN)
+ extern char **environ;
+ #endif
+
+ return environ;
+#endif
+}
+
+void Jim_SetEnviron(char **env)
+{
+#if defined(HAVE__NSGETENVIRON)
+ *_NSGetEnviron() = env;
+#else
+ #if !defined(NO_ENVIRON_EXTERN)
+ extern char **environ;
+ #endif
+
+ environ = env;
+#endif
+}
+
+
+static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const char *key;
+ const char *val;
+
+ if (argc == 1) {
+ char **e = Jim_GetEnviron();
+
+ int i;
+ Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+
+ for (i = 0; e[i]; i++) {
+ const char *equals = strchr(e[i], '=');
+
+ if (equals) {
+ Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, e[i],
+ equals - e[i]));
+ Jim_ListAppendElement(interp, listObjPtr, Jim_NewStringObj(interp, equals + 1, -1));
+ }
+ }
+
+ Jim_SetResult(interp, listObjPtr);
+ return JIM_OK;
+ }
+
+ if (argc < 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "varName ?default?");
+ return JIM_ERR;
+ }
+ key = Jim_String(argv[1]);
+ val = getenv(key);
+ if (val == NULL) {
+ if (argc < 3) {
+ Jim_SetResultFormatted(interp, "environment variable \"%#s\" does not exist", argv[1]);
+ return JIM_ERR;
+ }
+ val = Jim_String(argv[2]);
+ }
+ Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
+ return JIM_OK;
+}
+
+
+static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ int retval;
+
+ if (argc != 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "fileName");
+ return JIM_ERR;
+ }
+ retval = Jim_EvalFile(interp, Jim_String(argv[1]));
+ if (retval == JIM_RETURN)
+ return JIM_OK;
+ return retval;
+}
+
+
+static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ Jim_Obj *revObjPtr, **ele;
+ int len;
+
+ if (argc != 2) {
+ Jim_WrongNumArgs(interp, 1, argv, "list");
+ return JIM_ERR;
+ }
+ JimListGetElements(interp, argv[1], &len, &ele);
+ len--;
+ revObjPtr = Jim_NewListObj(interp, NULL, 0);
+ while (len >= 0)
+ ListAppendElement(revObjPtr, ele[len--]);
+ Jim_SetResult(interp, revObjPtr);
+ return JIM_OK;
+}
+
+static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
+{
+ jim_wide len;
+
+ if (step == 0)
+ return -1;
+ if (start == end)
+ return 0;
+ else if (step > 0 && start > end)
+ return -1;
+ else if (step < 0 && end > start)
+ return -1;
+ len = end - start;
+ if (len < 0)
+ len = -len;
+ if (step < 0)
+ step = -step;
+ len = 1 + ((len - 1) / step);
+ if (len > INT_MAX)
+ len = INT_MAX;
+ return (int)((len < 0) ? -1 : len);
+}
+
+
+static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ jim_wide start = 0, end, step = 1;
+ int len, i;
+ Jim_Obj *objPtr;
+
+ if (argc < 2 || argc > 4) {
+ Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
+ return JIM_ERR;
+ }
+ if (argc == 2) {
+ if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)
+ return JIM_ERR;
+ }
+ else {
+ if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||
+ Jim_GetWide(interp, argv[2], &end) != JIM_OK)
+ return JIM_ERR;
+ if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)
+ return JIM_ERR;
+ }
+ if ((len = JimRangeLen(start, end, step)) == -1) {
+ Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
+ return JIM_ERR;
+ }
+ objPtr = Jim_NewListObj(interp, NULL, 0);
+ for (i = 0; i < len; i++)
+ ListAppendElement(objPtr, Jim_NewIntObj(interp, start + i * step));
+ Jim_SetResult(interp, objPtr);
+ return JIM_OK;
+}
+
+
+static int Jim_RandCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ jim_wide min = 0, max = 0, len, maxMul;
+
+ if (argc < 1 || argc > 3) {
+ Jim_WrongNumArgs(interp, 1, argv, "?min? max");
+ return JIM_ERR;
+ }
+ if (argc == 1) {
+ max = JIM_WIDE_MAX;
+ } else if (argc == 2) {
+ if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)
+ return JIM_ERR;
+ } else if (argc == 3) {
+ if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||
+ Jim_GetWide(interp, argv[2], &max) != JIM_OK)
+ return JIM_ERR;
+ }
+ len = max-min;
+ if (len < 0) {
+ Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
+ return JIM_ERR;
+ }
+ maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
+ while (1) {
+ jim_wide r;
+
+ JimRandomBytes(interp, &r, sizeof(jim_wide));
+ if (r < 0 || r >= maxMul) continue;
+ r = (len == 0) ? 0 : r%len;
+ Jim_SetResultInt(interp, min+r);
+ return JIM_OK;
+ }
+}
+
+static const struct {
+ const char *name;
+ Jim_CmdProc *cmdProc;
+} Jim_CoreCommandsTable[] = {
+ {"alias", Jim_AliasCoreCommand},
+ {"set", Jim_SetCoreCommand},
+ {"unset", Jim_UnsetCoreCommand},
+ {"puts", Jim_PutsCoreCommand},
+ {"+", Jim_AddCoreCommand},
+ {"*", Jim_MulCoreCommand},
+ {"-", Jim_SubCoreCommand},
+ {"/", Jim_DivCoreCommand},
+ {"incr", Jim_IncrCoreCommand},
+ {"while", Jim_WhileCoreCommand},
+ {"loop", Jim_LoopCoreCommand},
+ {"for", Jim_ForCoreCommand},
+ {"foreach", Jim_ForeachCoreCommand},
+ {"lmap", Jim_LmapCoreCommand},
+ {"lassign", Jim_LassignCoreCommand},
+ {"if", Jim_IfCoreCommand},
+ {"switch", Jim_SwitchCoreCommand},
+ {"list", Jim_ListCoreCommand},
+ {"lindex", Jim_LindexCoreCommand},
+ {"lset", Jim_LsetCoreCommand},
+ {"lsearch", Jim_LsearchCoreCommand},
+ {"llength", Jim_LlengthCoreCommand},
+ {"lappend", Jim_LappendCoreCommand},
+ {"linsert", Jim_LinsertCoreCommand},
+ {"lreplace", Jim_LreplaceCoreCommand},
+ {"lsort", Jim_LsortCoreCommand},
+ {"append", Jim_AppendCoreCommand},
+ {"debug", Jim_DebugCoreCommand},
+ {"eval", Jim_EvalCoreCommand},
+ {"uplevel", Jim_UplevelCoreCommand},
+ {"expr", Jim_ExprCoreCommand},
+ {"break", Jim_BreakCoreCommand},
+ {"continue", Jim_ContinueCoreCommand},
+ {"proc", Jim_ProcCoreCommand},
+ {"concat", Jim_ConcatCoreCommand},
+ {"return", Jim_ReturnCoreCommand},
+ {"upvar", Jim_UpvarCoreCommand},
+ {"global", Jim_GlobalCoreCommand},
+ {"string", Jim_StringCoreCommand},
+ {"time", Jim_TimeCoreCommand},
+ {"exit", Jim_ExitCoreCommand},
+ {"catch", Jim_CatchCoreCommand},
+#ifdef JIM_REFERENCES
+ {"ref", Jim_RefCoreCommand},
+ {"getref", Jim_GetrefCoreCommand},
+ {"setref", Jim_SetrefCoreCommand},
+ {"finalize", Jim_FinalizeCoreCommand},
+ {"collect", Jim_CollectCoreCommand},
+#endif
+ {"rename", Jim_RenameCoreCommand},
+ {"dict", Jim_DictCoreCommand},
+ {"subst", Jim_SubstCoreCommand},
+ {"info", Jim_InfoCoreCommand},
+ {"exists", Jim_ExistsCoreCommand},
+ {"split", Jim_SplitCoreCommand},
+ {"join", Jim_JoinCoreCommand},
+ {"format", Jim_FormatCoreCommand},
+ {"scan", Jim_ScanCoreCommand},
+ {"error", Jim_ErrorCoreCommand},
+ {"lrange", Jim_LrangeCoreCommand},
+ {"lrepeat", Jim_LrepeatCoreCommand},
+ {"env", Jim_EnvCoreCommand},
+ {"source", Jim_SourceCoreCommand},
+ {"lreverse", Jim_LreverseCoreCommand},
+ {"range", Jim_RangeCoreCommand},
+ {"rand", Jim_RandCoreCommand},
+ {"tailcall", Jim_TailcallCoreCommand},
+ {"local", Jim_LocalCoreCommand},
+ {"upcall", Jim_UpcallCoreCommand},
+ {"apply", Jim_ApplyCoreCommand},
+ {NULL, NULL},
+};
+
+void Jim_RegisterCoreCommands(Jim_Interp *interp)
+{
+ int i = 0;
+
+ while (Jim_CoreCommandsTable[i].name != NULL) {
+ Jim_CreateCommand(interp,
+ Jim_CoreCommandsTable[i].name, Jim_CoreCommandsTable[i].cmdProc, NULL, NULL);
+ i++;
+ }
+}
+
+void Jim_MakeErrorMessage(Jim_Interp *interp)
+{
+ Jim_Obj *argv[2];
+
+ argv[0] = Jim_NewStringObj(interp, "errorInfo", -1);
+ argv[1] = interp->result;
+
+ Jim_EvalObjVector(interp, 2, argv);
+}
+
+static char **JimSortStringTable(const char *const *tablePtr)
+{
+ int count;
+ char **tablePtrSorted;
+
+
+ for (count = 0; tablePtr[count]; count++) {
+ }
+
+
+ tablePtrSorted = Jim_Alloc(sizeof(char *) * (count + 1));
+ memcpy(tablePtrSorted, tablePtr, sizeof(char *) * count);
+ qsort(tablePtrSorted, count, sizeof(char *), qsortCompareStringPointers);
+ tablePtrSorted[count] = NULL;
+
+ return tablePtrSorted;
+}
+
+static void JimSetFailedEnumResult(Jim_Interp *interp, const char *arg, const char *badtype,
+ const char *prefix, const char *const *tablePtr, const char *name)
+{
+ char **tablePtrSorted;
+ int i;
+
+ if (name == NULL) {
+ name = "option";
+ }
+
+ Jim_SetResultFormatted(interp, "%s%s \"%s\": must be ", badtype, name, arg);
+ tablePtrSorted = JimSortStringTable(tablePtr);
+ for (i = 0; tablePtrSorted[i]; i++) {
+ if (tablePtrSorted[i + 1] == NULL && i > 0) {
+ Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
+ }
+ Jim_AppendStrings(interp, Jim_GetResult(interp), prefix, tablePtrSorted[i], NULL);
+ if (tablePtrSorted[i + 1]) {
+ Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
+ }
+ }
+ Jim_Free(tablePtrSorted);
+}
+
+
+int Jim_CheckShowCommands(Jim_Interp *interp, Jim_Obj *objPtr, const char *const *tablePtr)
+{
+ if (Jim_CompareStringImmediate(interp, objPtr, "-commands")) {
+ int i;
+ char **tablePtrSorted = JimSortStringTable(tablePtr);
+ Jim_SetResult(interp, Jim_NewListObj(interp, NULL, 0));
+ for (i = 0; tablePtrSorted[i]; i++) {
+ Jim_ListAppendElement(interp, Jim_GetResult(interp), Jim_NewStringObj(interp, tablePtrSorted[i], -1));
+ }
+ Jim_Free(tablePtrSorted);
+ return JIM_OK;
+ }
+ return JIM_ERR;
+}
+
+static const Jim_ObjType getEnumObjType = {
+ "get-enum",
+ NULL,
+ NULL,
+ NULL,
+ JIM_TYPE_REFERENCES
+};
+
+int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
+ const char *const *tablePtr, int *indexPtr, const char *name, int flags)
+{
+ const char *bad = "bad ";
+ const char *const *entryPtr = NULL;
+ int i;
+ int match = -1;
+ int arglen;
+ const char *arg;
+
+ if (objPtr->typePtr == &getEnumObjType) {
+ if (objPtr->internalRep.ptrIntValue.ptr == tablePtr && objPtr->internalRep.ptrIntValue.int1 == flags) {
+ *indexPtr = objPtr->internalRep.ptrIntValue.int2;
+ return JIM_OK;
+ }
+ }
+
+ arg = Jim_GetString(objPtr, &arglen);
+
+ *indexPtr = -1;
+
+ for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
+ if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
+
+ match = i;
+ goto found;
+ }
+ if (flags & JIM_ENUM_ABBREV) {
+ if (strncmp(arg, *entryPtr, arglen) == 0) {
+ if (*arg == '-' && arglen == 1) {
+ break;
+ }
+ if (match >= 0) {
+ bad = "ambiguous ";
+ goto ambiguous;
+ }
+ match = i;
+ }
+ }
+ }
+
+
+ if (match >= 0) {
+ found:
+
+ Jim_FreeIntRep(interp, objPtr);
+ objPtr->typePtr = &getEnumObjType;
+ objPtr->internalRep.ptrIntValue.ptr = (void *)tablePtr;
+ objPtr->internalRep.ptrIntValue.int1 = flags;
+ objPtr->internalRep.ptrIntValue.int2 = match;
+
+ *indexPtr = match;
+ return JIM_OK;
+ }
+
+ ambiguous:
+ if (flags & JIM_ERRMSG) {
+ JimSetFailedEnumResult(interp, arg, bad, "", tablePtr, name);
+ }
+ return JIM_ERR;
+}
+
+int Jim_FindByName(const char *name, const char * const array[], size_t len)
+{
+ int i;
+
+ for (i = 0; i < (int)len; i++) {
+ if (array[i] && strcmp(array[i], name) == 0) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+int Jim_IsDict(Jim_Obj *objPtr)
+{
+ return objPtr->typePtr == &dictObjType;
+}
+
+int Jim_IsList(Jim_Obj *objPtr)
+{
+ return objPtr->typePtr == &listObjType;
+}
+
+void Jim_SetResultFormatted(Jim_Interp *interp, const char *format, ...)
+{
+
+ int len = strlen(format);
+ int extra = 0;
+ int n = 0;
+ const char *params[5];
+ int nobjparam = 0;
+ Jim_Obj *objparam[5];
+ char *buf;
+ va_list args;
+ int i;
+
+ va_start(args, format);
+
+ for (i = 0; i < len && n < 5; i++) {
+ int l;
+
+ if (strncmp(format + i, "%s", 2) == 0) {
+ params[n] = va_arg(args, char *);
+
+ l = strlen(params[n]);
+ }
+ else if (strncmp(format + i, "%#s", 3) == 0) {
+ Jim_Obj *objPtr = va_arg(args, Jim_Obj *);
+
+ params[n] = Jim_GetString(objPtr, &l);
+ objparam[nobjparam++] = objPtr;
+ Jim_IncrRefCount(objPtr);
+ }
+ else {
+ if (format[i] == '%') {
+ i++;
+ }
+ continue;
+ }
+ n++;
+ extra += l;
+ }
+
+ len += extra;
+ buf = Jim_Alloc(len + 1);
+ len = snprintf(buf, len + 1, format, params[0], params[1], params[2], params[3], params[4]);
+
+ va_end(args);
+
+ Jim_SetResult(interp, Jim_NewStringObjNoAlloc(interp, buf, len));
+
+ for (i = 0; i < nobjparam; i++) {
+ Jim_DecrRefCount(interp, objparam[i]);
+ }
+}
+
+
+#ifndef jim_ext_package
+int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver, int flags)
+{
+ return JIM_OK;
+}
+#endif
+#ifndef jim_ext_aio
+FILE *Jim_AioFilehandle(Jim_Interp *interp, Jim_Obj *fhObj)
+{
+ Jim_SetResultString(interp, "aio not enabled", -1);
+ return NULL;
+}
+#endif
+
+
+#include
+#include
+
+
+static int subcmd_null(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+
+ return JIM_OK;
+}
+
+static const jim_subcmd_type dummy_subcmd = {
+ "dummy", NULL, subcmd_null, 0, 0, JIM_MODFLAG_HIDDEN
+};
+
+static void add_commands(Jim_Interp *interp, const jim_subcmd_type * ct, const char *sep)
+{
+ const char *s = "";
+
+ for (; ct->cmd; ct++) {
+ if (!(ct->flags & JIM_MODFLAG_HIDDEN)) {
+ Jim_AppendStrings(interp, Jim_GetResult(interp), s, ct->cmd, NULL);
+ s = sep;
+ }
+ }
+}
+
+static void bad_subcmd(Jim_Interp *interp, const jim_subcmd_type * command_table, const char *type,
+ Jim_Obj *cmd, Jim_Obj *subcmd)
+{
+ Jim_SetResultFormatted(interp, "%#s, %s command \"%#s\": should be ", cmd, type, subcmd);
+ add_commands(interp, command_table, ", ");
+}
+
+static void show_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * command_table, int argc,
+ Jim_Obj *const *argv)
+{
+ Jim_SetResultFormatted(interp, "Usage: \"%#s command ... \", where command is one of: ", argv[0]);
+ add_commands(interp, command_table, ", ");
+}
+
+static void add_cmd_usage(Jim_Interp *interp, const jim_subcmd_type * ct, Jim_Obj *cmd)
+{
+ if (cmd) {
+ Jim_AppendStrings(interp, Jim_GetResult(interp), Jim_String(cmd), " ", NULL);
+ }
+ Jim_AppendStrings(interp, Jim_GetResult(interp), ct->cmd, NULL);
+ if (ct->args && *ct->args) {
+ Jim_AppendStrings(interp, Jim_GetResult(interp), " ", ct->args, NULL);
+ }
+}
+
+static void set_wrong_args(Jim_Interp *interp, const jim_subcmd_type * command_table, Jim_Obj *subcmd)
+{
+ Jim_SetResultString(interp, "wrong # args: should be \"", -1);
+ add_cmd_usage(interp, command_table, subcmd);
+ Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
+}
+
+static const Jim_ObjType subcmdLookupObjType = {
+ "subcmd-lookup",
+ NULL,
+ NULL,
+ NULL,
+ JIM_TYPE_REFERENCES
+};
+
+const jim_subcmd_type *Jim_ParseSubCmd(Jim_Interp *interp, const jim_subcmd_type * command_table,
+ int argc, Jim_Obj *const *argv)
+{
+ const jim_subcmd_type *ct;
+ const jim_subcmd_type *partial = 0;
+ int cmdlen;
+ Jim_Obj *cmd;
+ const char *cmdstr;
+ int help = 0;
+
+ if (argc < 2) {
+ Jim_SetResultFormatted(interp, "wrong # args: should be \"%#s command ...\"\n"
+ "Use \"%#s -help ?command?\" for help", argv[0], argv[0]);
+ return 0;
+ }
+
+ cmd = argv[1];
+
+
+ if (cmd->typePtr == &subcmdLookupObjType) {
+ if (cmd->internalRep.ptrIntValue.ptr == command_table) {
+ ct = command_table + cmd->internalRep.ptrIntValue.int1;
+ goto found;
+ }
+ }
+
+
+ if (Jim_CompareStringImmediate(interp, cmd, "-help")) {
+ if (argc == 2) {
+
+ show_cmd_usage(interp, command_table, argc, argv);
+ return &dummy_subcmd;
+ }
+ help = 1;
+
+
+ cmd = argv[2];
+ }
+
+
+ if (Jim_CompareStringImmediate(interp, cmd, "-commands")) {
+
+ Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+ add_commands(interp, command_table, " ");
+ return &dummy_subcmd;
+ }
+
+ cmdstr = Jim_GetString(cmd, &cmdlen);
+
+ for (ct = command_table; ct->cmd; ct++) {
+ if (Jim_CompareStringImmediate(interp, cmd, ct->cmd)) {
+
+ break;
+ }
+ if (strncmp(cmdstr, ct->cmd, cmdlen) == 0) {
+ if (partial) {
+
+ if (help) {
+
+ show_cmd_usage(interp, command_table, argc, argv);
+ return &dummy_subcmd;
+ }
+ bad_subcmd(interp, command_table, "ambiguous", argv[0], argv[1 + help]);
+ return 0;
+ }
+ partial = ct;
+ }
+ continue;
+ }
+
+
+ if (partial && !ct->cmd) {
+ ct = partial;
+ }
+
+ if (!ct->cmd) {
+
+ if (help) {
+
+ show_cmd_usage(interp, command_table, argc, argv);
+ return &dummy_subcmd;
+ }
+ bad_subcmd(interp, command_table, "unknown", argv[0], argv[1 + help]);
+ return 0;
+ }
+
+ if (help) {
+ Jim_SetResultString(interp, "Usage: ", -1);
+
+ add_cmd_usage(interp, ct, argv[0]);
+ return &dummy_subcmd;
+ }
+
+
+ Jim_FreeIntRep(interp, cmd);
+ cmd->typePtr = &subcmdLookupObjType;
+ cmd->internalRep.ptrIntValue.ptr = (void *)command_table;
+ cmd->internalRep.ptrIntValue.int1 = ct - command_table;
+
+found:
+
+ if (argc - 2 < ct->minargs || (ct->maxargs >= 0 && argc - 2 > ct->maxargs)) {
+ Jim_SetResultString(interp, "wrong # args: should be \"", -1);
+
+ add_cmd_usage(interp, ct, argv[0]);
+ Jim_AppendStrings(interp, Jim_GetResult(interp), "\"", NULL);
+
+ return 0;
+ }
+
+
+ return ct;
+}
+
+int Jim_CallSubCmd(Jim_Interp *interp, const jim_subcmd_type * ct, int argc, Jim_Obj *const *argv)
+{
+ int ret = JIM_ERR;
+
+ if (ct) {
+ if (ct->flags & JIM_MODFLAG_FULLARGV) {
+ ret = ct->function(interp, argc, argv);
+ }
+ else {
+ ret = ct->function(interp, argc - 2, argv + 2);
+ }
+ if (ret < 0) {
+ set_wrong_args(interp, ct, argv[0]);
+ ret = JIM_ERR;
+ }
+ }
+ return ret;
+}
+
+int Jim_SubCmdProc(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+ const jim_subcmd_type *ct =
+ Jim_ParseSubCmd(interp, (const jim_subcmd_type *)Jim_CmdPrivData(interp), argc, argv);
+
+ return Jim_CallSubCmd(interp, ct, argc, argv);
+}
+
+#include
+#include
+#include
+#include
+#include
+
+
+int utf8_fromunicode(char *p, unsigned uc)
+{
+ if (uc <= 0x7f) {
+ *p = uc;
+ return 1;
+ }
+ else if (uc <= 0x7ff) {
+ *p++ = 0xc0 | ((uc & 0x7c0) >> 6);
+ *p = 0x80 | (uc & 0x3f);
+ return 2;
+ }
+ else if (uc <= 0xffff) {
+ *p++ = 0xe0 | ((uc & 0xf000) >> 12);
+ *p++ = 0x80 | ((uc & 0xfc0) >> 6);
+ *p = 0x80 | (uc & 0x3f);
+ return 3;
+ }
+
+ else {
+ *p++ = 0xf0 | ((uc & 0x1c0000) >> 18);
+ *p++ = 0x80 | ((uc & 0x3f000) >> 12);
+ *p++ = 0x80 | ((uc & 0xfc0) >> 6);
+ *p = 0x80 | (uc & 0x3f);
+ return 4;
+ }
+}
+
+#include
+#include
+
+
+#define JIM_INTEGER_SPACE 24
+#define MAX_FLOAT_WIDTH 320
+
+Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv)
+{
+ const char *span, *format, *formatEnd, *msg;
+ int numBytes = 0, objIndex = 0, gotXpg = 0, gotSequential = 0;
+ static const char * const mixedXPG =
+ "cannot mix \"%\" and \"%n$\" conversion specifiers";
+ static const char * const badIndex[2] = {
+ "not enough arguments for all format specifiers",
+ "\"%n$\" argument index out of range"
+ };
+ int formatLen;
+ Jim_Obj *resultPtr;
+
+ char *num_buffer = NULL;
+ int num_buffer_size = 0;
+
+ span = format = Jim_GetString(fmtObjPtr, &formatLen);
+ formatEnd = format + formatLen;
+ resultPtr = Jim_NewEmptyStringObj(interp);
+
+ while (format != formatEnd) {
+ char *end;
+ int gotMinus, sawFlag;
+ int gotPrecision, useShort;
+ long width, precision;
+ int newXpg;
+ int ch;
+ int step;
+ int doubleType;
+ char pad = ' ';
+ char spec[2*JIM_INTEGER_SPACE + 12];
+ char *p;
+
+ int formatted_chars;
+ int formatted_bytes;
+ const char *formatted_buf;
+
+ step = utf8_tounicode(format, &ch);
+ format += step;
+ if (ch != '%') {
+ numBytes += step;
+ continue;
+ }
+ if (numBytes) {
+ Jim_AppendString(interp, resultPtr, span, numBytes);
+ numBytes = 0;
+ }
+
+
+ step = utf8_tounicode(format, &ch);
+ if (ch == '%') {
+ span = format;
+ numBytes = step;
+ format += step;
+ continue;
+ }
+
+
+ newXpg = 0;
+ if (isdigit(ch)) {
+ int position = strtoul(format, &end, 10);
+ if (*end == '$') {
+ newXpg = 1;
+ objIndex = position - 1;
+ format = end + 1;
+ step = utf8_tounicode(format, &ch);
+ }
+ }
+ if (newXpg) {
+ if (gotSequential) {
+ msg = mixedXPG;
+ goto errorMsg;
+ }
+ gotXpg = 1;
+ } else {
+ if (gotXpg) {
+ msg = mixedXPG;
+ goto errorMsg;
+ }
+ gotSequential = 1;
+ }
+ if ((objIndex < 0) || (objIndex >= objc)) {
+ msg = badIndex[gotXpg];
+ goto errorMsg;
+ }
+
+ p = spec;
+ *p++ = '%';
+
+ gotMinus = 0;
+ sawFlag = 1;
+ do {
+ switch (ch) {
+ case '-':
+ gotMinus = 1;
+ break;
+ case '0':
+ pad = ch;
+ break;
+ case ' ':
+ case '+':
+ case '#':
+ break;
+ default:
+ sawFlag = 0;
+ continue;
+ }
+ *p++ = ch;
+ format += step;
+ step = utf8_tounicode(format, &ch);
+
+ } while (sawFlag && (p - spec <= 5));
+
+
+ width = 0;
+ if (isdigit(ch)) {
+ width = strtoul(format, &end, 10);
+ format = end;
+ step = utf8_tounicode(format, &ch);
+ } else if (ch == '*') {
+ if (objIndex >= objc - 1) {
+ msg = badIndex[gotXpg];
+ goto errorMsg;
+ }
+ if (Jim_GetLong(interp, objv[objIndex], &width) != JIM_OK) {
+ goto error;
+ }
+ if (width < 0) {
+ width = -width;
+ if (!gotMinus) {
+ *p++ = '-';
+ gotMinus = 1;
+ }
+ }
+ objIndex++;
+ format += step;
+ step = utf8_tounicode(format, &ch);
+ }
+
+
+ gotPrecision = precision = 0;
+ if (ch == '.') {
+ gotPrecision = 1;
+ format += step;
+ step = utf8_tounicode(format, &ch);
+ }
+ if (isdigit(ch)) {
+ precision = strtoul(format, &end, 10);
+ format = end;
+ step = utf8_tounicode(format, &ch);
+ } else if (ch == '*') {
+ if (objIndex >= objc - 1) {
+ msg = badIndex[gotXpg];
+ goto errorMsg;
+ }
+ if (Jim_GetLong(interp, objv[objIndex], &precision) != JIM_OK) {
+ goto error;
+ }
+
+
+ if (precision < 0) {
+ precision = 0;
+ }
+ objIndex++;
+ format += step;
+ step = utf8_tounicode(format, &ch);
+ }
+
+
+ useShort = 0;
+ if (ch == 'h') {
+ useShort = 1;
+ format += step;
+ step = utf8_tounicode(format, &ch);
+ } else if (ch == 'l') {
+
+ format += step;
+ step = utf8_tounicode(format, &ch);
+ if (ch == 'l') {
+ format += step;
+ step = utf8_tounicode(format, &ch);
+ }
+ }
+
+ format += step;
+ span = format;
+
+
+ if (ch == 'i') {
+ ch = 'd';
+ }
+
+ doubleType = 0;
+
+ switch (ch) {
+ case '\0':
+ msg = "format string ended in middle of field specifier";
+ goto errorMsg;
+ case 's': {
+ formatted_buf = Jim_GetString(objv[objIndex], &formatted_bytes);
+ formatted_chars = Jim_Utf8Length(interp, objv[objIndex]);
+ if (gotPrecision && (precision < formatted_chars)) {
+
+ formatted_chars = precision;
+ formatted_bytes = utf8_index(formatted_buf, precision);
+ }
+ break;
+ }
+ case 'c': {
+ jim_wide code;
+
+ if (Jim_GetWide(interp, objv[objIndex], &code) != JIM_OK) {
+ goto error;
+ }
+
+ formatted_bytes = utf8_getchars(spec, code);
+ formatted_buf = spec;
+ formatted_chars = 1;
+ break;
+ }
+ case 'b': {
+ unsigned jim_wide w;
+ int length;
+ int i;
+ int j;
+
+ if (Jim_GetWide(interp, objv[objIndex], (jim_wide *)&w) != JIM_OK) {
+ goto error;
+ }
+ length = sizeof(w) * 8;
+
+
+
+ if (num_buffer_size < length + 1) {
+ num_buffer_size = length + 1;
+ num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
+ }
+
+ j = 0;
+ for (i = length; i > 0; ) {
+ i--;
+ if (w & ((unsigned jim_wide)1 << i)) {
+ num_buffer[j++] = '1';
+ }
+ else if (j || i == 0) {
+ num_buffer[j++] = '0';
+ }
+ }
+ num_buffer[j] = 0;
+ formatted_chars = formatted_bytes = j;
+ formatted_buf = num_buffer;
+ break;
+ }
+
+ case 'e':
+ case 'E':
+ case 'f':
+ case 'g':
+ case 'G':
+ doubleType = 1;
+
+ case 'd':
+ case 'u':
+ case 'o':
+ case 'x':
+ case 'X': {
+ jim_wide w;
+ double d;
+ int length;
+
+
+ if (width) {
+ p += sprintf(p, "%ld", width);
+ }
+ if (gotPrecision) {
+ p += sprintf(p, ".%ld", precision);
+ }
+
+
+ if (doubleType) {
+ if (Jim_GetDouble(interp, objv[objIndex], &d) != JIM_OK) {
+ goto error;
+ }
+ length = MAX_FLOAT_WIDTH;
+ }
+ else {
+ if (Jim_GetWide(interp, objv[objIndex], &w) != JIM_OK) {
+ goto error;
+ }
+ length = JIM_INTEGER_SPACE;
+ if (useShort) {
+ if (ch == 'd') {
+ w = (short)w;
+ }
+ else {
+ w = (unsigned short)w;
+ }
+ }
+ *p++ = 'l';
+#ifdef HAVE_LONG_LONG
+ if (sizeof(long long) == sizeof(jim_wide)) {
+ *p++ = 'l';
+ }
+#endif
+ }
+
+ *p++ = (char) ch;
+ *p = '\0';
+
+
+ if (width > 10000 || length > 10000 || precision > 10000) {
+ Jim_SetResultString(interp, "format too long", -1);
+ goto error;
+ }
+
+
+
+ if (width > length) {
+ length = width;
+ }
+ if (gotPrecision) {
+ length += precision;
+ }
+
+
+ if (num_buffer_size < length + 1) {
+ num_buffer_size = length + 1;
+ num_buffer = Jim_Realloc(num_buffer, num_buffer_size);
+ }
+
+ if (doubleType) {
+ snprintf(num_buffer, length + 1, spec, d);
+ }
+ else {
+ formatted_bytes = snprintf(num_buffer, length + 1, spec, w);
+ }
+ formatted_chars = formatted_bytes = strlen(num_buffer);
+ formatted_buf = num_buffer;
+ break;
+ }
+
+ default: {
+
+ spec[0] = ch;
+ spec[1] = '\0';
+ Jim_SetResultFormatted(interp, "bad field specifier \"%s\"", spec);
+ goto error;
+ }
+ }
+
+ if (!gotMinus) {
+ while (formatted_chars < width) {
+ Jim_AppendString(interp, resultPtr, &pad, 1);
+ formatted_chars++;
+ }
+ }
+
+ Jim_AppendString(interp, resultPtr, formatted_buf, formatted_bytes);
+
+ while (formatted_chars < width) {
+ Jim_AppendString(interp, resultPtr, &pad, 1);
+ formatted_chars++;
+ }
+
+ objIndex += gotSequential;
+ }
+ if (numBytes) {
+ Jim_AppendString(interp, resultPtr, span, numBytes);
+ }
+
+ Jim_Free(num_buffer);
+ return resultPtr;
+
+ errorMsg:
+ Jim_SetResultString(interp, msg, -1);
+ error:
+ Jim_FreeNewObj(interp, resultPtr);
+ Jim_Free(num_buffer);
+ return NULL;
+}
+
+
+#if defined(JIM_REGEXP)
+#include
+#include
+#include
+#include
+
+
+
+#define REG_MAX_PAREN 100
+
+
+
+#define END 0
+#define BOL 1
+#define EOL 2
+#define ANY 3
+#define ANYOF 4
+#define ANYBUT 5
+#define BRANCH 6
+#define BACK 7
+#define EXACTLY 8
+#define NOTHING 9
+#define REP 10
+#define REPMIN 11
+#define REPX 12
+#define REPXMIN 13
+#define BOLX 14
+#define EOLX 15
+#define WORDA 16
+#define WORDZ 17
+
+#define OPENNC 1000
+#define OPEN 1001
+
+
+
+
+#define CLOSENC 2000
+#define CLOSE 2001
+#define CLOSE_END (CLOSE+REG_MAX_PAREN)
+
+#define REG_MAGIC 0xFADED00D
+
+
+#define OP(preg, p) (preg->program[p])
+#define NEXT(preg, p) (preg->program[p + 1])
+#define OPERAND(p) ((p) + 2)
+
+
+
+
+#define FAIL(R,M) { (R)->err = (M); return (M); }
+#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?' || (c) == '{')
+#define META "^$.[()|?{+*"
+
+#define HASWIDTH 1
+#define SIMPLE 2
+#define SPSTART 4
+#define WORST 0
+
+#define MAX_REP_COUNT 1000000
+
+static int reg(regex_t *preg, int paren, int *flagp );
+static int regpiece(regex_t *preg, int *flagp );
+static int regbranch(regex_t *preg, int *flagp );
+static int regatom(regex_t *preg, int *flagp );
+static int regnode(regex_t *preg, int op );
+static int regnext(regex_t *preg, int p );
+static void regc(regex_t *preg, int b );
+static int reginsert(regex_t *preg, int op, int size, int opnd );
+static void regtail(regex_t *preg, int p, int val);
+static void regoptail(regex_t *preg, int p, int val );
+static int regopsize(regex_t *preg, int p );
+
+static int reg_range_find(const int *string, int c);
+static const char *str_find(const char *string, int c, int nocase);
+static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase);
+
+
+#ifdef DEBUG
+static int regnarrate = 0;
+static void regdump(regex_t *preg);
+static const char *regprop( int op );
+#endif
+
+
+static int str_int_len(const int *seq)
+{
+ int n = 0;
+ while (*seq++) {
+ n++;
+ }
+ return n;
+}
+
+int regcomp(regex_t *preg, const char *exp, int cflags)
+{
+ int scan;
+ int longest;
+ unsigned len;
+ int flags;
+
+#ifdef DEBUG
+ fprintf(stderr, "Compiling: '%s'\n", exp);
+#endif
+ memset(preg, 0, sizeof(*preg));
+
+ if (exp == NULL)
+ FAIL(preg, REG_ERR_NULL_ARGUMENT);
+
+
+ preg->cflags = cflags;
+ preg->regparse = exp;
+
+
+ preg->proglen = (strlen(exp) + 1) * 5;
+ preg->program = malloc(preg->proglen * sizeof(int));
+ if (preg->program == NULL)
+ FAIL(preg, REG_ERR_NOMEM);
+
+ regc(preg, REG_MAGIC);
+ if (reg(preg, 0, &flags) == 0) {
+ return preg->err;
+ }
+
+
+ if (preg->re_nsub >= REG_MAX_PAREN)
+ FAIL(preg,REG_ERR_TOO_BIG);
+
+
+ preg->regstart = 0;
+ preg->reganch = 0;
+ preg->regmust = 0;
+ preg->regmlen = 0;
+ scan = 1;
+ if (OP(preg, regnext(preg, scan)) == END) {
+ scan = OPERAND(scan);
+
+
+ if (OP(preg, scan) == EXACTLY) {
+ preg->regstart = preg->program[OPERAND(scan)];
+ }
+ else if (OP(preg, scan) == BOL)
+ preg->reganch++;
+
+ if (flags&SPSTART) {
+ longest = 0;
+ len = 0;
+ for (; scan != 0; scan = regnext(preg, scan)) {
+ if (OP(preg, scan) == EXACTLY) {
+ int plen = str_int_len(preg->program + OPERAND(scan));
+ if (plen >= len) {
+ longest = OPERAND(scan);
+ len = plen;
+ }
+ }
+ }
+ preg->regmust = longest;
+ preg->regmlen = len;
+ }
+ }
+
+#ifdef DEBUG
+ regdump(preg);
+#endif
+
+ return 0;
+}
+
+static int reg(regex_t *preg, int paren, int *flagp )
+{
+ int ret;
+ int br;
+ int ender;
+ int parno = 0;
+ int flags;
+
+ *flagp = HASWIDTH;
+
+
+ if (paren) {
+ if (preg->regparse[0] == '?' && preg->regparse[1] == ':') {
+
+ preg->regparse += 2;
+ parno = -1;
+ }
+ else {
+ parno = ++preg->re_nsub;
+ }
+ ret = regnode(preg, OPEN+parno);
+ } else
+ ret = 0;
+
+
+ br = regbranch(preg, &flags);
+ if (br == 0)
+ return 0;
+ if (ret != 0)
+ regtail(preg, ret, br);
+ else
+ ret = br;
+ if (!(flags&HASWIDTH))
+ *flagp &= ~HASWIDTH;
+ *flagp |= flags&SPSTART;
+ while (*preg->regparse == '|') {
+ preg->regparse++;
+ br = regbranch(preg, &flags);
+ if (br == 0)
+ return 0;
+ regtail(preg, ret, br);
+ if (!(flags&HASWIDTH))
+ *flagp &= ~HASWIDTH;
+ *flagp |= flags&SPSTART;
+ }
+
+
+ ender = regnode(preg, (paren) ? CLOSE+parno : END);
+ regtail(preg, ret, ender);
+
+
+ for (br = ret; br != 0; br = regnext(preg, br))
+ regoptail(preg, br, ender);
+
+
+ if (paren && *preg->regparse++ != ')') {
+ preg->err = REG_ERR_UNMATCHED_PAREN;
+ return 0;
+ } else if (!paren && *preg->regparse != '\0') {
+ if (*preg->regparse == ')') {
+ preg->err = REG_ERR_UNMATCHED_PAREN;
+ return 0;
+ } else {
+ preg->err = REG_ERR_JUNK_ON_END;
+ return 0;
+ }
+ }
+
+ return(ret);
+}
+
+static int regbranch(regex_t *preg, int *flagp )
+{
+ int ret;
+ int chain;
+ int latest;
+ int flags;
+
+ *flagp = WORST;
+
+ ret = regnode(preg, BRANCH);
+ chain = 0;
+ while (*preg->regparse != '\0' && *preg->regparse != ')' &&
+ *preg->regparse != '|') {
+ latest = regpiece(preg, &flags);
+ if (latest == 0)
+ return 0;
+ *flagp |= flags&HASWIDTH;
+ if (chain == 0) {
+ *flagp |= flags&SPSTART;
+ }
+ else {
+ regtail(preg, chain, latest);
+ }
+ chain = latest;
+ }
+ if (chain == 0)
+ (void) regnode(preg, NOTHING);
+
+ return(ret);
+}
+
+static int regpiece(regex_t *preg, int *flagp)
+{
+ int ret;
+ char op;
+ int next;
+ int flags;
+ int min;
+ int max;
+
+ ret = regatom(preg, &flags);
+ if (ret == 0)
+ return 0;
+
+ op = *preg->regparse;
+ if (!ISMULT(op)) {
+ *flagp = flags;
+ return(ret);
+ }
+
+ if (!(flags&HASWIDTH) && op != '?') {
+ preg->err = REG_ERR_OPERAND_COULD_BE_EMPTY;
+ return 0;
+ }
+
+
+ if (op == '{') {
+ char *end;
+
+ min = strtoul(preg->regparse + 1, &end, 10);
+ if (end == preg->regparse + 1) {
+ preg->err = REG_ERR_BAD_COUNT;
+ return 0;
+ }
+ if (*end == '}') {
+ max = min;
+ }
+ else if (*end == '\0') {
+ preg->err = REG_ERR_UNMATCHED_BRACES;
+ return 0;
+ }
+ else {
+ preg->regparse = end;
+ max = strtoul(preg->regparse + 1, &end, 10);
+ if (*end != '}') {
+ preg->err = REG_ERR_UNMATCHED_BRACES;
+ return 0;
+ }
+ }
+ if (end == preg->regparse + 1) {
+ max = MAX_REP_COUNT;
+ }
+ else if (max < min || max >= 100) {
+ preg->err = REG_ERR_BAD_COUNT;
+ return 0;
+ }
+ if (min >= 100) {
+ preg->err = REG_ERR_BAD_COUNT;
+ return 0;
+ }
+
+ preg->regparse = strchr(preg->regparse, '}');
+ }
+ else {
+ min = (op == '+');
+ max = (op == '?' ? 1 : MAX_REP_COUNT);
+ }
+
+ if (preg->regparse[1] == '?') {
+ preg->regparse++;
+ next = reginsert(preg, flags & SIMPLE ? REPMIN : REPXMIN, 5, ret);
+ }
+ else {
+ next = reginsert(preg, flags & SIMPLE ? REP: REPX, 5, ret);
+ }
+ preg->program[ret + 2] = max;
+ preg->program[ret + 3] = min;
+ preg->program[ret + 4] = 0;
+
+ *flagp = (min) ? (WORST|HASWIDTH) : (WORST|SPSTART);
+
+ if (!(flags & SIMPLE)) {
+ int back = regnode(preg, BACK);
+ regtail(preg, back, ret);
+ regtail(preg, next, back);
+ }
+
+ preg->regparse++;
+ if (ISMULT(*preg->regparse)) {
+ preg->err = REG_ERR_NESTED_COUNT;
+ return 0;
+ }
+
+ return ret;
+}
+
+static void reg_addrange(regex_t *preg, int lower, int upper)
+{
+ if (lower > upper) {
+ reg_addrange(preg, upper, lower);
+ }
+
+ regc(preg, upper - lower + 1);
+ regc(preg, lower);
+}
+
+static void reg_addrange_str(regex_t *preg, const char *str)
+{
+ while (*str) {
+ reg_addrange(preg, *str, *str);
+ str++;
+ }
+}
+
+static int reg_utf8_tounicode_case(const char *s, int *uc, int upper)
+{
+ int l = utf8_tounicode(s, uc);
+ if (upper) {
+ *uc = utf8_upper(*uc);
+ }
+ return l;
+}
+
+static int hexdigitval(int c)
+{
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+ return -1;
+}
+
+static int parse_hex(const char *s, int n, int *uc)
+{
+ int val = 0;
+ int k;
+
+ for (k = 0; k < n; k++) {
+ int c = hexdigitval(*s++);
+ if (c == -1) {
+ break;
+ }
+ val = (val << 4) | c;
+ }
+ if (k) {
+ *uc = val;
+ }
+ return k;
+}
+
+static int reg_decode_escape(const char *s, int *ch)
+{
+ int n;
+ const char *s0 = s;
+
+ *ch = *s++;
+
+ switch (*ch) {
+ case 'b': *ch = '\b'; break;
+ case 'e': *ch = 27; break;
+ case 'f': *ch = '\f'; break;
+ case 'n': *ch = '\n'; break;
+ case 'r': *ch = '\r'; break;
+ case 't': *ch = '\t'; break;
+ case 'v': *ch = '\v'; break;
+ case 'u':
+ if (*s == '{') {
+
+ n = parse_hex(s + 1, 6, ch);
+ if (n > 0 && s[n + 1] == '}' && *ch >= 0 && *ch <= 0x1fffff) {
+ s += n + 2;
+ }
+ else {
+
+ *ch = 'u';
+ }
+ }
+ else if ((n = parse_hex(s, 4, ch)) > 0) {
+ s += n;
+ }
+ break;
+ case 'U':
+ if ((n = parse_hex(s, 8, ch)) > 0) {
+ s += n;
+ }
+ break;
+ case 'x':
+ if ((n = parse_hex(s, 2, ch)) > 0) {
+ s += n;
+ }
+ break;
+ case '\0':
+ s--;
+ *ch = '\\';
+ break;
+ }
+ return s - s0;
+}
+
+static int regatom(regex_t *preg, int *flagp)
+{
+ int ret;
+ int flags;
+ int nocase = (preg->cflags & REG_ICASE);
+
+ int ch;
+ int n = reg_utf8_tounicode_case(preg->regparse, &ch, nocase);
+
+ *flagp = WORST;
+
+ preg->regparse += n;
+ switch (ch) {
+
+ case '^':
+ ret = regnode(preg, BOL);
+ break;
+ case '$':
+ ret = regnode(preg, EOL);
+ break;
+ case '.':
+ ret = regnode(preg, ANY);
+ *flagp |= HASWIDTH|SIMPLE;
+ break;
+ case '[': {
+ const char *pattern = preg->regparse;
+
+ if (*pattern == '^') {
+ ret = regnode(preg, ANYBUT);
+ pattern++;
+ } else
+ ret = regnode(preg, ANYOF);
+
+
+ if (*pattern == ']' || *pattern == '-') {
+ reg_addrange(preg, *pattern, *pattern);
+ pattern++;
+ }
+
+ while (*pattern && *pattern != ']') {
+
+ int start;
+ int end;
+
+ enum {
+ CC_ALPHA, CC_ALNUM, CC_SPACE, CC_BLANK, CC_UPPER, CC_LOWER,
+ CC_DIGIT, CC_XDIGIT, CC_CNTRL, CC_GRAPH, CC_PRINT, CC_PUNCT,
+ CC_NUM
+ };
+ int cc;
+
+ pattern += reg_utf8_tounicode_case(pattern, &start, nocase);
+ if (start == '\\') {
+
+ switch (*pattern) {
+ case 's':
+ pattern++;
+ cc = CC_SPACE;
+ goto cc_switch;
+ case 'd':
+ pattern++;
+ cc = CC_DIGIT;
+ goto cc_switch;
+ case 'w':
+ pattern++;
+ reg_addrange(preg, '_', '_');
+ cc = CC_ALNUM;
+ goto cc_switch;
+ }
+ pattern += reg_decode_escape(pattern, &start);
+ if (start == 0) {
+ preg->err = REG_ERR_NULL_CHAR;
+ return 0;
+ }
+ }
+ if (pattern[0] == '-' && pattern[1] && pattern[1] != ']') {
+
+ pattern += utf8_tounicode(pattern, &end);
+ pattern += reg_utf8_tounicode_case(pattern, &end, nocase);
+ if (end == '\\') {
+ pattern += reg_decode_escape(pattern, &end);
+ if (end == 0) {
+ preg->err = REG_ERR_NULL_CHAR;
+ return 0;
+ }
+ }
+
+ reg_addrange(preg, start, end);
+ continue;
+ }
+ if (start == '[' && pattern[0] == ':') {
+ static const char *character_class[] = {
+ ":alpha:", ":alnum:", ":space:", ":blank:", ":upper:", ":lower:",
+ ":digit:", ":xdigit:", ":cntrl:", ":graph:", ":print:", ":punct:",
+ };
+
+ for (cc = 0; cc < CC_NUM; cc++) {
+ n = strlen(character_class[cc]);
+ if (strncmp(pattern, character_class[cc], n) == 0) {
+
+ pattern += n + 1;
+ break;
+ }
+ }
+ if (cc != CC_NUM) {
+cc_switch:
+ switch (cc) {
+ case CC_ALNUM:
+ reg_addrange(preg, '0', '9');
+
+ case CC_ALPHA:
+ if ((preg->cflags & REG_ICASE) == 0) {
+ reg_addrange(preg, 'a', 'z');
+ }
+ reg_addrange(preg, 'A', 'Z');
+ break;
+ case CC_SPACE:
+ reg_addrange_str(preg, " \t\r\n\f\v");
+ break;
+ case CC_BLANK:
+ reg_addrange_str(preg, " \t");
+ break;
+ case CC_UPPER:
+ reg_addrange(preg, 'A', 'Z');
+ break;
+ case CC_LOWER:
+ reg_addrange(preg, 'a', 'z');
+ break;
+ case CC_XDIGIT:
+ reg_addrange(preg, 'a', 'f');
+ reg_addrange(preg, 'A', 'F');
+
+ case CC_DIGIT:
+ reg_addrange(preg, '0', '9');
+ break;
+ case CC_CNTRL:
+ reg_addrange(preg, 0, 31);
+ reg_addrange(preg, 127, 127);
+ break;
+ case CC_PRINT:
+ reg_addrange(preg, ' ', '~');
+ break;
+ case CC_GRAPH:
+ reg_addrange(preg, '!', '~');
+ break;
+ case CC_PUNCT:
+ reg_addrange(preg, '!', '/');
+ reg_addrange(preg, ':', '@');
+ reg_addrange(preg, '[', '`');
+ reg_addrange(preg, '{', '~');
+ break;
+ }
+ continue;
+ }
+ }
+
+ reg_addrange(preg, start, start);
+ }
+ regc(preg, '\0');
+
+ if (*pattern) {
+ pattern++;
+ }
+ preg->regparse = pattern;
+
+ *flagp |= HASWIDTH|SIMPLE;
+ }
+ break;
+ case '(':
+ ret = reg(preg, 1, &flags);
+ if (ret == 0)
+ return 0;
+ *flagp |= flags&(HASWIDTH|SPSTART);
+ break;
+ case '\0':
+ case '|':
+ case ')':
+ preg->err = REG_ERR_INTERNAL;
+ return 0;
+ case '?':
+ case '+':
+ case '*':
+ case '{':
+ preg->err = REG_ERR_COUNT_FOLLOWS_NOTHING;
+ return 0;
+ case '\\':
+ ch = *preg->regparse++;
+ switch (ch) {
+ case '\0':
+ preg->err = REG_ERR_TRAILING_BACKSLASH;
+ return 0;
+ case 'A':
+ ret = regnode(preg, BOLX);
+ break;
+ case 'Z':
+ ret = regnode(preg, EOLX);
+ break;
+ case '<':
+ case 'm':
+ ret = regnode(preg, WORDA);
+ break;
+ case '>':
+ case 'M':
+ ret = regnode(preg, WORDZ);
+ break;
+ case 'd':
+ case 'D':
+ ret = regnode(preg, ch == 'd' ? ANYOF : ANYBUT);
+ reg_addrange(preg, '0', '9');
+ regc(preg, '\0');
+ *flagp |= HASWIDTH|SIMPLE;
+ break;
+ case 'w':
+ case 'W':
+ ret = regnode(preg, ch == 'w' ? ANYOF : ANYBUT);
+ if ((preg->cflags & REG_ICASE) == 0) {
+ reg_addrange(preg, 'a', 'z');
+ }
+ reg_addrange(preg, 'A', 'Z');
+ reg_addrange(preg, '0', '9');
+ reg_addrange(preg, '_', '_');
+ regc(preg, '\0');
+ *flagp |= HASWIDTH|SIMPLE;
+ break;
+ case 's':
+ case 'S':
+ ret = regnode(preg, ch == 's' ? ANYOF : ANYBUT);
+ reg_addrange_str(preg," \t\r\n\f\v");
+ regc(preg, '\0');
+ *flagp |= HASWIDTH|SIMPLE;
+ break;
+
+ default:
+
+
+ preg->regparse--;
+ goto de_fault;
+ }
+ break;
+ de_fault:
+ default: {
+ int added = 0;
+
+
+ preg->regparse -= n;
+
+ ret = regnode(preg, EXACTLY);
+
+
+
+ while (*preg->regparse && strchr(META, *preg->regparse) == NULL) {
+ n = reg_utf8_tounicode_case(preg->regparse, &ch, (preg->cflags & REG_ICASE));
+ if (ch == '\\' && preg->regparse[n]) {
+ if (strchr("<>mMwWdDsSAZ", preg->regparse[n])) {
+
+ break;
+ }
+ n += reg_decode_escape(preg->regparse + n, &ch);
+ if (ch == 0) {
+ preg->err = REG_ERR_NULL_CHAR;
+ return 0;
+ }
+ }
+
+
+ if (ISMULT(preg->regparse[n])) {
+
+ if (added) {
+
+ break;
+ }
+
+ regc(preg, ch);
+ added++;
+ preg->regparse += n;
+ break;
+ }
+
+
+ regc(preg, ch);
+ added++;
+ preg->regparse += n;
+ }
+ regc(preg, '\0');
+
+ *flagp |= HASWIDTH;
+ if (added == 1)
+ *flagp |= SIMPLE;
+ break;
+ }
+ break;
+ }
+
+ return(ret);
+}
+
+static void reg_grow(regex_t *preg, int n)
+{
+ if (preg->p + n >= preg->proglen) {
+ preg->proglen = (preg->p + n) * 2;
+ preg->program = realloc(preg->program, preg->proglen * sizeof(int));
+ }
+}
+
+
+static int regnode(regex_t *preg, int op)
+{
+ reg_grow(preg, 2);
+
+
+ preg->program[preg->p++] = op;
+ preg->program[preg->p++] = 0;
+
+
+ return preg->p - 2;
+}
+
+static void regc(regex_t *preg, int b )
+{
+ reg_grow(preg, 1);
+ preg->program[preg->p++] = b;
+}
+
+static int reginsert(regex_t *preg, int op, int size, int opnd )
+{
+ reg_grow(preg, size);
+
+
+ memmove(preg->program + opnd + size, preg->program + opnd, sizeof(int) * (preg->p - opnd));
+
+ memset(preg->program + opnd, 0, sizeof(int) * size);
+
+ preg->program[opnd] = op;
+
+ preg->p += size;
+
+ return opnd + size;
+}
+
+static void regtail(regex_t *preg, int p, int val)
+{
+ int scan;
+ int temp;
+ int offset;
+
+
+ scan = p;
+ for (;;) {
+ temp = regnext(preg, scan);
+ if (temp == 0)
+ break;
+ scan = temp;
+ }
+
+ if (OP(preg, scan) == BACK)
+ offset = scan - val;
+ else
+ offset = val - scan;
+
+ preg->program[scan + 1] = offset;
+}
+
+
+static void regoptail(regex_t *preg, int p, int val )
+{
+
+ if (p != 0 && OP(preg, p) == BRANCH) {
+ regtail(preg, OPERAND(p), val);
+ }
+}
+
+
+static int regtry(regex_t *preg, const char *string );
+static int regmatch(regex_t *preg, int prog);
+static int regrepeat(regex_t *preg, int p, int max);
+
+int regexec(regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags)
+{
+ const char *s;
+ int scan;
+
+
+ if (preg == NULL || preg->program == NULL || string == NULL) {
+ return REG_ERR_NULL_ARGUMENT;
+ }
+
+
+ if (*preg->program != REG_MAGIC) {
+ return REG_ERR_CORRUPTED;
+ }
+
+#ifdef DEBUG
+ fprintf(stderr, "regexec: %s\n", string);
+ regdump(preg);
+#endif
+
+ preg->eflags = eflags;
+ preg->pmatch = pmatch;
+ preg->nmatch = nmatch;
+ preg->start = string;
+
+
+ for (scan = OPERAND(1); scan != 0; scan += regopsize(preg, scan)) {
+ int op = OP(preg, scan);
+ if (op == END)
+ break;
+ if (op == REPX || op == REPXMIN)
+ preg->program[scan + 4] = 0;
+ }
+
+
+ if (preg->regmust != 0) {
+ s = string;
+ while ((s = str_find(s, preg->program[preg->regmust], preg->cflags & REG_ICASE)) != NULL) {
+ if (prefix_cmp(preg->program + preg->regmust, preg->regmlen, s, preg->cflags & REG_ICASE) >= 0) {
+ break;
+ }
+ s++;
+ }
+ if (s == NULL)
+ return REG_NOMATCH;
+ }
+
+
+ preg->regbol = string;
+
+
+ if (preg->reganch) {
+ if (eflags & REG_NOTBOL) {
+
+ goto nextline;
+ }
+ while (1) {
+ if (regtry(preg, string)) {
+ return REG_NOERROR;
+ }
+ if (*string) {
+nextline:
+ if (preg->cflags & REG_NEWLINE) {
+
+ string = strchr(string, '\n');
+ if (string) {
+ preg->regbol = ++string;
+ continue;
+ }
+ }
+ }
+ return REG_NOMATCH;
+ }
+ }
+
+
+ s = string;
+ if (preg->regstart != '\0') {
+
+ while ((s = str_find(s, preg->regstart, preg->cflags & REG_ICASE)) != NULL) {
+ if (regtry(preg, s))
+ return REG_NOERROR;
+ s++;
+ }
+ }
+ else
+
+ while (1) {
+ if (regtry(preg, s))
+ return REG_NOERROR;
+ if (*s == '\0') {
+ break;
+ }
+ else {
+ int c;
+ s += utf8_tounicode(s, &c);
+ }
+ }
+
+
+ return REG_NOMATCH;
+}
+
+
+static int regtry( regex_t *preg, const char *string )
+{
+ int i;
+
+ preg->reginput = string;
+
+ for (i = 0; i < preg->nmatch; i++) {
+ preg->pmatch[i].rm_so = -1;
+ preg->pmatch[i].rm_eo = -1;
+ }
+ if (regmatch(preg, 1)) {
+ preg->pmatch[0].rm_so = string - preg->start;
+ preg->pmatch[0].rm_eo = preg->reginput - preg->start;
+ return(1);
+ } else
+ return(0);
+}
+
+static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase)
+{
+ const char *s = string;
+ while (proglen && *s) {
+ int ch;
+ int n = reg_utf8_tounicode_case(s, &ch, nocase);
+ if (ch != *prog) {
+ return -1;
+ }
+ prog++;
+ s += n;
+ proglen--;
+ }
+ if (proglen == 0) {
+ return s - string;
+ }
+ return -1;
+}
+
+static int reg_range_find(const int *range, int c)
+{
+ while (*range) {
+
+ if (c >= range[1] && c <= (range[0] + range[1] - 1)) {
+ return 1;
+ }
+ range += 2;
+ }
+ return 0;
+}
+
+static const char *str_find(const char *string, int c, int nocase)
+{
+ if (nocase) {
+
+ c = utf8_upper(c);
+ }
+ while (*string) {
+ int ch;
+ int n = reg_utf8_tounicode_case(string, &ch, nocase);
+ if (c == ch) {
+ return string;
+ }
+ string += n;
+ }
+ return NULL;
+}
+
+static int reg_iseol(regex_t *preg, int ch)
+{
+ if (preg->cflags & REG_NEWLINE) {
+ return ch == '\0' || ch == '\n';
+ }
+ else {
+ return ch == '\0';
+ }
+}
+
+static int regmatchsimplerepeat(regex_t *preg, int scan, int matchmin)
+{
+ int nextch = '\0';
+ const char *save;
+ int no;
+ int c;
+
+ int max = preg->program[scan + 2];
+ int min = preg->program[scan + 3];
+ int next = regnext(preg, scan);
+
+ if (OP(preg, next) == EXACTLY) {
+ nextch = preg->program[OPERAND(next)];
+ }
+ save = preg->reginput;
+ no = regrepeat(preg, scan + 5, max);
+ if (no < min) {
+ return 0;
+ }
+ if (matchmin) {
+
+ max = no;
+ no = min;
+ }
+
+ while (1) {
+ if (matchmin) {
+ if (no > max) {
+ break;
+ }
+ }
+ else {
+ if (no < min) {
+ break;
+ }
+ }
+ preg->reginput = save + utf8_index(save, no);
+ reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
+
+ if (reg_iseol(preg, nextch) || c == nextch) {
+ if (regmatch(preg, next)) {
+ return(1);
+ }
+ }
+ if (matchmin) {
+
+ no++;
+ }
+ else {
+
+ no--;
+ }
+ }
+ return(0);
+}
+
+static int regmatchrepeat(regex_t *preg, int scan, int matchmin)
+{
+ int *scanpt = preg->program + scan;
+
+ int max = scanpt[2];
+ int min = scanpt[3];
+
+
+ if (scanpt[4] < min) {
+
+ scanpt[4]++;
+ if (regmatch(preg, scan + 5)) {
+ return 1;
+ }
+ scanpt[4]--;
+ return 0;
+ }
+ if (scanpt[4] > max) {
+ return 0;
+ }
+
+ if (matchmin) {
+
+ if (regmatch(preg, regnext(preg, scan))) {
+ return 1;
+ }
+
+ scanpt[4]++;
+ if (regmatch(preg, scan + 5)) {
+ return 1;
+ }
+ scanpt[4]--;
+ return 0;
+ }
+
+ if (scanpt[4] < max) {
+ scanpt[4]++;
+ if (regmatch(preg, scan + 5)) {
+ return 1;
+ }
+ scanpt[4]--;
+ }
+
+ return regmatch(preg, regnext(preg, scan));
+}
+
+
+static int regmatch(regex_t *preg, int prog)
+{
+ int scan;
+ int next;
+ const char *save;
+
+ scan = prog;
+
+#ifdef DEBUG
+ if (scan != 0 && regnarrate)
+ fprintf(stderr, "%s(\n", regprop(scan));
+#endif
+ while (scan != 0) {
+ int n;
+ int c;
+#ifdef DEBUG
+ if (regnarrate) {
+ fprintf(stderr, "%3d: %s...\n", scan, regprop(OP(preg, scan)));
+ }
+#endif
+ next = regnext(preg, scan);
+ n = reg_utf8_tounicode_case(preg->reginput, &c, (preg->cflags & REG_ICASE));
+
+ switch (OP(preg, scan)) {
+ case BOLX:
+ if ((preg->eflags & REG_NOTBOL)) {
+ return(0);
+ }
+
+ case BOL:
+ if (preg->reginput != preg->regbol) {
+ return(0);
+ }
+ break;
+ case EOLX:
+ if (c != 0) {
+
+ return 0;
+ }
+ break;
+ case EOL:
+ if (!reg_iseol(preg, c)) {
+ return(0);
+ }
+ break;
+ case WORDA:
+
+ if ((!isalnum(UCHAR(c))) && c != '_')
+ return(0);
+
+ if (preg->reginput > preg->regbol &&
+ (isalnum(UCHAR(preg->reginput[-1])) || preg->reginput[-1] == '_'))
+ return(0);
+ break;
+ case WORDZ:
+
+ if (preg->reginput > preg->regbol) {
+
+ if (reg_iseol(preg, c) || !isalnum(UCHAR(c)) || c != '_') {
+ c = preg->reginput[-1];
+
+ if (isalnum(UCHAR(c)) || c == '_') {
+ break;
+ }
+ }
+ }
+
+ return(0);
+
+ case ANY:
+ if (reg_iseol(preg, c))
+ return 0;
+ preg->reginput += n;
+ break;
+ case EXACTLY: {
+ int opnd;
+ int len;
+ int slen;
+
+ opnd = OPERAND(scan);
+ len = str_int_len(preg->program + opnd);
+
+ slen = prefix_cmp(preg->program + opnd, len, preg->reginput, preg->cflags & REG_ICASE);
+ if (slen < 0) {
+ return(0);
+ }
+ preg->reginput += slen;
+ }
+ break;
+ case ANYOF:
+ if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) == 0) {
+ return(0);
+ }
+ preg->reginput += n;
+ break;
+ case ANYBUT:
+ if (reg_iseol(preg, c) || reg_range_find(preg->program + OPERAND(scan), c) != 0) {
+ return(0);
+ }
+ preg->reginput += n;
+ break;
+ case NOTHING:
+ break;
+ case BACK:
+ break;
+ case BRANCH:
+ if (OP(preg, next) != BRANCH)
+ next = OPERAND(scan);
+ else {
+ do {
+ save = preg->reginput;
+ if (regmatch(preg, OPERAND(scan))) {
+ return(1);
+ }
+ preg->reginput = save;
+ scan = regnext(preg, scan);
+ } while (scan != 0 && OP(preg, scan) == BRANCH);
+ return(0);
+
+ }
+ break;
+ case REP:
+ case REPMIN:
+ return regmatchsimplerepeat(preg, scan, OP(preg, scan) == REPMIN);
+
+ case REPX:
+ case REPXMIN:
+ return regmatchrepeat(preg, scan, OP(preg, scan) == REPXMIN);
+
+ case END:
+ return 1;
+
+ case OPENNC:
+ case CLOSENC:
+ return regmatch(preg, next);
+
+ default:
+ if (OP(preg, scan) >= OPEN+1 && OP(preg, scan) < CLOSE_END) {
+ save = preg->reginput;
+ if (regmatch(preg, next)) {
+ if (OP(preg, scan) < CLOSE) {
+ int no = OP(preg, scan) - OPEN;
+ if (no < preg->nmatch && preg->pmatch[no].rm_so == -1) {
+ preg->pmatch[no].rm_so = save - preg->start;
+ }
+ }
+ else {
+ int no = OP(preg, scan) - CLOSE;
+ if (no < preg->nmatch && preg->pmatch[no].rm_eo == -1) {
+ preg->pmatch[no].rm_eo = save - preg->start;
+ }
+ }
+ return(1);
+ }
+ return(0);
+ }
+ return REG_ERR_INTERNAL;
+ }
+
+ scan = next;
+ }
+
+ return REG_ERR_INTERNAL;
+}
+
+static int regrepeat(regex_t *preg, int p, int max)
+{
+ int count = 0;
+ const char *scan;
+ int opnd;
+ int ch;
+ int n;
+
+ scan = preg->reginput;
+ opnd = OPERAND(p);
+ switch (OP(preg, p)) {
+ case ANY:
+
+ while (!reg_iseol(preg, *scan) && count < max) {
+ count++;
+ scan++;
+ }
+ break;
+ case EXACTLY:
+ while (count < max) {
+ n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
+ if (preg->program[opnd] != ch) {
+ break;
+ }
+ count++;
+ scan += n;
+ }
+ break;
+ case ANYOF:
+ while (count < max) {
+ n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
+ if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) == 0) {
+ break;
+ }
+ count++;
+ scan += n;
+ }
+ break;
+ case ANYBUT:
+ while (count < max) {
+ n = reg_utf8_tounicode_case(scan, &ch, preg->cflags & REG_ICASE);
+ if (reg_iseol(preg, ch) || reg_range_find(preg->program + opnd, ch) != 0) {
+ break;
+ }
+ count++;
+ scan += n;
+ }
+ break;
+ default:
+ preg->err = REG_ERR_INTERNAL;
+ count = 0;
+ break;
+ }
+ preg->reginput = scan;
+
+ return(count);
+}
+
+static int regnext(regex_t *preg, int p )
+{
+ int offset;
+
+ offset = NEXT(preg, p);
+
+ if (offset == 0)
+ return 0;
+
+ if (OP(preg, p) == BACK)
+ return(p-offset);
+ else
+ return(p+offset);
+}
+
+static int regopsize(regex_t *preg, int p )
+{
+
+ switch (OP(preg, p)) {
+ case REP:
+ case REPMIN:
+ case REPX:
+ case REPXMIN:
+ return 5;
+
+ case ANYOF:
+ case ANYBUT:
+ case EXACTLY: {
+ int s = p + 2;
+ while (preg->program[s++]) {
+ }
+ return s - p;
+ }
+ }
+ return 2;
+}
+
+
+size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
+{
+ static const char *error_strings[] = {
+ "success",
+ "no match",
+ "bad pattern",
+ "null argument",
+ "unknown error",
+ "too big",
+ "out of memory",
+ "too many ()",
+ "parentheses () not balanced",
+ "braces {} not balanced",
+ "invalid repetition count(s)",
+ "extra characters",
+ "*+ of empty atom",
+ "nested count",
+ "internal error",
+ "count follows nothing",
+ "trailing backslash",
+ "corrupted program",
+ "contains null char",
+ };
+ const char *err;
+
+ if (errcode < 0 || errcode >= REG_ERR_NUM) {
+ err = "Bad error code";
+ }
+ else {
+ err = error_strings[errcode];
+ }
+
+ return snprintf(errbuf, errbuf_size, "%s", err);
+}
+
+void regfree(regex_t *preg)
+{
+ free(preg->program);
+}
+
+#endif
+#include
+
+void Jim_SetResultErrno(Jim_Interp *interp, const char *msg)
+{
+ Jim_SetResultFormatted(interp, "%s: %s", msg, strerror(Jim_Errno()));
+}
+
+#if defined(__MINGW32__)
+#include
+
+int Jim_Errno(void)
+{
+ switch (GetLastError()) {
+ case ERROR_FILE_NOT_FOUND: return ENOENT;
+ case ERROR_PATH_NOT_FOUND: return ENOENT;
+ case ERROR_TOO_MANY_OPEN_FILES: return EMFILE;
+ case ERROR_ACCESS_DENIED: return EACCES;
+ case ERROR_INVALID_HANDLE: return EBADF;
+ case ERROR_BAD_ENVIRONMENT: return E2BIG;
+ case ERROR_BAD_FORMAT: return ENOEXEC;
+ case ERROR_INVALID_ACCESS: return EACCES;
+ case ERROR_INVALID_DRIVE: return ENOENT;
+ case ERROR_CURRENT_DIRECTORY: return EACCES;
+ case ERROR_NOT_SAME_DEVICE: return EXDEV;
+ case ERROR_NO_MORE_FILES: return ENOENT;
+ case ERROR_WRITE_PROTECT: return EROFS;
+ case ERROR_BAD_UNIT: return ENXIO;
+ case ERROR_NOT_READY: return EBUSY;
+ case ERROR_BAD_COMMAND: return EIO;
+ case ERROR_CRC: return EIO;
+ case ERROR_BAD_LENGTH: return EIO;
+ case ERROR_SEEK: return EIO;
+ case ERROR_WRITE_FAULT: return EIO;
+ case ERROR_READ_FAULT: return EIO;
+ case ERROR_GEN_FAILURE: return EIO;
+ case ERROR_SHARING_VIOLATION: return EACCES;
+ case ERROR_LOCK_VIOLATION: return EACCES;
+ case ERROR_SHARING_BUFFER_EXCEEDED: return ENFILE;
+ case ERROR_HANDLE_DISK_FULL: return ENOSPC;
+ case ERROR_NOT_SUPPORTED: return ENODEV;
+ case ERROR_REM_NOT_LIST: return EBUSY;
+ case ERROR_DUP_NAME: return EEXIST;
+ case ERROR_BAD_NETPATH: return ENOENT;
+ case ERROR_NETWORK_BUSY: return EBUSY;
+ case ERROR_DEV_NOT_EXIST: return ENODEV;
+ case ERROR_TOO_MANY_CMDS: return EAGAIN;
+ case ERROR_ADAP_HDW_ERR: return EIO;
+ case ERROR_BAD_NET_RESP: return EIO;
+ case ERROR_UNEXP_NET_ERR: return EIO;
+ case ERROR_NETNAME_DELETED: return ENOENT;
+ case ERROR_NETWORK_ACCESS_DENIED: return EACCES;
+ case ERROR_BAD_DEV_TYPE: return ENODEV;
+ case ERROR_BAD_NET_NAME: return ENOENT;
+ case ERROR_TOO_MANY_NAMES: return ENFILE;
+ case ERROR_TOO_MANY_SESS: return EIO;
+ case ERROR_SHARING_PAUSED: return EAGAIN;
+ case ERROR_REDIR_PAUSED: return EAGAIN;
+ case ERROR_FILE_EXISTS: return EEXIST;
+ case ERROR_CANNOT_MAKE: return ENOSPC;
+ case ERROR_OUT_OF_STRUCTURES: return ENFILE;
+ case ERROR_ALREADY_ASSIGNED: return EEXIST;
+ case ERROR_INVALID_PASSWORD: return EPERM;
+ case ERROR_NET_WRITE_FAULT: return EIO;
+ case ERROR_NO_PROC_SLOTS: return EAGAIN;
+ case ERROR_DISK_CHANGE: return EXDEV;
+ case ERROR_BROKEN_PIPE: return EPIPE;
+ case ERROR_OPEN_FAILED: return ENOENT;
+ case ERROR_DISK_FULL: return ENOSPC;
+ case ERROR_NO_MORE_SEARCH_HANDLES: return EMFILE;
+ case ERROR_INVALID_TARGET_HANDLE: return EBADF;
+ case ERROR_INVALID_NAME: return ENOENT;
+ case ERROR_PROC_NOT_FOUND: return ESRCH;
+ case ERROR_WAIT_NO_CHILDREN: return ECHILD;
+ case ERROR_CHILD_NOT_COMPLETE: return ECHILD;
+ case ERROR_DIRECT_ACCESS_HANDLE: return EBADF;
+ case ERROR_SEEK_ON_DEVICE: return ESPIPE;
+ case ERROR_BUSY_DRIVE: return EAGAIN;
+ case ERROR_DIR_NOT_EMPTY: return EEXIST;
+ case ERROR_NOT_LOCKED: return EACCES;
+ case ERROR_BAD_PATHNAME: return ENOENT;
+ case ERROR_LOCK_FAILED: return EACCES;
+ case ERROR_ALREADY_EXISTS: return EEXIST;
+ case ERROR_FILENAME_EXCED_RANGE: return ENAMETOOLONG;
+ case ERROR_BAD_PIPE: return EPIPE;
+ case ERROR_PIPE_BUSY: return EAGAIN;
+ case ERROR_PIPE_NOT_CONNECTED: return EPIPE;
+ case ERROR_DIRECTORY: return ENOTDIR;
+ }
+ return EINVAL;
+}
+
+pidtype waitpid(pidtype pid, int *status, int nohang)
+{
+ DWORD ret = WaitForSingleObject(pid, nohang ? 0 : INFINITE);
+ if (ret == WAIT_TIMEOUT || ret == WAIT_FAILED) {
+
+ return JIM_BAD_PID;
+ }
+ GetExitCodeProcess(pid, &ret);
+ *status = ret;
+ CloseHandle(pid);
+ return pid;
+}
+
+int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file)
+{
+ char name[MAX_PATH];
+ HANDLE handle;
+
+ if (!GetTempPath(MAX_PATH, name) || !GetTempFileName(name, filename_template ? filename_template : "JIM", 0, name)) {
+ return -1;
+ }
+
+ handle = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
+ CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | (unlink_file ? FILE_FLAG_DELETE_ON_CLOSE : 0),
+ NULL);
+
+ if (handle == INVALID_HANDLE_VALUE) {
+ goto error;
+ }
+
+ Jim_SetResultString(interp, name, -1);
+ return _open_osfhandle((int)handle, _O_RDWR | _O_TEXT);
+
+ error:
+ Jim_SetResultErrno(interp, name);
+ DeleteFile(name);
+ return -1;
+}
+
+int Jim_OpenForWrite(const char *filename, int append)
+{
+ if (strcmp(filename, "/dev/null") == 0) {
+ filename = "nul:";
+ }
+ int fd = _open(filename, _O_WRONLY | _O_CREAT | _O_TEXT | (append ? _O_APPEND : _O_TRUNC), _S_IREAD | _S_IWRITE);
+ if (fd >= 0 && append) {
+
+ _lseek(fd, 0L, SEEK_END);
+ }
+ return fd;
+}
+
+int Jim_OpenForRead(const char *filename)
+{
+ if (strcmp(filename, "/dev/null") == 0) {
+ filename = "nul:";
+ }
+ return _open(filename, _O_RDONLY | _O_TEXT, 0);
+}
+
+#elif defined(HAVE_UNISTD_H)
+
+
+
+int Jim_MakeTempFile(Jim_Interp *interp, const char *filename_template, int unlink_file)
+{
+ int fd;
+ mode_t mask;
+ Jim_Obj *filenameObj;
+
+ if (filename_template == NULL) {
+ const char *tmpdir = getenv("TMPDIR");
+ if (tmpdir == NULL || *tmpdir == '\0' || access(tmpdir, W_OK) != 0) {
+ tmpdir = "/tmp/";
+ }
+ filenameObj = Jim_NewStringObj(interp, tmpdir, -1);
+ if (tmpdir[0] && tmpdir[strlen(tmpdir) - 1] != '/') {
+ Jim_AppendString(interp, filenameObj, "/", 1);
+ }
+ Jim_AppendString(interp, filenameObj, "tcl.tmp.XXXXXX", -1);
+ }
+ else {
+ filenameObj = Jim_NewStringObj(interp, filename_template, -1);
+ }
+
+
+ mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
+#ifdef HAVE_MKSTEMP
+ fd = mkstemp(filenameObj->bytes);
+#else
+ if (mktemp(filenameObj->bytes) == NULL) {
+ fd = -1;
+ }
+ else {
+ fd = open(filenameObj->bytes, O_RDWR | O_CREAT | O_TRUNC);
+ }
+#endif
+ umask(mask);
+ if (fd < 0) {
+ Jim_SetResultErrno(interp, Jim_String(filenameObj));
+ Jim_FreeNewObj(interp, filenameObj);
+ return -1;
+ }
+ if (unlink_file) {
+ remove(Jim_String(filenameObj));
+ }
+
+ Jim_SetResult(interp, filenameObj);
+ return fd;
+}
+
+int Jim_OpenForWrite(const char *filename, int append)
+{
+ return open(filename, O_WRONLY | O_CREAT | (append ? O_APPEND : O_TRUNC), 0666);
+}
+
+int Jim_OpenForRead(const char *filename)
+{
+ return open(filename, O_RDONLY, 0);
+}
+
+#endif
+
+#if defined(_WIN32) || defined(WIN32)
+#ifndef STRICT
+#define STRICT
+#endif
+#define WIN32_LEAN_AND_MEAN
+#include
+
+#if defined(HAVE_DLOPEN_COMPAT)
+void *dlopen(const char *path, int mode)
+{
+ JIM_NOTUSED(mode);
+
+ return (void *)LoadLibraryA(path);
+}
+
+int dlclose(void *handle)
+{
+ FreeLibrary((HANDLE)handle);
+ return 0;
+}
+
+void *dlsym(void *handle, const char *symbol)
+{
+ return GetProcAddress((HMODULE)handle, symbol);
+}
+
+char *dlerror(void)
+{
+ static char msg[121];
+ FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
+ LANG_NEUTRAL, msg, sizeof(msg) - 1, NULL);
+ return msg;
+}
+#endif
+
+#ifdef _MSC_VER
+
+#include
+
+
+int gettimeofday(struct timeval *tv, void *unused)
+{
+ struct _timeb tb;
+
+ _ftime(&tb);
+ tv->tv_sec = tb.time;
+ tv->tv_usec = tb.millitm * 1000;
+
+ return 0;
+}
+
+
+DIR *opendir(const char *name)
+{
+ DIR *dir = 0;
+
+ if (name && name[0]) {
+ size_t base_length = strlen(name);
+ const char *all =
+ strchr("/\\", name[base_length - 1]) ? "*" : "/*";
+
+ if ((dir = (DIR *) Jim_Alloc(sizeof *dir)) != 0 &&
+ (dir->name = (char *)Jim_Alloc(base_length + strlen(all) + 1)) != 0) {
+ strcat(strcpy(dir->name, name), all);
+
+ if ((dir->handle = (long)_findfirst(dir->name, &dir->info)) != -1)
+ dir->result.d_name = 0;
+ else {
+ Jim_Free(dir->name);
+ Jim_Free(dir);
+ dir = 0;
+ }
+ }
+ else {
+ Jim_Free(dir);
+ dir = 0;
+ errno = ENOMEM;
+ }
+ }
+ else {
+ errno = EINVAL;
+ }
+ return dir;
+}
+
+int closedir(DIR * dir)
+{
+ int result = -1;
+
+ if (dir) {
+ if (dir->handle != -1)
+ result = _findclose(dir->handle);
+ Jim_Free(dir->name);
+ Jim_Free(dir);
+ }
+ if (result == -1)
+ errno = EBADF;
+ return result;
+}
+
+struct dirent *readdir(DIR * dir)
+{
+ struct dirent *result = 0;
+
+ if (dir && dir->handle != -1) {
+ if (!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1) {
+ result = &dir->result;
+ result->d_name = dir->info.name;
+ }
+ }
+ else {
+ errno = EBADF;
+ }
+ return result;
+}
+#endif
+#endif
+#include
+#include
+
+
+
+
+
+
+#ifndef SIGPIPE
+#define SIGPIPE 13
+#endif
+#ifndef SIGINT
+#define SIGINT 2
+#endif
+
+const char *Jim_SignalId(int sig)
+{
+ static char buf[10];
+ switch (sig) {
+ case SIGINT: return "SIGINT";
+ case SIGPIPE: return "SIGPIPE";
+
+ }
+ snprintf(buf, sizeof(buf), "%d", sig);
+ return buf;
+}
+#ifndef JIM_BOOTSTRAP_LIB_ONLY
+#include
+#include
+
+
+#ifdef USE_LINENOISE
+#ifdef HAVE_UNISTD_H
+ #include
+#endif
+#ifdef HAVE_SYS_STAT_H
+ #include
+#endif
+#include "linenoise.h"
+#else
+#define MAX_LINE_LEN 512
+#endif
+
+#ifdef USE_LINENOISE
+static void JimCompletionCallback(const char *prefix, linenoiseCompletions *comp, void *userdata);
+static const char completion_callback_assoc_key[] = "interactive-completion";
+#endif
+
+char *Jim_HistoryGetline(Jim_Interp *interp, const char *prompt)
+{
+#ifdef USE_LINENOISE
+ struct JimCompletionInfo *compinfo = Jim_GetAssocData(interp, completion_callback_assoc_key);
+ char *result;
+ Jim_Obj *objPtr;
+ long mlmode = 0;
+ if (compinfo) {
+ linenoiseSetCompletionCallback(JimCompletionCallback, compinfo);
+ }
+ objPtr = Jim_GetVariableStr(interp, "history::multiline", JIM_NONE);
+ if (objPtr && Jim_GetLong(interp, objPtr, &mlmode) == JIM_NONE) {
+ linenoiseSetMultiLine(mlmode);
+ }
+
+ result = linenoise(prompt);
+
+ linenoiseSetCompletionCallback(NULL, NULL);
+ return result;
+#else
+ int len;
+ char *line = malloc(MAX_LINE_LEN);
+
+ fputs(prompt, stdout);
+ fflush(stdout);
+
+ if (fgets(line, MAX_LINE_LEN, stdin) == NULL) {
+ free(line);
+ return NULL;
+ }
+ len = strlen(line);
+ if (len && line[len - 1] == '\n') {
+ line[len - 1] = '\0';
+ }
+ return line;
+#endif
+}
+
+void Jim_HistoryLoad(const char *filename)
+{
+#ifdef USE_LINENOISE
+ linenoiseHistoryLoad(filename);
+#endif
+}
+
+void Jim_HistoryAdd(const char *line)
+{
+#ifdef USE_LINENOISE
+ linenoiseHistoryAdd(line);
+#endif
+}
+
+void Jim_HistorySave(const char *filename)
+{
+#ifdef USE_LINENOISE
+#ifdef HAVE_UMASK
+ mode_t mask;
+
+ mask = umask(S_IXUSR | S_IRWXG | S_IRWXO);
+#endif
+ linenoiseHistorySave(filename);
+#ifdef HAVE_UMASK
+ umask(mask);
+#endif
+#endif
+}
+
+void Jim_HistoryShow(void)
+{
+#ifdef USE_LINENOISE
+
+ int i;
+ int len;
+ char **history = linenoiseHistory(&len);
+ for (i = 0; i < len; i++) {
+ printf("%4d %s\n", i + 1, history[i]);
+ }
+#endif
+}
+
+#ifdef USE_LINENOISE
+struct JimCompletionInfo {
+ Jim_Interp *interp;
+ Jim_Obj *command;
+};
+
+static void JimCompletionCallback(const char *prefix, linenoiseCompletions *comp, void *userdata)
+{
+ struct JimCompletionInfo *info = (struct JimCompletionInfo *)userdata;
+ Jim_Obj *objv[2];
+ int ret;
+
+ objv[0] = info->command;
+ objv[1] = Jim_NewStringObj(info->interp, prefix, -1);
+
+ ret = Jim_EvalObjVector(info->interp, 2, objv);
+
+
+ if (ret == JIM_OK) {
+ int i;
+ Jim_Obj *listObj = Jim_GetResult(info->interp);
+ int len = Jim_ListLength(info->interp, listObj);
+ for (i = 0; i < len; i++) {
+ linenoiseAddCompletion(comp, Jim_String(Jim_ListGetIndex(info->interp, listObj, i)));
+ }
+ }
+}
+
+static void JimHistoryFreeCompletion(Jim_Interp *interp, void *data)
+{
+ struct JimCompletionInfo *compinfo = data;
+
+ Jim_DecrRefCount(interp, compinfo->command);
+
+ Jim_Free(compinfo);
+}
+#endif
+
+void Jim_HistorySetCompletion(Jim_Interp *interp, Jim_Obj *commandObj)
+{
+#ifdef USE_LINENOISE
+ if (commandObj) {
+
+ Jim_IncrRefCount(commandObj);
+ }
+
+ Jim_DeleteAssocData(interp, completion_callback_assoc_key);
+
+ if (commandObj) {
+ struct JimCompletionInfo *compinfo = Jim_Alloc(sizeof(*compinfo));
+ compinfo->interp = interp;
+ compinfo->command = commandObj;
+
+ Jim_SetAssocData(interp, completion_callback_assoc_key, JimHistoryFreeCompletion, compinfo);
+ }
+#endif
+}
+
+int Jim_InteractivePrompt(Jim_Interp *interp)
+{
+ int retcode = JIM_OK;
+ char *history_file = NULL;
+#ifdef USE_LINENOISE
+ const char *home;
+
+ home = getenv("HOME");
+ if (home && isatty(STDIN_FILENO)) {
+ int history_len = strlen(home) + sizeof("/.jim_history");
+ history_file = Jim_Alloc(history_len);
+ snprintf(history_file, history_len, "%s/.jim_history", home);
+ Jim_HistoryLoad(history_file);
+ }
+
+ Jim_HistorySetCompletion(interp, Jim_NewStringObj(interp, "tcl::autocomplete", -1));
+#endif
+
+ printf("Welcome to Jim version %d.%d\n",
+ JIM_VERSION / 100, JIM_VERSION % 100);
+ Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, "1");
+
+ while (1) {
+ Jim_Obj *scriptObjPtr;
+ const char *result;
+ int reslen;
+ char prompt[20];
+
+ if (retcode != JIM_OK) {
+ const char *retcodestr = Jim_ReturnCode(retcode);
+
+ if (*retcodestr == '?') {
+ snprintf(prompt, sizeof(prompt) - 3, "[%d] . ", retcode);
+ }
+ else {
+ snprintf(prompt, sizeof(prompt) - 3, "[%s] . ", retcodestr);
+ }
+ }
+ else {
+ strcpy(prompt, ". ");
+ }
+
+ scriptObjPtr = Jim_NewStringObj(interp, "", 0);
+ Jim_IncrRefCount(scriptObjPtr);
+ while (1) {
+ char state;
+ char *line;
+
+ line = Jim_HistoryGetline(interp, prompt);
+ if (line == NULL) {
+ if (errno == EINTR) {
+ continue;
+ }
+ Jim_DecrRefCount(interp, scriptObjPtr);
+ retcode = JIM_OK;
+ goto out;
+ }
+ if (Jim_Length(scriptObjPtr) != 0) {
+
+ Jim_AppendString(interp, scriptObjPtr, "\n", 1);
+ }
+ Jim_AppendString(interp, scriptObjPtr, line, -1);
+ free(line);
+ if (Jim_ScriptIsComplete(interp, scriptObjPtr, &state))
+ break;
+
+ snprintf(prompt, sizeof(prompt), "%c> ", state);
+ }
+#ifdef USE_LINENOISE
+ if (strcmp(Jim_String(scriptObjPtr), "h") == 0) {
+
+ Jim_HistoryShow();
+ Jim_DecrRefCount(interp, scriptObjPtr);
+ continue;
+ }
+
+ Jim_HistoryAdd(Jim_String(scriptObjPtr));
+ if (history_file) {
+ Jim_HistorySave(history_file);
+ }
+#endif
+ retcode = Jim_EvalObj(interp, scriptObjPtr);
+ Jim_DecrRefCount(interp, scriptObjPtr);
+
+ if (retcode == JIM_EXIT) {
+ break;
+ }
+ if (retcode == JIM_ERR) {
+ Jim_MakeErrorMessage(interp);
+ }
+ result = Jim_GetString(Jim_GetResult(interp), &reslen);
+ if (reslen) {
+ printf("%s\n", result);
+ }
+ }
+ out:
+ Jim_Free(history_file);
+
+ return retcode;
+}
+
+#include
+#include
+#include
+
+
+
+extern int Jim_initjimshInit(Jim_Interp *interp);
+
+static void JimSetArgv(Jim_Interp *interp, int argc, char *const argv[])
+{
+ int n;
+ Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
+
+
+ for (n = 0; n < argc; n++) {
+ Jim_Obj *obj = Jim_NewStringObj(interp, argv[n], -1);
+
+ Jim_ListAppendElement(interp, listObj, obj);
+ }
+
+ Jim_SetVariableStr(interp, "argv", listObj);
+ Jim_SetVariableStr(interp, "argc", Jim_NewIntObj(interp, argc));
+}
+
+static void JimPrintErrorMessage(Jim_Interp *interp)
+{
+ Jim_MakeErrorMessage(interp);
+ fprintf(stderr, "%s\n", Jim_String(Jim_GetResult(interp)));
+}
+
+void usage(const char* executable_name)
+{
+ printf("jimsh version %d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
+ printf("Usage: %s\n", executable_name);
+ printf("or : %s [options] [filename]\n", executable_name);
+ printf("\n");
+ printf("Without options: Interactive mode\n");
+ printf("\n");
+ printf("Options:\n");
+ printf(" --version : prints the version string\n");
+ printf(" --help : prints this text\n");
+ printf(" -e CMD : executes command CMD\n");
+ printf(" NOTE: all subsequent options will be passed as arguments to the command\n");
+ printf(" [filename|-] : executes the script contained in the named file, or from stdin if \"-\"\n");
+ printf(" NOTE: all subsequent options will be passed to the script\n\n");
+}
+
+int main(int argc, char *const argv[])
+{
+ int retcode;
+ Jim_Interp *interp;
+ char *const orig_argv0 = argv[0];
+
+
+ if (argc > 1 && strcmp(argv[1], "--version") == 0) {
+ printf("%d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
+ return 0;
+ }
+ else if (argc > 1 && strcmp(argv[1], "--help") == 0) {
+ usage(argv[0]);
+ return 0;
+ }
+
+
+ interp = Jim_CreateInterp();
+ Jim_RegisterCoreCommands(interp);
+
+
+ if (Jim_InitStaticExtensions(interp) != JIM_OK) {
+ JimPrintErrorMessage(interp);
+ }
+
+ Jim_SetVariableStrWithStr(interp, "jim::argv0", orig_argv0);
+ Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, argc == 1 ? "1" : "0");
+ retcode = Jim_initjimshInit(interp);
+
+ if (argc == 1) {
+
+ if (retcode == JIM_ERR) {
+ JimPrintErrorMessage(interp);
+ }
+ if (retcode != JIM_EXIT) {
+ JimSetArgv(interp, 0, NULL);
+ retcode = Jim_InteractivePrompt(interp);
+ }
+ }
+ else {
+
+ if (argc > 2 && strcmp(argv[1], "-e") == 0) {
+
+ JimSetArgv(interp, argc - 3, argv + 3);
+ retcode = Jim_Eval(interp, argv[2]);
+ if (retcode != JIM_ERR) {
+ printf("%s\n", Jim_String(Jim_GetResult(interp)));
+ }
+ }
+ else {
+ Jim_SetVariableStr(interp, "argv0", Jim_NewStringObj(interp, argv[1], -1));
+ JimSetArgv(interp, argc - 2, argv + 2);
+ if (strcmp(argv[1], "-") == 0) {
+ retcode = Jim_Eval(interp, "eval [info source [stdin read] stdin 1]");
+ } else {
+ retcode = Jim_EvalFile(interp, argv[1]);
+ }
+ }
+ if (retcode == JIM_ERR) {
+ JimPrintErrorMessage(interp);
+ }
+ }
+ if (retcode == JIM_EXIT) {
+ retcode = Jim_GetExitCode(interp);
+ }
+ else if (retcode == JIM_ERR) {
+ retcode = 1;
+ }
+ else {
+ retcode = 0;
+ }
+ Jim_FreeInterp(interp);
+ return retcode;
+}
+#endif
ADDED autosetup/local.tcl
Index: autosetup/local.tcl
==================================================================
--- autosetup/local.tcl
+++ autosetup/local.tcl
@@ -0,0 +1,31 @@
+# For this project, disable the pager for --help and --ref
+# The user can still enable by using --nopager=0 or --disable-nopager
+dict set autosetup(optdefault) nopager 1
+
+# Searches for a usable Tcl (prefer 8.6, 8.5, 8.4) in the given paths
+# Returns a dictionary of the contents of the tclConfig.sh file, or
+# empty if not found
+proc parse-tclconfig-sh {args} {
+ foreach p $args {
+ # Allow pointing directly to the path containing tclConfig.sh
+ if {[file exists $p/tclConfig.sh]} {
+ return [parse-tclconfig-sh-file $p/tclConfig.sh]
+ }
+ # Some systems allow for multiple versions
+ foreach libpath {lib/tcl8.6 lib/tcl8.5 lib/tcl8.4 lib/tcl tcl lib} {
+ if {[file exists $p/$libpath/tclConfig.sh]} {
+ return [parse-tclconfig-sh-file $p/$libpath/tclConfig.sh]
+ }
+ }
+ }
+}
+
+proc parse-tclconfig-sh-file {filename} {
+ foreach line [split [readfile $filename] \n] {
+ if {[regexp {^(TCL_[^=]*)=(.*)$} $line -> name value]} {
+ set value [regsub -all {\$\{.*\}} $value ""]
+ set tclconfig($name) [string trim $value ']
+ }
+ }
+ return [array get tclconfig]
+}
ADDED autosetup/pkg-config.tcl
Index: autosetup/pkg-config.tcl
==================================================================
--- autosetup/pkg-config.tcl
+++ autosetup/pkg-config.tcl
@@ -0,0 +1,135 @@
+# Copyright (c) 2016 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# @synopsis:
+#
+# The 'pkg-config' module allows package information to be found via 'pkg-config'.
+#
+# If not cross-compiling, the package path should be determined automatically
+# by 'pkg-config'.
+# If cross-compiling, the default package path is the compiler sysroot.
+# If the C compiler doesn't support '-print-sysroot', the path can be supplied
+# by the '--sysroot' option or by defining 'SYSROOT'.
+#
+# 'PKG_CONFIG' may be set to use an alternative to 'pkg-config'.
+
+use cc
+
+module-options {
+ sysroot:dir => "Override compiler sysroot for pkg-config search path"
+}
+
+# @pkg-config-init ?required?
+#
+# Initialises the 'pkg-config' system. Unless '$required' is set to 0,
+# it is a fatal error if a usable 'pkg-config' is not found .
+#
+# This command will normally be called automatically as required,
+# but it may be invoked explicitly if lack of 'pkg-config' is acceptable.
+#
+# Returns 1 if ok, or 0 if 'pkg-config' not found/usable (only if '$required' is 0).
+#
+proc pkg-config-init {{required 1}} {
+ if {[is-defined HAVE_PKG_CONFIG]} {
+ return [get-define HAVE_PKG_CONFIG]
+ }
+ set found 0
+
+ define PKG_CONFIG [get-env PKG_CONFIG pkg-config]
+ msg-checking "Checking for pkg-config..."
+
+ if {[catch {exec [get-define PKG_CONFIG] --version} version]} {
+ msg-result "[get-define PKG_CONFIG] (not found)"
+ if {$required} {
+ user-error "No usable pkg-config"
+ }
+ } else {
+ msg-result $version
+ define PKG_CONFIG_VERSION $version
+
+ set found 1
+
+ if {[opt-str sysroot o]} {
+ define SYSROOT [file-normalize $o]
+ msg-result "Using specified sysroot [get-define SYSROOT]"
+ } elseif {[get-define build] ne [get-define host]} {
+ if {[catch {exec-with-stderr [get-define CC] -print-sysroot} result errinfo] == 0} {
+ # Use the compiler sysroot, if there is one
+ define SYSROOT $result
+ msg-result "Found compiler sysroot $result"
+ } else {
+ set msg "pkg-config: Cross compiling, but no compiler sysroot and no --sysroot supplied"
+ if {$required} {
+ user-error $msg
+ } else {
+ msg-result $msg
+ }
+ set found 0
+ }
+ }
+ if {[is-defined SYSROOT]} {
+ set sysroot [get-define SYSROOT]
+
+ # XXX: It's possible that these should be set only when invoking pkg-config
+ global env
+ set env(PKG_CONFIG_DIR) ""
+ # Do we need to try /usr/local as well or instead?
+ set env(PKG_CONFIG_LIBDIR) $sysroot/usr/lib/pkgconfig:$sysroot/usr/share/pkgconfig
+ set env(PKG_CONFIG_SYSROOT_DIR) $sysroot
+ }
+ }
+ define HAVE_PKG_CONFIG $found
+ return $found
+}
+
+# @pkg-config module ?requirements?
+#
+# Use 'pkg-config' to find the given module meeting the given requirements.
+# e.g.
+#
+## pkg-config pango >= 1.37.0
+#
+# If found, returns 1 and sets 'HAVE_PKG_PANGO' to 1 along with:
+#
+## PKG_PANGO_VERSION to the found version
+## PKG_PANGO_LIBS to the required libs (--libs-only-l)
+## PKG_PANGO_LDFLAGS to the required linker flags (--libs-only-L)
+## PKG_PANGO_CFLAGS to the required compiler flags (--cflags)
+#
+# If not found, returns 0.
+#
+proc pkg-config {module args} {
+ set ok [pkg-config-init]
+
+ msg-checking "Checking for $module $args..."
+
+ if {!$ok} {
+ msg-result "no pkg-config"
+ return 0
+ }
+
+ if {[catch {exec [get-define PKG_CONFIG] --modversion "$module $args"} version]} {
+ msg-result "not found"
+ configlog "pkg-config --modversion $module $args: $version"
+ return 0
+ }
+ msg-result $version
+ set prefix [feature-define-name $module PKG_]
+ define HAVE_${prefix}
+ define ${prefix}_VERSION $version
+ define ${prefix}_LIBS [exec pkg-config --libs-only-l $module]
+ define ${prefix}_LDFLAGS [exec pkg-config --libs-only-L $module]
+ define ${prefix}_CFLAGS [exec pkg-config --cflags $module]
+ return 1
+}
+
+# @pkg-config-get module setting
+#
+# Convenience access to the results of 'pkg-config'.
+#
+# For example, '[pkg-config-get pango CFLAGS]' returns
+# the value of 'PKG_PANGO_CFLAGS', or '""' if not defined.
+proc pkg-config-get {module name} {
+ set prefix [feature-define-name $module PKG_]
+ get-define ${prefix}_${name} ""
+}
ADDED autosetup/system.tcl
Index: autosetup/system.tcl
==================================================================
--- autosetup/system.tcl
+++ autosetup/system.tcl
@@ -0,0 +1,407 @@
+# Copyright (c) 2010 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# @synopsis:
+#
+# This module supports common system interrogation and options
+# such as '--host', '--build', '--prefix', and setting 'srcdir', 'builddir', and 'EXEEXT'.
+#
+# It also support the "feature" naming convention, where searching
+# for a feature such as 'sys/type.h' defines 'HAVE_SYS_TYPES_H'.
+#
+# It defines the following variables, based on '--prefix' unless overridden by the user:
+#
+## datadir
+## sysconfdir
+## sharedstatedir
+## localstatedir
+## infodir
+## mandir
+## includedir
+#
+# If '--prefix' is not supplied, it defaults to '/usr/local' unless 'defaultprefix' is defined *before*
+# including the 'system' module.
+
+if {[is-defined defaultprefix]} {
+ user-notice "Note: defaultprefix is deprecated. Use options-defaults to set default options"
+ options-defaults [list prefix [get-define defaultprefix]]
+}
+
+module-options [subst -noc -nob {
+ host:host-alias => {a complete or partial cpu-vendor-opsys for the system where
+ the application will run (defaults to the same value as --build)}
+ build:build-alias => {a complete or partial cpu-vendor-opsys for the system
+ where the application will be built (defaults to the
+ result of running config.guess)}
+ prefix:dir=/usr/local => {the target directory for the build (default: '@default@')}
+
+ # These (hidden) options are supported for autoconf/automake compatibility
+ exec-prefix:
+ bindir:
+ sbindir:
+ includedir:
+ mandir:
+ infodir:
+ libexecdir:
+ datadir:
+ libdir:
+ sysconfdir:
+ sharedstatedir:
+ localstatedir:
+ runstatedir:
+ maintainer-mode=0
+ dependency-tracking=0
+ silent-rules=0
+}]
+
+# @check-feature name { script }
+#
+# defines feature '$name' to the return value of '$script',
+# which should be 1 if found or 0 if not found.
+#
+# e.g. the following will define 'HAVE_CONST' to 0 or 1.
+#
+## check-feature const {
+## cctest -code {const int _x = 0;}
+## }
+proc check-feature {name code} {
+ msg-checking "Checking for $name..."
+ set r [uplevel 1 $code]
+ define-feature $name $r
+ if {$r} {
+ msg-result "ok"
+ } else {
+ msg-result "not found"
+ }
+ return $r
+}
+
+# @have-feature name ?default=0?
+#
+# Returns the value of feature '$name' if defined, or '$default' if not.
+#
+# See 'feature-define-name' for how the "feature" name
+# is translated into the "define" name.
+#
+proc have-feature {name {default 0}} {
+ get-define [feature-define-name $name] $default
+}
+
+# @define-feature name ?value=1?
+#
+# Sets the feature 'define' to '$value'.
+#
+# See 'feature-define-name' for how the "feature" name
+# is translated into the "define" name.
+#
+proc define-feature {name {value 1}} {
+ define [feature-define-name $name] $value
+}
+
+# @feature-checked name
+#
+# Returns 1 if feature '$name' has been checked, whether true or not.
+#
+proc feature-checked {name} {
+ is-defined [feature-define-name $name]
+}
+
+# @feature-define-name name ?prefix=HAVE_?
+#
+# Converts a "feature" name to the corresponding "define",
+# e.g. 'sys/stat.h' becomes 'HAVE_SYS_STAT_H'.
+#
+# Converts '*' to 'P' and all non-alphanumeric to underscore.
+#
+proc feature-define-name {name {prefix HAVE_}} {
+ string toupper $prefix[regsub -all {[^a-zA-Z0-9]} [regsub -all {[*]} $name p] _]
+}
+
+# @write-if-changed filename contents ?script?
+#
+# If '$filename' doesn't exist, or it's contents are different to '$contents',
+# the file is written and '$script' is evaluated.
+#
+# Otherwise a "file is unchanged" message is displayed.
+proc write-if-changed {file buf {script {}}} {
+ set old [readfile $file ""]
+ if {$old eq $buf && [file exists $file]} {
+ msg-result "$file is unchanged"
+ } else {
+ writefile $file $buf\n
+ uplevel 1 $script
+ }
+}
+
+
+# @include-file infile mapping
+#
+# The core of make-template, called recursively for each @include
+# directive found within that template so that this proc's result
+# is the fully-expanded template.
+#
+# The mapping parameter is how we expand @varname@ within the template.
+# We do that inline within this step only for @include directives which
+# can have variables in the filename arg. A separate substitution pass
+# happens when this recursive function returns, expanding the rest of
+# the variables.
+#
+proc include-file {infile mapping} {
+ # A stack of true/false conditions, one for each nested conditional
+ # starting with "true"
+ set condstack {1}
+ set result {}
+ set linenum 0
+ foreach line [split [readfile $infile] \n] {
+ incr linenum
+ if {[regexp {^@(if|else|endif)(\s*)(.*)} $line -> condtype condspace condargs]} {
+ if {$condtype eq "if"} {
+ if {[string length $condspace] == 0} {
+ autosetup-error "$infile:$linenum: Invalid expression: $line"
+ }
+ if {[llength $condargs] == 1} {
+ # ABC => [get-define ABC] ni {0 ""}
+ # !ABC => [get-define ABC] in {0 ""}
+ lassign $condargs condvar
+ if {[regexp {^!(.*)} $condvar -> condvar]} {
+ set op in
+ } else {
+ set op ni
+ }
+ set condexpr "\[[list get-define $condvar]\] $op {0 {}}"
+ } else {
+ # Translate alphanumeric ABC into [get-define ABC] and leave the
+ # rest of the expression untouched
+ regsub -all {([A-Z][[:alnum:]_]*)} $condargs {[get-define \1]} condexpr
+ }
+ if {[catch [list expr $condexpr] condval]} {
+ dputs $condval
+ autosetup-error "$infile:$linenum: Invalid expression: $line"
+ }
+ dputs "@$condtype: $condexpr => $condval"
+ }
+ if {$condtype ne "if"} {
+ if {[llength $condstack] <= 1} {
+ autosetup-error "$infile:$linenum: Error: @$condtype missing @if"
+ } elseif {[string length $condargs] && [string index $condargs 0] ne "#"} {
+ autosetup-error "$infile:$linenum: Error: Extra arguments after @$condtype"
+ }
+ }
+ switch -exact $condtype {
+ if {
+ # push condval
+ lappend condstack $condval
+ }
+ else {
+ # Toggle the last entry
+ set condval [lpop condstack]
+ set condval [expr {!$condval}]
+ lappend condstack $condval
+ }
+ endif {
+ if {[llength $condstack] == 0} {
+ user-notice "$infile:$linenum: Error: @endif missing @if"
+ }
+ lpop condstack
+ }
+ }
+ continue
+ } elseif {[regexp {^@include\s+(.*)} $line -> filearg]} {
+ set incfile [string map $mapping $filearg]
+ if {[file exists $incfile]} {
+ lappend ::autosetup(deps) [file-normalize $incfile]
+ lappend result {*}[include-file $incfile $mapping]
+ } else {
+ user-error "$infile:$linenum: Include file $incfile is missing"
+ }
+ continue
+ } elseif {[regexp {^@define\s+(\w+)\s+(.*)} $line -> var val]} {
+ define $var $val
+ continue
+ }
+ # Only output this line if the stack contains all "true"
+ if {"0" in $condstack} {
+ continue
+ }
+ lappend result $line
+ }
+ return $result
+}
+
+
+# @make-template template ?outfile?
+#
+# Reads the input file '/$template' and writes the output file '$outfile'
+# (unless unchanged).
+# If '$outfile' is blank/omitted, '$template' should end with '.in' which
+# is removed to create the output file name.
+#
+# Each pattern of the form '@define@' is replaced with the corresponding
+# "define", if it exists, or left unchanged if not.
+#
+# The special value '@srcdir@' is substituted with the relative
+# path to the source directory from the directory where the output
+# file is created, while the special value '@top_srcdir@' is substituted
+# with the relative path to the top level source directory.
+#
+# Conditional sections may be specified as follows:
+## @if NAME eq "value"
+## lines
+## @else
+## lines
+## @endif
+#
+# Where 'NAME' is a defined variable name and '@else' is optional.
+# Note that variables names *must* start with an uppercase letter.
+# If the expression does not match, all lines through '@endif' are ignored.
+#
+# The alternative forms may also be used:
+## @if NAME (true if the variable is defined, but not empty and not "0")
+## @if !NAME (opposite of the form above)
+## @if
+#
+# In the general Tcl expression, any words beginning with an uppercase letter
+# are translated into [get-define NAME]
+#
+# Expressions may be nested
+#
+proc make-template {template {out {}}} {
+ set infile [file join $::autosetup(srcdir) $template]
+
+ if {![file exists $infile]} {
+ user-error "Template $template is missing"
+ }
+
+ # Define this as late as possible
+ define AUTODEPS $::autosetup(deps)
+
+ if {$out eq ""} {
+ if {[file ext $template] ne ".in"} {
+ autosetup-error "make_template $template has no target file and can't guess"
+ }
+ set out [file rootname $template]
+ }
+
+ set outdir [file dirname $out]
+
+ # Make sure the directory exists
+ file mkdir $outdir
+
+ # Set up srcdir and top_srcdir to be relative to the target dir
+ define srcdir [relative-path [file join $::autosetup(srcdir) $outdir] $outdir]
+ define top_srcdir [relative-path $::autosetup(srcdir) $outdir]
+
+ # Build map from global defines to their values so they can be
+ # substituted into @include file names.
+ proc build-define-mapping {} {
+ set mapping {}
+ foreach {n v} [array get ::define] {
+ lappend mapping @$n@ $v
+ }
+ return $mapping
+ }
+ set mapping [build-define-mapping]
+
+ set result [include-file $infile $mapping]
+
+ # Rebuild the define mapping in case we ran across @define
+ # directives in the template or a file it @included, then
+ # apply that mapping to the expanded template.
+ set mapping [build-define-mapping]
+ write-if-changed $out [string map $mapping [join $result \n]] {
+ msg-result "Created [relative-path $out] from [relative-path $template]"
+ }
+}
+
+# build/host tuples and cross-compilation prefix
+opt-str build build ""
+define build_alias $build
+if {$build eq ""} {
+ define build [config_guess]
+} else {
+ define build [config_sub $build]
+}
+
+opt-str host host ""
+define host_alias $host
+if {$host eq ""} {
+ define host [get-define build]
+ set cross ""
+} else {
+ define host [config_sub $host]
+ set cross $host-
+}
+define cross [get-env CROSS $cross]
+
+# build/host _cpu, _vendor and _os
+foreach type {build host} {
+ set v [get-define $type]
+ if {![regexp {^([^-]+)-([^-]+)-(.*)$} $v -> cpu vendor os]} {
+ user-error "Invalid canonical $type: $v"
+ }
+ define ${type}_cpu $cpu
+ define ${type}_vendor $vendor
+ define ${type}_os $os
+}
+
+opt-str prefix prefix /usr/local
+
+# These are for compatibility with autoconf
+define target [get-define host]
+define prefix $prefix
+define builddir $autosetup(builddir)
+define srcdir $autosetup(srcdir)
+define top_srcdir $autosetup(srcdir)
+define abs_top_srcdir [file-normalize $autosetup(srcdir)]
+define abs_top_builddir [file-normalize $autosetup(builddir)]
+
+# autoconf supports all of these
+define exec_prefix [opt-str exec-prefix exec_prefix $prefix]
+foreach {name defpath} {
+ bindir /bin
+ sbindir /sbin
+ libexecdir /libexec
+ libdir /lib
+} {
+ define $name [opt-str $name o $exec_prefix$defpath]
+}
+foreach {name defpath} {
+ datadir /share
+ sharedstatedir /com
+ infodir /share/info
+ mandir /share/man
+ includedir /include
+} {
+ define $name [opt-str $name o $prefix$defpath]
+}
+if {$prefix ne {/usr}} {
+ opt-str sysconfdir sysconfdir $prefix/etc
+} else {
+ opt-str sysconfdir sysconfdir /etc
+}
+define sysconfdir $sysconfdir
+
+define localstatedir [opt-str localstatedir o /var]
+define runstatedir [opt-str runstatedir o /run]
+
+define SHELL [get-env SHELL [find-an-executable sh bash ksh]]
+
+# These could be used to generate Makefiles following some automake conventions
+define AM_SILENT_RULES [opt-bool silent-rules]
+define AM_MAINTAINER_MODE [opt-bool maintainer-mode]
+define AM_DEPENDENCY_TRACKING [opt-bool dependency-tracking]
+
+# Windows vs. non-Windows
+switch -glob -- [get-define host] {
+ *-*-ming* - *-*-cygwin - *-*-msys {
+ define-feature windows
+ define EXEEXT .exe
+ }
+ default {
+ define EXEEXT ""
+ }
+}
+
+# Display
+msg-result "Host System...[get-define host]"
+msg-result "Build System...[get-define build]"
ADDED autosetup/tmake.auto
Index: autosetup/tmake.auto
==================================================================
--- autosetup/tmake.auto
+++ autosetup/tmake.auto
@@ -0,0 +1,55 @@
+# Copyright (c) 2016 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# Auto-load module for 'tmake' build system integration
+
+use init
+
+autosetup_add_init_type tmake "Tcl-based tmake build system" {
+ autosetup_check_create auto.def \
+{# Initial auto.def created by 'autosetup --init=tmake'
+# vim:set syntax=tcl:
+
+use cc cc-lib cc-db cc-shared
+use tmake
+
+# Add any user options here
+# Really want a --configure that takes over the rest of the command line
+options {
+}
+
+cc-check-tools ar ranlib
+
+set objdir [get-env BUILDDIR objdir]
+
+make-config-header $objdir/include/autoconf.h
+make-tmake-settings $objdir/settings.conf {[A-Z]*} *dir lib_*
+}
+
+ autosetup_check_create project.spec \
+{# Initial project.spec created by 'autosetup --init=tmake'
+
+tmake-require-version 0.7.3
+
+# vim:set syntax=tcl:
+define? DESTDIR _install
+
+# XXX If configure creates additional/different files than include/autoconf.h
+# that should be reflected here
+Autosetup include/autoconf.h
+
+# e.g. for autoconf.h
+IncludePaths include
+
+ifconfig !CONFIGURED {
+ # Not configured, so don't process subdirs
+ AutoSubDirs off
+ # And don't process this file any further
+ ifconfig false
+}
+}
+
+ if {![file exists build.spec]} {
+ puts "Note: I don't see build.spec. Try running: tmake --genie"
+ }
+}
ADDED autosetup/tmake.tcl
Index: autosetup/tmake.tcl
==================================================================
--- autosetup/tmake.tcl
+++ autosetup/tmake.tcl
@@ -0,0 +1,52 @@
+# Copyright (c) 2011 WorkWare Systems http://www.workware.net.au/
+# All rights reserved
+
+# @synopsis:
+#
+# The 'tmake' module makes it easy to support the tmake build system.
+#
+# The following variables are set:
+#
+## CONFIGURED - to indicate that the project is configured
+
+use system
+
+module-options {}
+
+define CONFIGURED
+
+# @make-tmake-settings outfile patterns ...
+#
+# Examines all defined variables which match the given patterns (defaults to '*')
+# and writes a tmake-compatible .conf file defining those variables.
+# For example, if 'ABC' is '"3 monkeys"' and 'ABC' matches a pattern, then the file will include:
+#
+## define ABC {3 monkeys}
+#
+# If the file would be unchanged, it is not written.
+#
+# Typical usage is:
+#
+## make-tmake-settings [get-env BUILDDIR objdir]/settings.conf {[A-Z]*}
+proc make-tmake-settings {file args} {
+ file mkdir [file dirname $file]
+ set lines {}
+
+ if {[llength $args] == 0} {
+ set args *
+ }
+
+ foreach n [lsort [dict keys [all-defines]]] {
+ foreach p $args {
+ if {[string match $p $n]} {
+ set value [get-define $n]
+ lappend lines "define $n [list $value]"
+ break
+ }
+ }
+ }
+ set buf [join $lines \n]
+ write-if-changed $file $buf {
+ msg-result "Created $file"
+ }
+}
DELETED ci_cvs.txt
Index: ci_cvs.txt
==================================================================
--- ci_cvs.txt
+++ ci_cvs.txt
@@ -1,192 +0,0 @@
-===============================================================================
-
-First experimental codes ...
-
-tools/import-cvs.tcl
-tools/lib/rcsparser.tcl
-
-No actual import, right now only working on getting csets right. The
-code uses CVSROOT/history as foundation, and augments that with data
-from the individual RCS files (commit messages).
-
-Statistics of a run ...
- 3516 csets.
-
- 1545 breaks on user change
- 558 breaks on file duplicate
- 13 breaks on branch/trunk change
- 1402 breaks on commit message change
-
-Time statistics ...
- 3297 were processed in <= 1 seconds (93.77%)
- 217 were processed in between 2 seconds and 14 minutes.
- 1 was processed in ~41 minutes
- 1 was processed in ~22 hours
-
-Time fuzz - Differences between csets range from 0 seconds to 66
-days. Needs stats analysis to see if there is an obvious break. Even
-so the times within csets and between csets overlap a great deal,
-making time a bad criterium for cset separation, IMHO.
-
-Leaving that topic, back to the current cset separator ...
-
-It has a problem:
- The history file is not starting at the root!
-
-Examples:
- The first three changesets are
-
- =============================/user
- M {Wed Nov 22 09:28:49 AM PST 2000} ericm 1.4 tcllib/modules/ftpd/ChangeLog
- M {Wed Nov 22 09:28:49 AM PST 2000} ericm 1.7 tcllib/modules/ftpd/ftpd.tcl
- files: 2
- delta: 0
- range: 0 seconds
- =============================/cmsg
- M {Wed Nov 29 02:14:33 PM PST 2000} ericm 1.3 tcllib/aclocal.m4
- files: 1
- delta:
- range: 0 seconds
- =============================/cmsg
- M {Sun Feb 04 12:28:35 AM PST 2001} ericm 1.9 tcllib/modules/mime/ChangeLog
- M {Sun Feb 04 12:28:35 AM PST 2001} ericm 1.12 tcllib/modules/mime/mime.tcl
- files: 2
- delta: 0
- range: 0 seconds
-
-All csets modify files which already have several revisions. We have
-no csets from before that in the history, but these csets are in the
-RCS files.
-
-I wonder, is SF maybe removing old entries from the history when it
-grows too large ?
-
-This also affects incremental import ... I cannot assume that the
-history always grows. It may shrink ... I cannot keep an offset, will
-have to record the time of the last entry, or even the full entry
-processed last, to allow me to skip ahead to anything not known yet.
-
-I might have to try to implement the algorithm outlined below,
-matching the revision trees of the individual RCS files to each other
-to form the global tree of revisions. Maybe we can use the history to
-help in the matchup, for the parts where we do have it.
-
-Wait. This might be easier ... Take the delta information from the RCS
-files and generate a fake history ... Actually, this might even allow
-us to create a total history ... No, not quite, the merge entries the
-actual history may contain will be missing. These we can mix in from
-the actual history, as much as we have.
-
-Still, lets try that, a fake history, and then run this script on it
-to see if/where are differences.
-
-===============================================================================
-
-
-Notes about CVS import, regarding CVS.
-
-- Problem: CVS does not really track changesets, but only individual
- revisions of files. To recover changesets it is necessary to look at
- author, branch, timestamp information, and the commit messages. Even
- so this is only heuristic, not foolproof.
-
- Existing tool: cvsps.
-
- Processes the output of 'cvs log' to recover changesets. Problem:
- Sees only a linear list of revisions, does not see branchpoints,
- etc. Cannot use the tree structure to help in making the decisions.
-
-- Problem: CVS does not track merge-points at all. Recovery through
- heuristics is brittle at best, looking for keywords in commit
- messages which might indicate that a branch was merged with some
- other.
-
-
-Ideas regarding an algorithm to recover changesets.
-
-Key feature: Uses the per-file revision trees to help in uncovering
-the underlying changesets and global revision tree G.
-
-The per-file revision tree for a file X is in essence the global
-revision tree with all nodes not pertaining to X removed from it. In
-the reverse this allows us to built up the global revision tree from
-the per-file trees by matching nodes to each other and extending.
-
-Start with the per file revision tree of a single file as initial
-approximation of the global tree. All nodes of this tree refer to the
-revision of the file belonging to it, and through that the file
-itself. At each step the global tree contains the nodes for a finite
-set of files, and all nodes in the tree refer to revisions of all
-files in the set, making the mapping total.
-
-To add a file X to the tree take the per-file revision tree R and
-performs the following actions:
-
-- For each node N in R use the tuple
- to identify a set of nodes in G which may match N. Use the timestamp
- to locate the node nearest in time.
-
-- This process will leave nodes in N unmapped. If there are unmapped
- nodes which have no neighbouring mapped nodes we have to
- abort.
-
- Otherwise take the nodes which have mapped neighbours. Trace the
- edges and see which of these nodes are connected in the local
- tree. Then look at the identified neighbours and trace their
- connections.
-
- If two global nodes have a direct connection, but a multi-edge
- connection in the local tree insert global nodes mapping to the
- local nodes and map them together. This expands the global tree to
- hold the revisions added by the new file.
-
- Otherwise, both sides have multi-edge connections then abort. This
- looks like a merge of two different branches, but there are no such
- in CVS ... Wait ... sort the nodes over time and fit the new nodes
- in between the other nodes, per the timestamps. We have overlapping
- / alternating changes to one file and others.
-
- A last possibility is that a node is only connected to a mapped
- parent. This may be a new branch, or again an alternating change on
- the given line. Symbols on the revisions will help to map this.
-
-- We now have an extended global tree which incorporates the revisions
- of the new file. However new nodes will refer only to the new file,
- and old nodes may not refer to the new file. This has to be fixed,
- as all nodes have to refer to all files.
-
- Run over the tree and look at each parent/child pair. If a file is
- not referenced in the child, but the parent, then copy a reference
- to the file revision on the parent forward to the child. This
- signals that the file did not change in the given revision.
-
-- After all files have been integrated in this manner we have global
- revision tree capturing all changesets, including the unchanged
- files per changeset.
-
-
-This algorithm has to be refined to also take Attic/ files into
-account.
-
--------------------------------------------------------------------------
-
-Two archive files mapping to the same user file. How are they
-interleaved ?
-
-(a) sqlite/src/os_unix.h,v
-(b) sqlite/src/Attic/os_unix.h,v
-
-Problem: Max version of (a) is 1.9
- Max version of (b) is 1.11
- cvs co 1.10 -> no longer in the repository.
-
-This seems to indicate that the non-Attic file is relevant.
-
---------------------------------------------------------------------------
-
-tcllib - more problems - tklib/pie.tcl,v -
-
-invalid change text in
-/home/aku/Projects/Tcl/Fossil/Devel/Examples/cvs-tcllib/tklib/modules/tkpiechart/pie.tcl,v
-
-Possibly braces ?
DELETED ci_fossil.txt
Index: ci_fossil.txt
==================================================================
--- ci_fossil.txt
+++ ci_fossil.txt
@@ -1,127 +0,0 @@
-
-To perform CVS imports for fossil we need at least the ability to
-parse CVS files, i.e. RCS files, with slight differences.
-
-For the general architecture of the import facility we have two major
-paths to choose between.
-
-One is to use an external tool which processes a cvs repository and
-drives fossil through its CLI to insert the found changesets.
-
-The other is to integrate the whole facility into the fossil binary
-itself.
-
-I dislike the second choice. It may be faster, as the implementation
-can use all internal functionality of fossil to perform the import,
-however it will also bloat the binary with functionality not needed
-most of the time. Which becomes especially obvious if more importers
-are to be written, like for monotone, bazaar, mercurial, bitkeeper,
-git, SVN, Arc, etc. Keeping all this out of the core fossil binary is
-IMHO more beneficial in the long term, also from a maintenance point
-of view. The tools can evolve separately. Especially important for CVS
-as it will have to deal with lots of broken repositories, all
-different.
-
-However, nothing speaks against looking for common parts in all
-possible import tools, and having these in the fossil core, as a
-general backend all importer may use. Something like that has already
-been proposed: The deconstruct|reconstruct methods. For us, actually
-only reconstruct is important. Taking an unordered collection of files
-(data, and manifests) it generates a proper fossil repository. With
-that method implemented all import tools only have to generate the
-necessary collection and then leave the main work of filling the
-database to fossil itself.
-
-The disadvantage of this method is however that it will gobble up a
-lot of temporary space in the filesystem to hold all unique revisions
-of all files in their expanded form.
-
-It might be worthwhile to consider an extension of 'reconstruct' which
-is able to incrementally add a set of files to an existing fossil
-repository already containing revisions. In that case the import tool
-can be changed to incrementally generate the collection for a
-particular revision, import it, and iterate over all revisions in the
-origin repository. This is of course also dependent on the origin
-repository itself, how well it supports such incremental export.
-
-This also leads to a possible method for performing the import using
-only existing functionality ('reconstruct' has not been implemented
-yet). Instead generating an unordered collection for each revision
-generate a properly setup workspace, simply commit it. This will
-require use of rm, add and update methods as well, to remove old and
-enter new files, and point the fossil repository to the correct parent
-revision from the new revision is derived.
-
-The relative efficiency (in time) of these incremental methods versus
-importing a complete collection of files encoding the entire origin
-repository however is not clear.
-
-----------------------------------
-
-reconstruct
-
-The core logic for handling content is in the file "content.c", in
-particular the functions 'content_put' and 'content_deltify'. One of
-the main users of these functions is in the file "checkin.c", see the
-function 'commit_cmd'.
-
-The logic is clear. The new modified files are simply stored without
-delta-compression, using 'content_put'. And should fosssil have an id
-for the _previous_ revision of the committed file it uses
-'content_deltify' to convert the already stored data for that revision
-into a delta with the just stored new revision as origin.
-
-In other words, fossil produces reverse deltas, with leaf revisions
-stored just zip-compressed (plain) and older revisions using both zip-
-and delta-compression.
-
-Of note is that the underlying logic in 'content_deltify' gives up on
-delta compression if the involved files are either not large enough,
-or if the achieved compression factor was not high enough. In that
-case the old revision of the file is left plain.
-
-The scheme can thus be called a 'truncated reverse delta'.
-
-The manifest is created and committed after the modified files. It
-uses the same logic as for the regular files. The new leaf is stored
-plain, and storage of the parent manifest is modified to be a delta
-with the current as origin.
-
-Further note that for a checkin of a merge result oonly the primary
-parent is modified in that way. The secondary parent, the one merged
-into the current revision is not touched. I.e. from the storage layer
-point of view this revision is still a leaf and the data is kept
-stored plain, not delta-compressed.
-
-
-
-Now the "reconstruct" can be done like so:
-
-- Scan the files in the indicated directory, and look for a manifest.
-
-- When the manifest has been found parse its contents and follow the
- chain of parent links to locate the root manifest (no parent).
-
-- Import the files referenced by the root manifest, then the manifest
- itself. This can be done using a modified form of the 'commit_cmd'
- which does not have to construct a manifest on its own from vfile,
- vmerge, etc.
-
-- After that recursively apply the import of the previous step to the
- children of the root, and so on.
-
-For an incremental "reconstruct" the collection of files would not be
-a single tree with a root, but a forest, and the roots to look for are
-not manifests without parent, but with a parent which is already
-present in the repository. After one such root has been found and
-processed the unprocessed files have to be searched further for more
-roots, and only if no such are found anymore will the remaining files
-be considered as superfluous.
-
-We can use the functions in "manifest.c" for the parsing and following
-the parental chain.
-
-Hm. But we have no direct child information. So the above algorithm
-has to be modified, we have to scan all manifests before we start
-importing, and we have to create a reverse index, from manifest to
-children so that we can perform the import from root to leaves.
ADDED compat/tcl-8.6/generic/tcl.h
Index: compat/tcl-8.6/generic/tcl.h
==================================================================
--- compat/tcl-8.6/generic/tcl.h
+++ compat/tcl-8.6/generic/tcl.h
@@ -0,0 +1,2653 @@
+/*
+ * tcl.h --
+ *
+ * This header file describes the externally-visible facilities of the
+ * Tcl interpreter.
+ *
+ * Copyright (c) 1987-1994 The Regents of the University of California.
+ * Copyright (c) 1993-1996 Lucent Technologies.
+ * Copyright (c) 1994-1998 Sun Microsystems, Inc.
+ * Copyright (c) 1998-2000 by Scriptics Corporation.
+ * Copyright (c) 2002 by Kevin B. Kenny. All rights reserved.
+ *
+ * See the file "license.terms" for information on usage and redistribution of
+ * this file, and for a DISCLAIMER OF ALL WARRANTIES.
+ */
+
+#ifndef _TCL
+#define _TCL
+
+/*
+ * For C++ compilers, use extern "C"
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The following defines are used to indicate the various release levels.
+ */
+
+#define TCL_ALPHA_RELEASE 0
+#define TCL_BETA_RELEASE 1
+#define TCL_FINAL_RELEASE 2
+
+/*
+ * When version numbers change here, must also go into the following files and
+ * update the version numbers:
+ *
+ * library/init.tcl (1 LOC patch)
+ * unix/configure.in (2 LOC Major, 2 LOC minor, 1 LOC patch)
+ * win/configure.in (as above)
+ * win/tcl.m4 (not patchlevel)
+ * win/makefile.bc (not patchlevel) 2 LOC
+ * README (sections 0 and 2, with and without separator)
+ * macosx/Tcl.pbproj/project.pbxproj (not patchlevel) 1 LOC
+ * macosx/Tcl.pbproj/default.pbxuser (not patchlevel) 1 LOC
+ * macosx/Tcl.xcode/project.pbxproj (not patchlevel) 2 LOC
+ * macosx/Tcl.xcode/default.pbxuser (not patchlevel) 1 LOC
+ * macosx/Tcl-Common.xcconfig (not patchlevel) 1 LOC
+ * win/README (not patchlevel) (sections 0 and 2)
+ * unix/tcl.spec (1 LOC patch)
+ * tools/tcl.hpj.in (not patchlevel, for windows installer)
+ */
+
+#define TCL_MAJOR_VERSION 8
+#define TCL_MINOR_VERSION 6
+#define TCL_RELEASE_LEVEL TCL_FINAL_RELEASE
+#define TCL_RELEASE_SERIAL 0
+
+#define TCL_VERSION "8.6"
+#define TCL_PATCH_LEVEL "8.6.0"
+
+/*
+ *----------------------------------------------------------------------------
+ * The following definitions set up the proper options for Windows compilers.
+ * We use this method because there is no autoconf equivalent.
+ */
+
+#ifndef __WIN32__
+# if defined(_WIN32) || defined(WIN32) || defined(__MINGW32__) || defined(__BORLANDC__) || (defined(__WATCOMC__) && defined(__WINDOWS_386__))
+# define __WIN32__
+# ifndef WIN32
+# define WIN32
+# endif
+# ifndef _WIN32
+# define _WIN32
+# endif
+# endif
+#endif
+
+/*
+ * STRICT: See MSDN Article Q83456
+ */
+
+#ifdef __WIN32__
+# ifndef STRICT
+# define STRICT
+# endif
+#endif /* __WIN32__ */
+
+/*
+ * Utility macros: STRINGIFY takes an argument and wraps it in "" (double
+ * quotation marks), JOIN joins two arguments.
+ */
+
+#ifndef STRINGIFY
+# define STRINGIFY(x) STRINGIFY1(x)
+# define STRINGIFY1(x) #x
+#endif
+#ifndef JOIN
+# define JOIN(a,b) JOIN1(a,b)
+# define JOIN1(a,b) a##b
+#endif
+
+/*
+ * A special definition used to allow this header file to be included from
+ * windows resource files so that they can obtain version information.
+ * RC_INVOKED is defined by default by the windows RC tool.
+ *
+ * Resource compilers don't like all the C stuff, like typedefs and function
+ * declarations, that occur below, so block them out.
+ */
+
+#ifndef RC_INVOKED
+
+/*
+ * Special macro to define mutexes, that doesn't do anything if we are not
+ * using threads.
+ */
+
+#ifdef TCL_THREADS
+#define TCL_DECLARE_MUTEX(name) static Tcl_Mutex name;
+#else
+#define TCL_DECLARE_MUTEX(name)
+#endif
+
+/*
+ * Tcl's public routine Tcl_FSSeek() uses the values SEEK_SET, SEEK_CUR, and
+ * SEEK_END, all #define'd by stdio.h .
+ *
+ * Also, many extensions need stdio.h, and they've grown accustomed to tcl.h
+ * providing it for them rather than #include-ing it themselves as they
+ * should, so also for their sake, we keep the #include to be consistent with
+ * prior Tcl releases.
+ */
+
+#include
+
+/*
+ *----------------------------------------------------------------------------
+ * Support for functions with a variable number of arguments.
+ *
+ * The following TCL_VARARGS* macros are to support old extensions
+ * written for older versions of Tcl where the macros permitted
+ * support for the varargs.h system as well as stdarg.h .
+ *
+ * New code should just directly be written to use stdarg.h conventions.
+ */
+
+#include
+#ifndef TCL_NO_DEPRECATED
+# define TCL_VARARGS(type, name) (type name, ...)
+# define TCL_VARARGS_DEF(type, name) (type name, ...)
+# define TCL_VARARGS_START(type, name, list) (va_start(list, name), name)
+#endif
+#if defined(__GNUC__) && (__GNUC__ > 2)
+# define TCL_FORMAT_PRINTF(a,b) __attribute__ ((__format__ (__printf__, a, b)))
+#else
+# define TCL_FORMAT_PRINTF(a,b)
+#endif
+
+/*
+ * Allow a part of Tcl's API to be explicitly marked as deprecated.
+ *
+ * Used to make TIP 330/336 generate moans even if people use the
+ * compatibility macros. Change your code, guys! We won't support you forever.
+ */
+
+#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
+# if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC__MINOR__ >= 5))
+# define TCL_DEPRECATED_API(msg) __attribute__ ((__deprecated__ (msg)))
+# else
+# define TCL_DEPRECATED_API(msg) __attribute__ ((__deprecated__))
+# endif
+#else
+# define TCL_DEPRECATED_API(msg) /* nothing portable */
+#endif
+
+/*
+ *----------------------------------------------------------------------------
+ * Macros used to declare a function to be exported by a DLL. Used by Windows,
+ * maps to no-op declarations on non-Windows systems. The default build on
+ * windows is for a DLL, which causes the DLLIMPORT and DLLEXPORT macros to be
+ * nonempty. To build a static library, the macro STATIC_BUILD should be
+ * defined.
+ *
+ * Note: when building static but linking dynamically to MSVCRT we must still
+ * correctly decorate the C library imported function. Use CRTIMPORT
+ * for this purpose. _DLL is defined by the compiler when linking to
+ * MSVCRT.
+ */
+
+#if (defined(__WIN32__) && (defined(_MSC_VER) || (__BORLANDC__ >= 0x0550) || defined(__LCC__) || defined(__WATCOMC__) || (defined(__GNUC__) && defined(__declspec))))
+# define HAVE_DECLSPEC 1
+# ifdef STATIC_BUILD
+# define DLLIMPORT
+# define DLLEXPORT
+# ifdef _DLL
+# define CRTIMPORT __declspec(dllimport)
+# else
+# define CRTIMPORT
+# endif
+# else
+# define DLLIMPORT __declspec(dllimport)
+# define DLLEXPORT __declspec(dllexport)
+# define CRTIMPORT __declspec(dllimport)
+# endif
+#else
+# define DLLIMPORT
+# if defined(__GNUC__) && __GNUC__ > 3
+# define DLLEXPORT __attribute__ ((visibility("default")))
+# else
+# define DLLEXPORT
+# endif
+# define CRTIMPORT
+#endif
+
+/*
+ * These macros are used to control whether functions are being declared for
+ * import or export. If a function is being declared while it is being built
+ * to be included in a shared library, then it should have the DLLEXPORT
+ * storage class. If is being declared for use by a module that is going to
+ * link against the shared library, then it should have the DLLIMPORT storage
+ * class. If the symbol is beind declared for a static build or for use from a
+ * stub library, then the storage class should be empty.
+ *
+ * The convention is that a macro called BUILD_xxxx, where xxxx is the name of
+ * a library we are building, is set on the compile line for sources that are
+ * to be placed in the library. When this macro is set, the storage class will
+ * be set to DLLEXPORT. At the end of the header file, the storage class will
+ * be reset to DLLIMPORT.
+ */
+
+#undef TCL_STORAGE_CLASS
+#ifdef BUILD_tcl
+# define TCL_STORAGE_CLASS DLLEXPORT
+#else
+# ifdef USE_TCL_STUBS
+# define TCL_STORAGE_CLASS
+# else
+# define TCL_STORAGE_CLASS DLLIMPORT
+# endif
+#endif
+
+/*
+ * The following _ANSI_ARGS_ macro is to support old extensions
+ * written for older versions of Tcl where it permitted support
+ * for compilers written in the pre-prototype era of C.
+ *
+ * New code should use prototypes.
+ */
+
+#ifndef TCL_NO_DEPRECATED
+# undef _ANSI_ARGS_
+# define _ANSI_ARGS_(x) x
+#endif
+
+/*
+ * Definitions that allow this header file to be used either with or without
+ * ANSI C features.
+ */
+
+#ifndef INLINE
+# define INLINE
+#endif
+
+#ifdef NO_CONST
+# ifndef const
+# define const
+# endif
+#endif
+#ifndef CONST
+# define CONST const
+#endif
+
+#ifdef USE_NON_CONST
+# ifdef USE_COMPAT_CONST
+# error define at most one of USE_NON_CONST and USE_COMPAT_CONST
+# endif
+# define CONST84
+# define CONST84_RETURN
+#else
+# ifdef USE_COMPAT_CONST
+# define CONST84
+# define CONST84_RETURN const
+# else
+# define CONST84 const
+# define CONST84_RETURN const
+# endif
+#endif
+
+#ifndef CONST86
+# define CONST86 CONST84
+#endif
+
+/*
+ * Make sure EXTERN isn't defined elsewhere.
+ */
+
+#ifdef EXTERN
+# undef EXTERN
+#endif /* EXTERN */
+
+#ifdef __cplusplus
+# define EXTERN extern "C" TCL_STORAGE_CLASS
+#else
+# define EXTERN extern TCL_STORAGE_CLASS
+#endif
+
+/*
+ *----------------------------------------------------------------------------
+ * The following code is copied from winnt.h. If we don't replicate it here,
+ * then can't be included after tcl.h, since tcl.h also defines
+ * VOID. This block is skipped under Cygwin and Mingw.
+ */
+
+#if defined(__WIN32__) && !defined(HAVE_WINNT_IGNORE_VOID)
+#ifndef VOID
+#define VOID void
+typedef char CHAR;
+typedef short SHORT;
+typedef long LONG;
+#endif
+#endif /* __WIN32__ && !HAVE_WINNT_IGNORE_VOID */
+
+/*
+ * Macro to use instead of "void" for arguments that must have type "void *"
+ * in ANSI C; maps them to type "char *" in non-ANSI systems.
+ */
+
+#ifndef NO_VOID
+# define VOID void
+#else
+# define VOID char
+#endif
+
+/*
+ * Miscellaneous declarations.
+ */
+
+#ifndef _CLIENTDATA
+# ifndef NO_VOID
+ typedef void *ClientData;
+# else
+ typedef int *ClientData;
+# endif
+# define _CLIENTDATA
+#endif
+
+/*
+ * Darwin specific configure overrides (to support fat compiles, where
+ * configure runs only once for multiple architectures):
+ */
+
+#ifdef __APPLE__
+# ifdef __LP64__
+# undef TCL_WIDE_INT_TYPE
+# define TCL_WIDE_INT_IS_LONG 1
+# define TCL_CFG_DO64BIT 1
+# else /* !__LP64__ */
+# define TCL_WIDE_INT_TYPE long long
+# undef TCL_WIDE_INT_IS_LONG
+# undef TCL_CFG_DO64BIT
+# endif /* __LP64__ */
+# undef HAVE_STRUCT_STAT64
+#endif /* __APPLE__ */
+
+/*
+ * Define Tcl_WideInt to be a type that is (at least) 64-bits wide, and define
+ * Tcl_WideUInt to be the unsigned variant of that type (assuming that where
+ * we have one, we can have the other.)
+ *
+ * Also defines the following macros:
+ * TCL_WIDE_INT_IS_LONG - if wide ints are really longs (i.e. we're on a real
+ * 64-bit system.)
+ * Tcl_WideAsLong - forgetful converter from wideInt to long.
+ * Tcl_LongAsWide - sign-extending converter from long to wideInt.
+ * Tcl_WideAsDouble - converter from wideInt to double.
+ * Tcl_DoubleAsWide - converter from double to wideInt.
+ *
+ * The following invariant should hold for any long value 'longVal':
+ * longVal == Tcl_WideAsLong(Tcl_LongAsWide(longVal))
+ *
+ * Note on converting between Tcl_WideInt and strings. This implementation (in
+ * tclObj.c) depends on the function
+ * sprintf(...,"%" TCL_LL_MODIFIER "d",...).
+ */
+
+#if !defined(TCL_WIDE_INT_TYPE)&&!defined(TCL_WIDE_INT_IS_LONG)
+# if defined(__WIN32__)
+# define TCL_WIDE_INT_TYPE __int64
+# ifdef __BORLANDC__
+# define TCL_LL_MODIFIER "L"
+# else /* __BORLANDC__ */
+# define TCL_LL_MODIFIER "I64"
+# endif /* __BORLANDC__ */
+# elif defined(__GNUC__)
+# define TCL_WIDE_INT_TYPE long long
+# define TCL_LL_MODIFIER "ll"
+# else /* ! __WIN32__ && ! __GNUC__ */
+/*
+ * Don't know what platform it is and configure hasn't discovered what is
+ * going on for us. Try to guess...
+ */
+# ifdef NO_LIMITS_H
+# error please define either TCL_WIDE_INT_TYPE or TCL_WIDE_INT_IS_LONG
+# else /* !NO_LIMITS_H */
+# include
+# if (INT_MAX < LONG_MAX)
+# define TCL_WIDE_INT_IS_LONG 1
+# else
+# define TCL_WIDE_INT_TYPE long long
+# endif
+# endif /* NO_LIMITS_H */
+# endif /* __WIN32__ */
+#endif /* !TCL_WIDE_INT_TYPE & !TCL_WIDE_INT_IS_LONG */
+#ifdef TCL_WIDE_INT_IS_LONG
+# undef TCL_WIDE_INT_TYPE
+# define TCL_WIDE_INT_TYPE long
+#endif /* TCL_WIDE_INT_IS_LONG */
+
+typedef TCL_WIDE_INT_TYPE Tcl_WideInt;
+typedef unsigned TCL_WIDE_INT_TYPE Tcl_WideUInt;
+
+#ifdef TCL_WIDE_INT_IS_LONG
+# define Tcl_WideAsLong(val) ((long)(val))
+# define Tcl_LongAsWide(val) ((long)(val))
+# define Tcl_WideAsDouble(val) ((double)((long)(val)))
+# define Tcl_DoubleAsWide(val) ((long)((double)(val)))
+# ifndef TCL_LL_MODIFIER
+# define TCL_LL_MODIFIER "l"
+# endif /* !TCL_LL_MODIFIER */
+#else /* TCL_WIDE_INT_IS_LONG */
+/*
+ * The next short section of defines are only done when not running on Windows
+ * or some other strange platform.
+ */
+# ifndef TCL_LL_MODIFIER
+# define TCL_LL_MODIFIER "ll"
+# endif /* !TCL_LL_MODIFIER */
+# define Tcl_WideAsLong(val) ((long)((Tcl_WideInt)(val)))
+# define Tcl_LongAsWide(val) ((Tcl_WideInt)((long)(val)))
+# define Tcl_WideAsDouble(val) ((double)((Tcl_WideInt)(val)))
+# define Tcl_DoubleAsWide(val) ((Tcl_WideInt)((double)(val)))
+#endif /* TCL_WIDE_INT_IS_LONG */
+
+#if defined(__WIN32__)
+# ifdef __BORLANDC__
+ typedef struct stati64 Tcl_StatBuf;
+# elif defined(_WIN64)
+ typedef struct __stat64 Tcl_StatBuf;
+# elif (defined(_MSC_VER) && (_MSC_VER < 1400)) || defined(_USE_32BIT_TIME_T)
+ typedef struct _stati64 Tcl_StatBuf;
+# else
+ typedef struct _stat32i64 Tcl_StatBuf;
+# endif /* _MSC_VER < 1400 */
+#elif defined(__CYGWIN__)
+ typedef struct _stat32i64 {
+ dev_t st_dev;
+ unsigned short st_ino;
+ unsigned short st_mode;
+ short st_nlink;
+ short st_uid;
+ short st_gid;
+ /* Here is a 2-byte gap */
+ dev_t st_rdev;
+ /* Here is a 4-byte gap */
+ long long st_size;
+ struct {long tv_sec;} st_atim;
+ struct {long tv_sec;} st_mtim;
+ struct {long tv_sec;} st_ctim;
+ /* Here is a 4-byte gap */
+ } Tcl_StatBuf;
+#elif defined(HAVE_STRUCT_STAT64)
+ typedef struct stat64 Tcl_StatBuf;
+#else
+ typedef struct stat Tcl_StatBuf;
+#endif
+
+/*
+ *----------------------------------------------------------------------------
+ * Data structures defined opaquely in this module. The definitions below just
+ * provide dummy types. A few fields are made visible in Tcl_Interp
+ * structures, namely those used for returning a string result from commands.
+ * Direct access to the result field is discouraged in Tcl 8.0. The
+ * interpreter result is either an object or a string, and the two values are
+ * kept consistent unless some C code sets interp->result directly.
+ * Programmers should use either the function Tcl_GetObjResult() or
+ * Tcl_GetStringResult() to read the interpreter's result. See the SetResult
+ * man page for details.
+ *
+ * Note: any change to the Tcl_Interp definition below must be mirrored in the
+ * "real" definition in tclInt.h.
+ *
+ * Note: Tcl_ObjCmdProc functions do not directly set result and freeProc.
+ * Instead, they set a Tcl_Obj member in the "real" structure that can be
+ * accessed with Tcl_GetObjResult() and Tcl_SetObjResult().
+ */
+
+typedef struct Tcl_Interp
+#ifndef TCL_NO_DEPRECATED
+{
+ /* TIP #330: Strongly discourage extensions from using the string
+ * result. */
+#ifdef USE_INTERP_RESULT
+ char *result TCL_DEPRECATED_API("use Tcl_GetResult/Tcl_SetResult");
+ /* If the last command returned a string
+ * result, this points to it. */
+ void (*freeProc) (char *blockPtr)
+ TCL_DEPRECATED_API("use Tcl_GetResult/Tcl_SetResult");
+ /* Zero means the string result is statically
+ * allocated. TCL_DYNAMIC means it was
+ * allocated with ckalloc and should be freed
+ * with ckfree. Other values give the address
+ * of function to invoke to free the result.
+ * Tcl_Eval must free it before executing next
+ * command. */
+#else
+ char *resultDontUse; /* Don't use in extensions! */
+ void (*freeProcDontUse) (char *); /* Don't use in extensions! */
+#endif
+#ifdef USE_INTERP_ERRORLINE
+ int errorLine TCL_DEPRECATED_API("use Tcl_GetErrorLine/Tcl_SetErrorLine");
+ /* When TCL_ERROR is returned, this gives the
+ * line number within the command where the
+ * error occurred (1 if first line). */
+#else
+ int errorLineDontUse; /* Don't use in extensions! */
+#endif
+}
+#endif /* TCL_NO_DEPRECATED */
+Tcl_Interp;
+
+typedef struct Tcl_AsyncHandler_ *Tcl_AsyncHandler;
+typedef struct Tcl_Channel_ *Tcl_Channel;
+typedef struct Tcl_ChannelTypeVersion_ *Tcl_ChannelTypeVersion;
+typedef struct Tcl_Command_ *Tcl_Command;
+typedef struct Tcl_Condition_ *Tcl_Condition;
+typedef struct Tcl_Dict_ *Tcl_Dict;
+typedef struct Tcl_EncodingState_ *Tcl_EncodingState;
+typedef struct Tcl_Encoding_ *Tcl_Encoding;
+typedef struct Tcl_Event Tcl_Event;
+typedef struct Tcl_InterpState_ *Tcl_InterpState;
+typedef struct Tcl_LoadHandle_ *Tcl_LoadHandle;
+typedef struct Tcl_Mutex_ *Tcl_Mutex;
+typedef struct Tcl_Pid_ *Tcl_Pid;
+typedef struct Tcl_RegExp_ *Tcl_RegExp;
+typedef struct Tcl_ThreadDataKey_ *Tcl_ThreadDataKey;
+typedef struct Tcl_ThreadId_ *Tcl_ThreadId;
+typedef struct Tcl_TimerToken_ *Tcl_TimerToken;
+typedef struct Tcl_Trace_ *Tcl_Trace;
+typedef struct Tcl_Var_ *Tcl_Var;
+typedef struct Tcl_ZLibStream_ *Tcl_ZlibStream;
+
+/*
+ *----------------------------------------------------------------------------
+ * Definition of the interface to functions implementing threads. A function
+ * following this definition is given to each call of 'Tcl_CreateThread' and
+ * will be called as the main fuction of the new thread created by that call.
+ */
+
+#if defined __WIN32__
+typedef unsigned (__stdcall Tcl_ThreadCreateProc) (ClientData clientData);
+#else
+typedef void (Tcl_ThreadCreateProc) (ClientData clientData);
+#endif
+
+/*
+ * Threading function return types used for abstracting away platform
+ * differences when writing a Tcl_ThreadCreateProc. See the NewThread function
+ * in generic/tclThreadTest.c for it's usage.
+ */
+
+#if defined __WIN32__
+# define Tcl_ThreadCreateType unsigned __stdcall
+# define TCL_THREAD_CREATE_RETURN return 0
+#else
+# define Tcl_ThreadCreateType void
+# define TCL_THREAD_CREATE_RETURN
+#endif
+
+/*
+ * Definition of values for default stacksize and the possible flags to be
+ * given to Tcl_CreateThread.
+ */
+
+#define TCL_THREAD_STACK_DEFAULT (0) /* Use default size for stack. */
+#define TCL_THREAD_NOFLAGS (0000) /* Standard flags, default
+ * behaviour. */
+#define TCL_THREAD_JOINABLE (0001) /* Mark the thread as joinable. */
+
+/*
+ * Flag values passed to Tcl_StringCaseMatch.
+ */
+
+#define TCL_MATCH_NOCASE (1<<0)
+
+/*
+ * Flag values passed to Tcl_GetRegExpFromObj.
+ */
+
+#define TCL_REG_BASIC 000000 /* BREs (convenience). */
+#define TCL_REG_EXTENDED 000001 /* EREs. */
+#define TCL_REG_ADVF 000002 /* Advanced features in EREs. */
+#define TCL_REG_ADVANCED 000003 /* AREs (which are also EREs). */
+#define TCL_REG_QUOTE 000004 /* No special characters, none. */
+#define TCL_REG_NOCASE 000010 /* Ignore case. */
+#define TCL_REG_NOSUB 000020 /* Don't care about subexpressions. */
+#define TCL_REG_EXPANDED 000040 /* Expanded format, white space &
+ * comments. */
+#define TCL_REG_NLSTOP 000100 /* \n doesn't match . or [^ ] */
+#define TCL_REG_NLANCH 000200 /* ^ matches after \n, $ before. */
+#define TCL_REG_NEWLINE 000300 /* Newlines are line terminators. */
+#define TCL_REG_CANMATCH 001000 /* Report details on partial/limited
+ * matches. */
+
+/*
+ * Flags values passed to Tcl_RegExpExecObj.
+ */
+
+#define TCL_REG_NOTBOL 0001 /* Beginning of string does not match ^. */
+#define TCL_REG_NOTEOL 0002 /* End of string does not match $. */
+
+/*
+ * Structures filled in by Tcl_RegExpInfo. Note that all offset values are
+ * relative to the start of the match string, not the beginning of the entire
+ * string.
+ */
+
+typedef struct Tcl_RegExpIndices {
+ long start; /* Character offset of first character in
+ * match. */
+ long end; /* Character offset of first character after
+ * the match. */
+} Tcl_RegExpIndices;
+
+typedef struct Tcl_RegExpInfo {
+ int nsubs; /* Number of subexpressions in the compiled
+ * expression. */
+ Tcl_RegExpIndices *matches; /* Array of nsubs match offset pairs. */
+ long extendStart; /* The offset at which a subsequent match
+ * might begin. */
+ long reserved; /* Reserved for later use. */
+} Tcl_RegExpInfo;
+
+/*
+ * Picky compilers complain if this typdef doesn't appear before the struct's
+ * reference in tclDecls.h.
+ */
+
+typedef Tcl_StatBuf *Tcl_Stat_;
+typedef struct stat *Tcl_OldStat_;
+
+/*
+ *----------------------------------------------------------------------------
+ * When a TCL command returns, the interpreter contains a result from the
+ * command. Programmers are strongly encouraged to use one of the functions
+ * Tcl_GetObjResult() or Tcl_GetStringResult() to read the interpreter's
+ * result. See the SetResult man page for details. Besides this result, the
+ * command function returns an integer code, which is one of the following:
+ *
+ * TCL_OK Command completed normally; the interpreter's result
+ * contains the command's result.
+ * TCL_ERROR The command couldn't be completed successfully; the
+ * interpreter's result describes what went wrong.
+ * TCL_RETURN The command requests that the current function return;
+ * the interpreter's result contains the function's
+ * return value.
+ * TCL_BREAK The command requests that the innermost loop be
+ * exited; the interpreter's result is meaningless.
+ * TCL_CONTINUE Go on to the next iteration of the current loop; the
+ * interpreter's result is meaningless.
+ */
+
+#define TCL_OK 0
+#define TCL_ERROR 1
+#define TCL_RETURN 2
+#define TCL_BREAK 3
+#define TCL_CONTINUE 4
+
+#define TCL_RESULT_SIZE 200
+
+/*
+ *----------------------------------------------------------------------------
+ * Flags to control what substitutions are performed by Tcl_SubstObj():
+ */
+
+#define TCL_SUBST_COMMANDS 001
+#define TCL_SUBST_VARIABLES 002
+#define TCL_SUBST_BACKSLASHES 004
+#define TCL_SUBST_ALL 007
+
+/*
+ * Argument descriptors for math function callbacks in expressions:
+ */
+
+typedef enum {
+ TCL_INT, TCL_DOUBLE, TCL_EITHER, TCL_WIDE_INT
+} Tcl_ValueType;
+
+typedef struct Tcl_Value {
+ Tcl_ValueType type; /* Indicates intValue or doubleValue is valid,
+ * or both. */
+ long intValue; /* Integer value. */
+ double doubleValue; /* Double-precision floating value. */
+ Tcl_WideInt wideValue; /* Wide (min. 64-bit) integer value. */
+} Tcl_Value;
+
+/*
+ * Forward declaration of Tcl_Obj to prevent an error when the forward
+ * reference to Tcl_Obj is encountered in the function types declared below.
+ */
+
+struct Tcl_Obj;
+
+/*
+ *----------------------------------------------------------------------------
+ * Function types defined by Tcl:
+ */
+
+typedef int (Tcl_AppInitProc) (Tcl_Interp *interp);
+typedef int (Tcl_AsyncProc) (ClientData clientData, Tcl_Interp *interp,
+ int code);
+typedef void (Tcl_ChannelProc) (ClientData clientData, int mask);
+typedef void (Tcl_CloseProc) (ClientData data);
+typedef void (Tcl_CmdDeleteProc) (ClientData clientData);
+typedef int (Tcl_CmdProc) (ClientData clientData, Tcl_Interp *interp,
+ int argc, CONST84 char *argv[]);
+typedef void (Tcl_CmdTraceProc) (ClientData clientData, Tcl_Interp *interp,
+ int level, char *command, Tcl_CmdProc *proc,
+ ClientData cmdClientData, int argc, CONST84 char *argv[]);
+typedef int (Tcl_CmdObjTraceProc) (ClientData clientData, Tcl_Interp *interp,
+ int level, const char *command, Tcl_Command commandInfo, int objc,
+ struct Tcl_Obj *const *objv);
+typedef void (Tcl_CmdObjTraceDeleteProc) (ClientData clientData);
+typedef void (Tcl_DupInternalRepProc) (struct Tcl_Obj *srcPtr,
+ struct Tcl_Obj *dupPtr);
+typedef int (Tcl_EncodingConvertProc) (ClientData clientData, const char *src,
+ int srcLen, int flags, Tcl_EncodingState *statePtr, char *dst,
+ int dstLen, int *srcReadPtr, int *dstWrotePtr, int *dstCharsPtr);
+typedef void (Tcl_EncodingFreeProc) (ClientData clientData);
+typedef int (Tcl_EventProc) (Tcl_Event *evPtr, int flags);
+typedef void (Tcl_EventCheckProc) (ClientData clientData, int flags);
+typedef int (Tcl_EventDeleteProc) (Tcl_Event *evPtr, ClientData clientData);
+typedef void (Tcl_EventSetupProc) (ClientData clientData, int flags);
+typedef void (Tcl_ExitProc) (ClientData clientData);
+typedef void (Tcl_FileProc) (ClientData clientData, int mask);
+typedef void (Tcl_FileFreeProc) (ClientData clientData);
+typedef void (Tcl_FreeInternalRepProc) (struct Tcl_Obj *objPtr);
+typedef void (Tcl_FreeProc) (char *blockPtr);
+typedef void (Tcl_IdleProc) (ClientData clientData);
+typedef void (Tcl_InterpDeleteProc) (ClientData clientData,
+ Tcl_Interp *interp);
+typedef int (Tcl_MathProc) (ClientData clientData, Tcl_Interp *interp,
+ Tcl_Value *args, Tcl_Value *resultPtr);
+typedef void (Tcl_NamespaceDeleteProc) (ClientData clientData);
+typedef int (Tcl_ObjCmdProc) (ClientData clientData, Tcl_Interp *interp,
+ int objc, struct Tcl_Obj *const *objv);
+typedef int (Tcl_PackageInitProc) (Tcl_Interp *interp);
+typedef int (Tcl_PackageUnloadProc) (Tcl_Interp *interp, int flags);
+typedef void (Tcl_PanicProc) (const char *format, ...);
+typedef void (Tcl_TcpAcceptProc) (ClientData callbackData, Tcl_Channel chan,
+ char *address, int port);
+typedef void (Tcl_TimerProc) (ClientData clientData);
+typedef int (Tcl_SetFromAnyProc) (Tcl_Interp *interp, struct Tcl_Obj *objPtr);
+typedef void (Tcl_UpdateStringProc) (struct Tcl_Obj *objPtr);
+typedef char * (Tcl_VarTraceProc) (ClientData clientData, Tcl_Interp *interp,
+ CONST84 char *part1, CONST84 char *part2, int flags);
+typedef void (Tcl_CommandTraceProc) (ClientData clientData, Tcl_Interp *interp,
+ const char *oldName, const char *newName, int flags);
+typedef void (Tcl_CreateFileHandlerProc) (int fd, int mask, Tcl_FileProc *proc,
+ ClientData clientData);
+typedef void (Tcl_DeleteFileHandlerProc) (int fd);
+typedef void (Tcl_AlertNotifierProc) (ClientData clientData);
+typedef void (Tcl_ServiceModeHookProc) (int mode);
+typedef ClientData (Tcl_InitNotifierProc) (void);
+typedef void (Tcl_FinalizeNotifierProc) (ClientData clientData);
+typedef void (Tcl_MainLoopProc) (void);
+
+/*
+ *----------------------------------------------------------------------------
+ * The following structure represents a type of object, which is a particular
+ * internal representation for an object plus a set of functions that provide
+ * standard operations on objects of that type.
+ */
+
+typedef struct Tcl_ObjType {
+ const char *name; /* Name of the type, e.g. "int". */
+ Tcl_FreeInternalRepProc *freeIntRepProc;
+ /* Called to free any storage for the type's
+ * internal rep. NULL if the internal rep does
+ * not need freeing. */
+ Tcl_DupInternalRepProc *dupIntRepProc;
+ /* Called to create a new object as a copy of
+ * an existing object. */
+ Tcl_UpdateStringProc *updateStringProc;
+ /* Called to update the string rep from the
+ * type's internal representation. */
+ Tcl_SetFromAnyProc *setFromAnyProc;
+ /* Called to convert the object's internal rep
+ * to this type. Frees the internal rep of the
+ * old type. Returns TCL_ERROR on failure. */
+} Tcl_ObjType;
+
+/*
+ * One of the following structures exists for each object in the Tcl system.
+ * An object stores a value as either a string, some internal representation,
+ * or both.
+ */
+
+typedef struct Tcl_Obj {
+ int refCount; /* When 0 the object will be freed. */
+ char *bytes; /* This points to the first byte of the
+ * object's string representation. The array
+ * must be followed by a null byte (i.e., at
+ * offset length) but may also contain
+ * embedded null characters. The array's
+ * storage is allocated by ckalloc. NULL means
+ * the string rep is invalid and must be
+ * regenerated from the internal rep. Clients
+ * should use Tcl_GetStringFromObj or
+ * Tcl_GetString to get a pointer to the byte
+ * array as a readonly value. */
+ int length; /* The number of bytes at *bytes, not
+ * including the terminating null. */
+ const Tcl_ObjType *typePtr; /* Denotes the object's type. Always
+ * corresponds to the type of the object's
+ * internal rep. NULL indicates the object has
+ * no internal rep (has no type). */
+ union { /* The internal representation: */
+ long longValue; /* - an long integer value. */
+ double doubleValue; /* - a double-precision floating value. */
+ void *otherValuePtr; /* - another, type-specific value. */
+ Tcl_WideInt wideValue; /* - a long long value. */
+ struct { /* - internal rep as two pointers. */
+ void *ptr1;
+ void *ptr2;
+ } twoPtrValue;
+ struct { /* - internal rep as a pointer and a long,
+ * the main use of which is a bignum's
+ * tightly packed fields, where the alloc,
+ * used and signum flags are packed into a
+ * single word with everything else hung
+ * off the pointer. */
+ void *ptr;
+ unsigned long value;
+ } ptrAndLongRep;
+ } internalRep;
+} Tcl_Obj;
+
+/*
+ * Macros to increment and decrement a Tcl_Obj's reference count, and to test
+ * whether an object is shared (i.e. has reference count > 1). Note: clients
+ * should use Tcl_DecrRefCount() when they are finished using an object, and
+ * should never call TclFreeObj() directly. TclFreeObj() is only defined and
+ * made public in tcl.h to support Tcl_DecrRefCount's macro definition.
+ */
+
+void Tcl_IncrRefCount(Tcl_Obj *objPtr);
+void Tcl_DecrRefCount(Tcl_Obj *objPtr);
+int Tcl_IsShared(Tcl_Obj *objPtr);
+
+/*
+ *----------------------------------------------------------------------------
+ * The following structure contains the state needed by Tcl_SaveResult. No-one
+ * outside of Tcl should access any of these fields. This structure is
+ * typically allocated on the stack.
+ */
+
+typedef struct Tcl_SavedResult {
+ char *result;
+ Tcl_FreeProc *freeProc;
+ Tcl_Obj *objResultPtr;
+ char *appendResult;
+ int appendAvl;
+ int appendUsed;
+ char resultSpace[TCL_RESULT_SIZE+1];
+} Tcl_SavedResult;
+
+/*
+ *----------------------------------------------------------------------------
+ * The following definitions support Tcl's namespace facility. Note: the first
+ * five fields must match exactly the fields in a Namespace structure (see
+ * tclInt.h).
+ */
+
+typedef struct Tcl_Namespace {
+ char *name; /* The namespace's name within its parent
+ * namespace. This contains no ::'s. The name
+ * of the global namespace is "" although "::"
+ * is an synonym. */
+ char *fullName; /* The namespace's fully qualified name. This
+ * starts with ::. */
+ ClientData clientData; /* Arbitrary value associated with this
+ * namespace. */
+ Tcl_NamespaceDeleteProc *deleteProc;
+ /* Function invoked when deleting the
+ * namespace to, e.g., free clientData. */
+ struct Tcl_Namespace *parentPtr;
+ /* Points to the namespace that contains this
+ * one. NULL if this is the global
+ * namespace. */
+} Tcl_Namespace;
+
+/*
+ *----------------------------------------------------------------------------
+ * The following structure represents a call frame, or activation record. A
+ * call frame defines a naming context for a procedure call: its local scope
+ * (for local variables) and its namespace scope (used for non-local
+ * variables; often the global :: namespace). A call frame can also define the
+ * naming context for a namespace eval or namespace inscope command: the
+ * namespace in which the command's code should execute. The Tcl_CallFrame
+ * structures exist only while procedures or namespace eval/inscope's are
+ * being executed, and provide a Tcl call stack.
+ *
+ * A call frame is initialized and pushed using Tcl_PushCallFrame and popped
+ * using Tcl_PopCallFrame. Storage for a Tcl_CallFrame must be provided by the
+ * Tcl_PushCallFrame caller, and callers typically allocate them on the C call
+ * stack for efficiency. For this reason, Tcl_CallFrame is defined as a
+ * structure and not as an opaque token. However, most Tcl_CallFrame fields
+ * are hidden since applications should not access them directly; others are
+ * declared as "dummyX".
+ *
+ * WARNING!! The structure definition must be kept consistent with the
+ * CallFrame structure in tclInt.h. If you change one, change the other.
+ */
+
+typedef struct Tcl_CallFrame {
+ Tcl_Namespace *nsPtr;
+ int dummy1;
+ int dummy2;
+ void *dummy3;
+ void *dummy4;
+ void *dummy5;
+ int dummy6;
+ void *dummy7;
+ void *dummy8;
+ int dummy9;
+ void *dummy10;
+ void *dummy11;
+ void *dummy12;
+ void *dummy13;
+} Tcl_CallFrame;
+
+/*
+ *----------------------------------------------------------------------------
+ * Information about commands that is returned by Tcl_GetCommandInfo and
+ * passed to Tcl_SetCommandInfo. objProc is an objc/objv object-based command
+ * function while proc is a traditional Tcl argc/argv string-based function.
+ * Tcl_CreateObjCommand and Tcl_CreateCommand ensure that both objProc and
+ * proc are non-NULL and can be called to execute the command. However, it may
+ * be faster to call one instead of the other. The member isNativeObjectProc
+ * is set to 1 if an object-based function was registered by
+ * Tcl_CreateObjCommand, and to 0 if a string-based function was registered by
+ * Tcl_CreateCommand. The other function is typically set to a compatibility
+ * wrapper that does string-to-object or object-to-string argument conversions
+ * then calls the other function.
+ */
+
+typedef struct Tcl_CmdInfo {
+ int isNativeObjectProc; /* 1 if objProc was registered by a call to
+ * Tcl_CreateObjCommand; 0 otherwise.
+ * Tcl_SetCmdInfo does not modify this
+ * field. */
+ Tcl_ObjCmdProc *objProc; /* Command's object-based function. */
+ ClientData objClientData; /* ClientData for object proc. */
+ Tcl_CmdProc *proc; /* Command's string-based function. */
+ ClientData clientData; /* ClientData for string proc. */
+ Tcl_CmdDeleteProc *deleteProc;
+ /* Function to call when command is
+ * deleted. */
+ ClientData deleteData; /* Value to pass to deleteProc (usually the
+ * same as clientData). */
+ Tcl_Namespace *namespacePtr;/* Points to the namespace that contains this
+ * command. Note that Tcl_SetCmdInfo will not
+ * change a command's namespace; use
+ * TclRenameCommand or Tcl_Eval (of 'rename')
+ * to do that. */
+} Tcl_CmdInfo;
+
+/*
+ *----------------------------------------------------------------------------
+ * The structure defined below is used to hold dynamic strings. The only
+ * fields that clients should use are string and length, accessible via the
+ * macros Tcl_DStringValue and Tcl_DStringLength.
+ */
+
+#define TCL_DSTRING_STATIC_SIZE 200
+typedef struct Tcl_DString {
+ char *string; /* Points to beginning of string: either
+ * staticSpace below or a malloced array. */
+ int length; /* Number of non-NULL characters in the
+ * string. */
+ int spaceAvl; /* Total number of bytes available for the
+ * string and its terminating NULL char. */
+ char staticSpace[TCL_DSTRING_STATIC_SIZE];
+ /* Space to use in common case where string is
+ * small. */
+} Tcl_DString;
+
+#define Tcl_DStringLength(dsPtr) ((dsPtr)->length)
+#define Tcl_DStringValue(dsPtr) ((dsPtr)->string)
+#define Tcl_DStringTrunc Tcl_DStringSetLength
+
+/*
+ * Definitions for the maximum number of digits of precision that may be
+ * specified in the "tcl_precision" variable, and the number of bytes of
+ * buffer space required by Tcl_PrintDouble.
+ */
+
+#define TCL_MAX_PREC 17
+#define TCL_DOUBLE_SPACE (TCL_MAX_PREC+10)
+
+/*
+ * Definition for a number of bytes of buffer space sufficient to hold the
+ * string representation of an integer in base 10 (assuming the existence of
+ * 64-bit integers).
+ */
+
+#define TCL_INTEGER_SPACE 24
+
+/*
+ * Flag values passed to Tcl_ConvertElement.
+ * TCL_DONT_USE_BRACES forces it not to enclose the element in braces, but to
+ * use backslash quoting instead.
+ * TCL_DONT_QUOTE_HASH disables the default quoting of the '#' character. It
+ * is safe to leave the hash unquoted when the element is not the first
+ * element of a list, and this flag can be used by the caller to indicate
+ * that condition.
+ */
+
+#define TCL_DONT_USE_BRACES 1
+#define TCL_DONT_QUOTE_HASH 8
+
+/*
+ * Flag that may be passed to Tcl_GetIndexFromObj to force it to disallow
+ * abbreviated strings.
+ */
+
+#define TCL_EXACT 1
+
+/*
+ *----------------------------------------------------------------------------
+ * Flag values passed to Tcl_RecordAndEval, Tcl_EvalObj, Tcl_EvalObjv.
+ * WARNING: these bit choices must not conflict with the bit choices for
+ * evalFlag bits in tclInt.h!
+ *
+ * Meanings:
+ * TCL_NO_EVAL: Just record this command
+ * TCL_EVAL_GLOBAL: Execute script in global namespace
+ * TCL_EVAL_DIRECT: Do not compile this script
+ * TCL_EVAL_INVOKE: Magical Tcl_EvalObjv mode for aliases/ensembles
+ * o Run in iPtr->lookupNsPtr or global namespace
+ * o Cut out of error traces
+ * o Don't reset the flags controlling ensemble
+ * error message rewriting.
+ * TCL_CANCEL_UNWIND: Magical Tcl_CancelEval mode that causes the
+ * stack for the script in progress to be
+ * completely unwound.
+ * TCL_EVAL_NOERR: Do no exception reporting at all, just return
+ * as the caller will report.
+ */
+
+#define TCL_NO_EVAL 0x010000
+#define TCL_EVAL_GLOBAL 0x020000
+#define TCL_EVAL_DIRECT 0x040000
+#define TCL_EVAL_INVOKE 0x080000
+#define TCL_CANCEL_UNWIND 0x100000
+#define TCL_EVAL_NOERR 0x200000
+
+/*
+ * Special freeProc values that may be passed to Tcl_SetResult (see the man
+ * page for details):
+ */
+
+#define TCL_VOLATILE ((Tcl_FreeProc *) 1)
+#define TCL_STATIC ((Tcl_FreeProc *) 0)
+#define TCL_DYNAMIC ((Tcl_FreeProc *) 3)
+
+/*
+ * Flag values passed to variable-related functions.
+ * WARNING: these bit choices must not conflict with the bit choice for
+ * TCL_CANCEL_UNWIND, above.
+ */
+
+#define TCL_GLOBAL_ONLY 1
+#define TCL_NAMESPACE_ONLY 2
+#define TCL_APPEND_VALUE 4
+#define TCL_LIST_ELEMENT 8
+#define TCL_TRACE_READS 0x10
+#define TCL_TRACE_WRITES 0x20
+#define TCL_TRACE_UNSETS 0x40
+#define TCL_TRACE_DESTROYED 0x80
+#define TCL_INTERP_DESTROYED 0x100
+#define TCL_LEAVE_ERR_MSG 0x200
+#define TCL_TRACE_ARRAY 0x800
+#ifndef TCL_REMOVE_OBSOLETE_TRACES
+/* Required to support old variable/vdelete/vinfo traces. */
+#define TCL_TRACE_OLD_STYLE 0x1000
+#endif
+/* Indicate the semantics of the result of a trace. */
+#define TCL_TRACE_RESULT_DYNAMIC 0x8000
+#define TCL_TRACE_RESULT_OBJECT 0x10000
+
+/*
+ * Flag values for ensemble commands.
+ */
+
+#define TCL_ENSEMBLE_PREFIX 0x02/* Flag value to say whether to allow
+ * unambiguous prefixes of commands or to
+ * require exact matches for command names. */
+
+/*
+ * Flag values passed to command-related functions.
+ */
+
+#define TCL_TRACE_RENAME 0x2000
+#define TCL_TRACE_DELETE 0x4000
+
+#define TCL_ALLOW_INLINE_COMPILATION 0x20000
+
+/*
+ * The TCL_PARSE_PART1 flag is deprecated and has no effect. The part1 is now
+ * always parsed whenever the part2 is NULL. (This is to avoid a common error
+ * when converting code to use the new object based APIs and forgetting to
+ * give the flag)
+ */
+
+#ifndef TCL_NO_DEPRECATED
+# define TCL_PARSE_PART1 0x400
+#endif
+
+/*
+ * Types for linked variables:
+ */
+
+#define TCL_LINK_INT 1
+#define TCL_LINK_DOUBLE 2
+#define TCL_LINK_BOOLEAN 3
+#define TCL_LINK_STRING 4
+#define TCL_LINK_WIDE_INT 5
+#define TCL_LINK_CHAR 6
+#define TCL_LINK_UCHAR 7
+#define TCL_LINK_SHORT 8
+#define TCL_LINK_USHORT 9
+#define TCL_LINK_UINT 10
+#define TCL_LINK_LONG 11
+#define TCL_LINK_ULONG 12
+#define TCL_LINK_FLOAT 13
+#define TCL_LINK_WIDE_UINT 14
+#define TCL_LINK_READ_ONLY 0x80
+
+/*
+ *----------------------------------------------------------------------------
+ * Forward declarations of Tcl_HashTable and related types.
+ */
+
+typedef struct Tcl_HashKeyType Tcl_HashKeyType;
+typedef struct Tcl_HashTable Tcl_HashTable;
+typedef struct Tcl_HashEntry Tcl_HashEntry;
+
+typedef unsigned (Tcl_HashKeyProc) (Tcl_HashTable *tablePtr, void *keyPtr);
+typedef int (Tcl_CompareHashKeysProc) (void *keyPtr, Tcl_HashEntry *hPtr);
+typedef Tcl_HashEntry * (Tcl_AllocHashEntryProc) (Tcl_HashTable *tablePtr,
+ void *keyPtr);
+typedef void (Tcl_FreeHashEntryProc) (Tcl_HashEntry *hPtr);
+
+/*
+ * This flag controls whether the hash table stores the hash of a key, or
+ * recalculates it. There should be no reason for turning this flag off as it
+ * is completely binary and source compatible unless you directly access the
+ * bucketPtr member of the Tcl_HashTableEntry structure. This member has been
+ * removed and the space used to store the hash value.
+ */
+
+#ifndef TCL_HASH_KEY_STORE_HASH
+# define TCL_HASH_KEY_STORE_HASH 1
+#endif
+
+/*
+ * Structure definition for an entry in a hash table. No-one outside Tcl
+ * should access any of these fields directly; use the macros defined below.
+ */
+
+struct Tcl_HashEntry {
+ Tcl_HashEntry *nextPtr; /* Pointer to next entry in this hash bucket,
+ * or NULL for end of chain. */
+ Tcl_HashTable *tablePtr; /* Pointer to table containing entry. */
+#if TCL_HASH_KEY_STORE_HASH
+ void *hash; /* Hash value, stored as pointer to ensure
+ * that the offsets of the fields in this
+ * structure are not changed. */
+#else
+ Tcl_HashEntry **bucketPtr; /* Pointer to bucket that points to first
+ * entry in this entry's chain: used for
+ * deleting the entry. */
+#endif
+ ClientData clientData; /* Application stores something here with
+ * Tcl_SetHashValue. */
+ union { /* Key has one of these forms: */
+ char *oneWordValue; /* One-word value for key. */
+ Tcl_Obj *objPtr; /* Tcl_Obj * key value. */
+ int words[1]; /* Multiple integer words for key. The actual
+ * size will be as large as necessary for this
+ * table's keys. */
+ char string[1]; /* String for key. The actual size will be as
+ * large as needed to hold the key. */
+ } key; /* MUST BE LAST FIELD IN RECORD!! */
+};
+
+/*
+ * Flags used in Tcl_HashKeyType.
+ *
+ * TCL_HASH_KEY_RANDOMIZE_HASH -
+ * There are some things, pointers for example
+ * which don't hash well because they do not use
+ * the lower bits. If this flag is set then the
+ * hash table will attempt to rectify this by
+ * randomising the bits and then using the upper
+ * N bits as the index into the table.
+ * TCL_HASH_KEY_SYSTEM_HASH - If this flag is set then all memory internally
+ * allocated for the hash table that is not for an
+ * entry will use the system heap.
+ */
+
+#define TCL_HASH_KEY_RANDOMIZE_HASH 0x1
+#define TCL_HASH_KEY_SYSTEM_HASH 0x2
+
+/*
+ * Structure definition for the methods associated with a hash table key type.
+ */
+
+#define TCL_HASH_KEY_TYPE_VERSION 1
+struct Tcl_HashKeyType {
+ int version; /* Version of the table. If this structure is
+ * extended in future then the version can be
+ * used to distinguish between different
+ * structures. */
+ int flags; /* Flags, see above for details. */
+ Tcl_HashKeyProc *hashKeyProc;
+ /* Calculates a hash value for the key. If
+ * this is NULL then the pointer itself is
+ * used as a hash value. */
+ Tcl_CompareHashKeysProc *compareKeysProc;
+ /* Compares two keys and returns zero if they
+ * do not match, and non-zero if they do. If
+ * this is NULL then the pointers are
+ * compared. */
+ Tcl_AllocHashEntryProc *allocEntryProc;
+ /* Called to allocate memory for a new entry,
+ * i.e. if the key is a string then this could
+ * allocate a single block which contains
+ * enough space for both the entry and the
+ * string. Only the key field of the allocated
+ * Tcl_HashEntry structure needs to be filled
+ * in. If something else needs to be done to
+ * the key, i.e. incrementing a reference
+ * count then that should be done by this
+ * function. If this is NULL then Tcl_Alloc is
+ * used to allocate enough space for a
+ * Tcl_HashEntry and the key pointer is
+ * assigned to key.oneWordValue. */
+ Tcl_FreeHashEntryProc *freeEntryProc;
+ /* Called to free memory associated with an
+ * entry. If something else needs to be done
+ * to the key, i.e. decrementing a reference
+ * count then that should be done by this
+ * function. If this is NULL then Tcl_Free is
+ * used to free the Tcl_HashEntry. */
+};
+
+/*
+ * Structure definition for a hash table. Must be in tcl.h so clients can
+ * allocate space for these structures, but clients should never access any
+ * fields in this structure.
+ */
+
+#define TCL_SMALL_HASH_TABLE 4
+struct Tcl_HashTable {
+ Tcl_HashEntry **buckets; /* Pointer to bucket array. Each element
+ * points to first entry in bucket's hash
+ * chain, or NULL. */
+ Tcl_HashEntry *staticBuckets[TCL_SMALL_HASH_TABLE];
+ /* Bucket array used for small tables (to
+ * avoid mallocs and frees). */
+ int numBuckets; /* Total number of buckets allocated at
+ * **bucketPtr. */
+ int numEntries; /* Total number of entries present in
+ * table. */
+ int rebuildSize; /* Enlarge table when numEntries gets to be
+ * this large. */
+ int downShift; /* Shift count used in hashing function.
+ * Designed to use high-order bits of
+ * randomized keys. */
+ int mask; /* Mask value used in hashing function. */
+ int keyType; /* Type of keys used in this table. It's
+ * either TCL_CUSTOM_KEYS, TCL_STRING_KEYS,
+ * TCL_ONE_WORD_KEYS, or an integer giving the
+ * number of ints that is the size of the
+ * key. */
+ Tcl_HashEntry *(*findProc) (Tcl_HashTable *tablePtr, const char *key);
+ Tcl_HashEntry *(*createProc) (Tcl_HashTable *tablePtr, const char *key,
+ int *newPtr);
+ const Tcl_HashKeyType *typePtr;
+ /* Type of the keys used in the
+ * Tcl_HashTable. */
+};
+
+/*
+ * Structure definition for information used to keep track of searches through
+ * hash tables:
+ */
+
+typedef struct Tcl_HashSearch {
+ Tcl_HashTable *tablePtr; /* Table being searched. */
+ int nextIndex; /* Index of next bucket to be enumerated after
+ * present one. */
+ Tcl_HashEntry *nextEntryPtr;/* Next entry to be enumerated in the current
+ * bucket. */
+} Tcl_HashSearch;
+
+/*
+ * Acceptable key types for hash tables:
+ *
+ * TCL_STRING_KEYS: The keys are strings, they are copied into the
+ * entry.
+ * TCL_ONE_WORD_KEYS: The keys are pointers, the pointer is stored
+ * in the entry.
+ * TCL_CUSTOM_TYPE_KEYS: The keys are arbitrary types which are copied
+ * into the entry.
+ * TCL_CUSTOM_PTR_KEYS: The keys are pointers to arbitrary types, the
+ * pointer is stored in the entry.
+ *
+ * While maintaining binary compatability the above have to be distinct values
+ * as they are used to differentiate between old versions of the hash table
+ * which don't have a typePtr and new ones which do. Once binary compatability
+ * is discarded in favour of making more wide spread changes TCL_STRING_KEYS
+ * can be the same as TCL_CUSTOM_TYPE_KEYS, and TCL_ONE_WORD_KEYS can be the
+ * same as TCL_CUSTOM_PTR_KEYS because they simply determine how the key is
+ * accessed from the entry and not the behaviour.
+ */
+
+#define TCL_STRING_KEYS (0)
+#define TCL_ONE_WORD_KEYS (1)
+#define TCL_CUSTOM_TYPE_KEYS (-2)
+#define TCL_CUSTOM_PTR_KEYS (-1)
+
+/*
+ * Structure definition for information used to keep track of searches through
+ * dictionaries. These fields should not be accessed by code outside
+ * tclDictObj.c
+ */
+
+typedef struct {
+ void *next; /* Search position for underlying hash
+ * table. */
+ int epoch; /* Epoch marker for dictionary being searched,
+ * or -1 if search has terminated. */
+ Tcl_Dict dictionaryPtr; /* Reference to dictionary being searched. */
+} Tcl_DictSearch;
+
+/*
+ *----------------------------------------------------------------------------
+ * Flag values to pass to Tcl_DoOneEvent to disable searches for some kinds of
+ * events:
+ */
+
+#define TCL_DONT_WAIT (1<<1)
+#define TCL_WINDOW_EVENTS (1<<2)
+#define TCL_FILE_EVENTS (1<<3)
+#define TCL_TIMER_EVENTS (1<<4)
+#define TCL_IDLE_EVENTS (1<<5) /* WAS 0x10 ???? */
+#define TCL_ALL_EVENTS (~TCL_DONT_WAIT)
+
+/*
+ * The following structure defines a generic event for the Tcl event system.
+ * These are the things that are queued in calls to Tcl_QueueEvent and
+ * serviced later by Tcl_DoOneEvent. There can be many different kinds of
+ * events with different fields, corresponding to window events, timer events,
+ * etc. The structure for a particular event consists of a Tcl_Event header
+ * followed by additional information specific to that event.
+ */
+
+struct Tcl_Event {
+ Tcl_EventProc *proc; /* Function to call to service this event. */
+ struct Tcl_Event *nextPtr; /* Next in list of pending events, or NULL. */
+};
+
+/*
+ * Positions to pass to Tcl_QueueEvent:
+ */
+
+typedef enum {
+ TCL_QUEUE_TAIL, TCL_QUEUE_HEAD, TCL_QUEUE_MARK
+} Tcl_QueuePosition;
+
+/*
+ * Values to pass to Tcl_SetServiceMode to specify the behavior of notifier
+ * event routines.
+ */
+
+#define TCL_SERVICE_NONE 0
+#define TCL_SERVICE_ALL 1
+
+/*
+ * The following structure keeps is used to hold a time value, either as an
+ * absolute time (the number of seconds from the epoch) or as an elapsed time.
+ * On Unix systems the epoch is Midnight Jan 1, 1970 GMT.
+ */
+
+typedef struct Tcl_Time {
+ long sec; /* Seconds. */
+ long usec; /* Microseconds. */
+} Tcl_Time;
+
+typedef void (Tcl_SetTimerProc) (CONST86 Tcl_Time *timePtr);
+typedef int (Tcl_WaitForEventProc) (CONST86 Tcl_Time *timePtr);
+
+/*
+ * TIP #233 (Virtualized Time)
+ */
+
+typedef void (Tcl_GetTimeProc) (Tcl_Time *timebuf, ClientData clientData);
+typedef void (Tcl_ScaleTimeProc) (Tcl_Time *timebuf, ClientData clientData);
+
+/*
+ *----------------------------------------------------------------------------
+ * Bits to pass to Tcl_CreateFileHandler and Tcl_CreateChannelHandler to
+ * indicate what sorts of events are of interest:
+ */
+
+#define TCL_READABLE (1<<1)
+#define TCL_WRITABLE (1<<2)
+#define TCL_EXCEPTION (1<<3)
+
+/*
+ * Flag values to pass to Tcl_OpenCommandChannel to indicate the disposition
+ * of the stdio handles. TCL_STDIN, TCL_STDOUT, TCL_STDERR, are also used in
+ * Tcl_GetStdChannel.
+ */
+
+#define TCL_STDIN (1<<1)
+#define TCL_STDOUT (1<<2)
+#define TCL_STDERR (1<<3)
+#define TCL_ENFORCE_MODE (1<<4)
+
+/*
+ * Bits passed to Tcl_DriverClose2Proc to indicate which side of a channel
+ * should be closed.
+ */
+
+#define TCL_CLOSE_READ (1<<1)
+#define TCL_CLOSE_WRITE (1<<2)
+
+/*
+ * Value to use as the closeProc for a channel that supports the close2Proc
+ * interface.
+ */
+
+#define TCL_CLOSE2PROC ((Tcl_DriverCloseProc *) 1)
+
+/*
+ * Channel version tag. This was introduced in 8.3.2/8.4.
+ */
+
+#define TCL_CHANNEL_VERSION_1 ((Tcl_ChannelTypeVersion) 0x1)
+#define TCL_CHANNEL_VERSION_2 ((Tcl_ChannelTypeVersion) 0x2)
+#define TCL_CHANNEL_VERSION_3 ((Tcl_ChannelTypeVersion) 0x3)
+#define TCL_CHANNEL_VERSION_4 ((Tcl_ChannelTypeVersion) 0x4)
+#define TCL_CHANNEL_VERSION_5 ((Tcl_ChannelTypeVersion) 0x5)
+
+/*
+ * TIP #218: Channel Actions, Ids for Tcl_DriverThreadActionProc.
+ */
+
+#define TCL_CHANNEL_THREAD_INSERT (0)
+#define TCL_CHANNEL_THREAD_REMOVE (1)
+
+/*
+ * Typedefs for the various operations in a channel type:
+ */
+
+typedef int (Tcl_DriverBlockModeProc) (ClientData instanceData, int mode);
+typedef int (Tcl_DriverCloseProc) (ClientData instanceData,
+ Tcl_Interp *interp);
+typedef int (Tcl_DriverClose2Proc) (ClientData instanceData,
+ Tcl_Interp *interp, int flags);
+typedef int (Tcl_DriverInputProc) (ClientData instanceData, char *buf,
+ int toRead, int *errorCodePtr);
+typedef int (Tcl_DriverOutputProc) (ClientData instanceData,
+ CONST84 char *buf, int toWrite, int *errorCodePtr);
+typedef int (Tcl_DriverSeekProc) (ClientData instanceData, long offset,
+ int mode, int *errorCodePtr);
+typedef int (Tcl_DriverSetOptionProc) (ClientData instanceData,
+ Tcl_Interp *interp, const char *optionName,
+ const char *value);
+typedef int (Tcl_DriverGetOptionProc) (ClientData instanceData,
+ Tcl_Interp *interp, CONST84 char *optionName,
+ Tcl_DString *dsPtr);
+typedef void (Tcl_DriverWatchProc) (ClientData instanceData, int mask);
+typedef int (Tcl_DriverGetHandleProc) (ClientData instanceData,
+ int direction, ClientData *handlePtr);
+typedef int (Tcl_DriverFlushProc) (ClientData instanceData);
+typedef int (Tcl_DriverHandlerProc) (ClientData instanceData,
+ int interestMask);
+typedef Tcl_WideInt (Tcl_DriverWideSeekProc) (ClientData instanceData,
+ Tcl_WideInt offset, int mode, int *errorCodePtr);
+/*
+ * TIP #218, Channel Thread Actions
+ */
+typedef void (Tcl_DriverThreadActionProc) (ClientData instanceData,
+ int action);
+/*
+ * TIP #208, File Truncation (etc.)
+ */
+typedef int (Tcl_DriverTruncateProc) (ClientData instanceData,
+ Tcl_WideInt length);
+
+/*
+ * struct Tcl_ChannelType:
+ *
+ * One such structure exists for each type (kind) of channel. It collects
+ * together in one place all the functions that are part of the specific
+ * channel type.
+ *
+ * It is recommend that the Tcl_Channel* functions are used to access elements
+ * of this structure, instead of direct accessing.
+ */
+
+typedef struct Tcl_ChannelType {
+ const char *typeName; /* The name of the channel type in Tcl
+ * commands. This storage is owned by channel
+ * type. */
+ Tcl_ChannelTypeVersion version;
+ /* Version of the channel type. */
+ Tcl_DriverCloseProc *closeProc;
+ /* Function to call to close the channel, or
+ * TCL_CLOSE2PROC if the close2Proc should be
+ * used instead. */
+ Tcl_DriverInputProc *inputProc;
+ /* Function to call for input on channel. */
+ Tcl_DriverOutputProc *outputProc;
+ /* Function to call for output on channel. */
+ Tcl_DriverSeekProc *seekProc;
+ /* Function to call to seek on the channel.
+ * May be NULL. */
+ Tcl_DriverSetOptionProc *setOptionProc;
+ /* Set an option on a channel. */
+ Tcl_DriverGetOptionProc *getOptionProc;
+ /* Get an option from a channel. */
+ Tcl_DriverWatchProc *watchProc;
+ /* Set up the notifier to watch for events on
+ * this channel. */
+ Tcl_DriverGetHandleProc *getHandleProc;
+ /* Get an OS handle from the channel or NULL
+ * if not supported. */
+ Tcl_DriverClose2Proc *close2Proc;
+ /* Function to call to close the channel if
+ * the device supports closing the read &
+ * write sides independently. */
+ Tcl_DriverBlockModeProc *blockModeProc;
+ /* Set blocking mode for the raw channel. May
+ * be NULL. */
+ /*
+ * Only valid in TCL_CHANNEL_VERSION_2 channels or later.
+ */
+ Tcl_DriverFlushProc *flushProc;
+ /* Function to call to flush a channel. May be
+ * NULL. */
+ Tcl_DriverHandlerProc *handlerProc;
+ /* Function to call to handle a channel event.
+ * This will be passed up the stacked channel
+ * chain. */
+ /*
+ * Only valid in TCL_CHANNEL_VERSION_3 channels or later.
+ */
+ Tcl_DriverWideSeekProc *wideSeekProc;
+ /* Function to call to seek on the channel
+ * which can handle 64-bit offsets. May be
+ * NULL, and must be NULL if seekProc is
+ * NULL. */
+ /*
+ * Only valid in TCL_CHANNEL_VERSION_4 channels or later.
+ * TIP #218, Channel Thread Actions.
+ */
+ Tcl_DriverThreadActionProc *threadActionProc;
+ /* Function to call to notify the driver of
+ * thread specific activity for a channel. May
+ * be NULL. */
+ /*
+ * Only valid in TCL_CHANNEL_VERSION_5 channels or later.
+ * TIP #208, File Truncation.
+ */
+ Tcl_DriverTruncateProc *truncateProc;
+ /* Function to call to truncate the underlying
+ * file to a particular length. May be NULL if
+ * the channel does not support truncation. */
+} Tcl_ChannelType;
+
+/*
+ * The following flags determine whether the blockModeProc above should set
+ * the channel into blocking or nonblocking mode. They are passed as arguments
+ * to the blockModeProc function in the above structure.
+ */
+
+#define TCL_MODE_BLOCKING 0 /* Put channel into blocking mode. */
+#define TCL_MODE_NONBLOCKING 1 /* Put channel into nonblocking
+ * mode. */
+
+/*
+ *----------------------------------------------------------------------------
+ * Enum for different types of file paths.
+ */
+
+typedef enum Tcl_PathType {
+ TCL_PATH_ABSOLUTE,
+ TCL_PATH_RELATIVE,
+ TCL_PATH_VOLUME_RELATIVE
+} Tcl_PathType;
+
+/*
+ * The following structure is used to pass glob type data amongst the various
+ * glob routines and Tcl_FSMatchInDirectory.
+ */
+
+typedef struct Tcl_GlobTypeData {
+ int type; /* Corresponds to bcdpfls as in 'find -t'. */
+ int perm; /* Corresponds to file permissions. */
+ Tcl_Obj *macType; /* Acceptable Mac type. */
+ Tcl_Obj *macCreator; /* Acceptable Mac creator. */
+} Tcl_GlobTypeData;
+
+/*
+ * Type and permission definitions for glob command.
+ */
+
+#define TCL_GLOB_TYPE_BLOCK (1<<0)
+#define TCL_GLOB_TYPE_CHAR (1<<1)
+#define TCL_GLOB_TYPE_DIR (1<<2)
+#define TCL_GLOB_TYPE_PIPE (1<<3)
+#define TCL_GLOB_TYPE_FILE (1<<4)
+#define TCL_GLOB_TYPE_LINK (1<<5)
+#define TCL_GLOB_TYPE_SOCK (1<<6)
+#define TCL_GLOB_TYPE_MOUNT (1<<7)
+
+#define TCL_GLOB_PERM_RONLY (1<<0)
+#define TCL_GLOB_PERM_HIDDEN (1<<1)
+#define TCL_GLOB_PERM_R (1<<2)
+#define TCL_GLOB_PERM_W (1<<3)
+#define TCL_GLOB_PERM_X (1<<4)
+
+/*
+ * Flags for the unload callback function.
+ */
+
+#define TCL_UNLOAD_DETACH_FROM_INTERPRETER (1<<0)
+#define TCL_UNLOAD_DETACH_FROM_PROCESS (1<<1)
+
+/*
+ * Typedefs for the various filesystem operations:
+ */
+
+typedef int (Tcl_FSStatProc) (Tcl_Obj *pathPtr, Tcl_StatBuf *buf);
+typedef int (Tcl_FSAccessProc) (Tcl_Obj *pathPtr, int mode);
+typedef Tcl_Channel (Tcl_FSOpenFileChannelProc) (Tcl_Interp *interp,
+ Tcl_Obj *pathPtr, int mode, int permissions);
+typedef int (Tcl_FSMatchInDirectoryProc) (Tcl_Interp *interp, Tcl_Obj *result,
+ Tcl_Obj *pathPtr, const char *pattern, Tcl_GlobTypeData *types);
+typedef Tcl_Obj * (Tcl_FSGetCwdProc) (Tcl_Interp *interp);
+typedef int (Tcl_FSChdirProc) (Tcl_Obj *pathPtr);
+typedef int (Tcl_FSLstatProc) (Tcl_Obj *pathPtr, Tcl_StatBuf *buf);
+typedef int (Tcl_FSCreateDirectoryProc) (Tcl_Obj *pathPtr);
+typedef int (Tcl_FSDeleteFileProc) (Tcl_Obj *pathPtr);
+typedef int (Tcl_FSCopyDirectoryProc) (Tcl_Obj *srcPathPtr,
+ Tcl_Obj *destPathPtr, Tcl_Obj **errorPtr);
+typedef int (Tcl_FSCopyFileProc) (Tcl_Obj *srcPathPtr, Tcl_Obj *destPathPtr);
+typedef int (Tcl_FSRemoveDirectoryProc) (Tcl_Obj *pathPtr, int recursive,
+ Tcl_Obj **errorPtr);
+typedef int (Tcl_FSRenameFileProc) (Tcl_Obj *srcPathPtr, Tcl_Obj *destPathPtr);
+typedef void (Tcl_FSUnloadFileProc) (Tcl_LoadHandle loadHandle);
+typedef Tcl_Obj * (Tcl_FSListVolumesProc) (void);
+/* We have to declare the utime structure here. */
+struct utimbuf;
+typedef int (Tcl_FSUtimeProc) (Tcl_Obj *pathPtr, struct utimbuf *tval);
+typedef int (Tcl_FSNormalizePathProc) (Tcl_Interp *interp, Tcl_Obj *pathPtr,
+ int nextCheckpoint);
+typedef int (Tcl_FSFileAttrsGetProc) (Tcl_Interp *interp, int index,
+ Tcl_Obj *pathPtr, Tcl_Obj **objPtrRef);
+typedef const char *CONST86 * (Tcl_FSFileAttrStringsProc) (Tcl_Obj *pathPtr,
+ Tcl_Obj **objPtrRef);
+typedef int (Tcl_FSFileAttrsSetProc) (Tcl_Interp *interp, int index,
+ Tcl_Obj *pathPtr, Tcl_Obj *objPtr);
+typedef Tcl_Obj * (Tcl_FSLinkProc) (Tcl_Obj *pathPtr, Tcl_Obj *toPtr,
+ int linkType);
+typedef int (Tcl_FSLoadFileProc) (Tcl_Interp *interp, Tcl_Obj *pathPtr,
+ Tcl_LoadHandle *handlePtr, Tcl_FSUnloadFileProc **unloadProcPtr);
+typedef int (Tcl_FSPathInFilesystemProc) (Tcl_Obj *pathPtr,
+ ClientData *clientDataPtr);
+typedef Tcl_Obj * (Tcl_FSFilesystemPathTypeProc) (Tcl_Obj *pathPtr);
+typedef Tcl_Obj * (Tcl_FSFilesystemSeparatorProc) (Tcl_Obj *pathPtr);
+typedef void (Tcl_FSFreeInternalRepProc) (ClientData clientData);
+typedef ClientData (Tcl_FSDupInternalRepProc) (ClientData clientData);
+typedef Tcl_Obj * (Tcl_FSInternalToNormalizedProc) (ClientData clientData);
+typedef ClientData (Tcl_FSCreateInternalRepProc) (Tcl_Obj *pathPtr);
+
+typedef struct Tcl_FSVersion_ *Tcl_FSVersion;
+
+/*
+ *----------------------------------------------------------------------------
+ * Data structures related to hooking into the filesystem
+ */
+
+/*
+ * Filesystem version tag. This was introduced in 8.4.
+ */
+
+#define TCL_FILESYSTEM_VERSION_1 ((Tcl_FSVersion) 0x1)
+
+/*
+ * struct Tcl_Filesystem:
+ *
+ * One such structure exists for each type (kind) of filesystem. It collects
+ * together in one place all the functions that are part of the specific
+ * filesystem. Tcl always accesses the filesystem through one of these
+ * structures.
+ *
+ * Not all entries need be non-NULL; any which are NULL are simply ignored.
+ * However, a complete filesystem should provide all of these functions. The
+ * explanations in the structure show the importance of each function.
+ */
+
+typedef struct Tcl_Filesystem {
+ const char *typeName; /* The name of the filesystem. */
+ int structureLength; /* Length of this structure, so future binary
+ * compatibility can be assured. */
+ Tcl_FSVersion version; /* Version of the filesystem type. */
+ Tcl_FSPathInFilesystemProc *pathInFilesystemProc;
+ /* Function to check whether a path is in this
+ * filesystem. This is the most important
+ * filesystem function. */
+ Tcl_FSDupInternalRepProc *dupInternalRepProc;
+ /* Function to duplicate internal fs rep. May
+ * be NULL (but then fs is less efficient). */
+ Tcl_FSFreeInternalRepProc *freeInternalRepProc;
+ /* Function to free internal fs rep. Must be
+ * implemented if internal representations
+ * need freeing, otherwise it can be NULL. */
+ Tcl_FSInternalToNormalizedProc *internalToNormalizedProc;
+ /* Function to convert internal representation
+ * to a normalized path. Only required if the
+ * fs creates pure path objects with no
+ * string/path representation. */
+ Tcl_FSCreateInternalRepProc *createInternalRepProc;
+ /* Function to create a filesystem-specific
+ * internal representation. May be NULL if
+ * paths have no internal representation, or
+ * if the Tcl_FSPathInFilesystemProc for this
+ * filesystem always immediately creates an
+ * internal representation for paths it
+ * accepts. */
+ Tcl_FSNormalizePathProc *normalizePathProc;
+ /* Function to normalize a path. Should be
+ * implemented for all filesystems which can
+ * have multiple string representations for
+ * the same path object. */
+ Tcl_FSFilesystemPathTypeProc *filesystemPathTypeProc;
+ /* Function to determine the type of a path in
+ * this filesystem. May be NULL. */
+ Tcl_FSFilesystemSeparatorProc *filesystemSeparatorProc;
+ /* Function to return the separator
+ * character(s) for this filesystem. Must be
+ * implemented. */
+ Tcl_FSStatProc *statProc; /* Function to process a 'Tcl_FSStat()' call.
+ * Must be implemented for any reasonable
+ * filesystem. */
+ Tcl_FSAccessProc *accessProc;
+ /* Function to process a 'Tcl_FSAccess()'
+ * call. Must be implemented for any
+ * reasonable filesystem. */
+ Tcl_FSOpenFileChannelProc *openFileChannelProc;
+ /* Function to process a
+ * 'Tcl_FSOpenFileChannel()' call. Must be
+ * implemented for any reasonable
+ * filesystem. */
+ Tcl_FSMatchInDirectoryProc *matchInDirectoryProc;
+ /* Function to process a
+ * 'Tcl_FSMatchInDirectory()'. If not
+ * implemented, then glob and recursive copy
+ * functionality will be lacking in the
+ * filesystem. */
+ Tcl_FSUtimeProc *utimeProc; /* Function to process a 'Tcl_FSUtime()' call.
+ * Required to allow setting (not reading) of
+ * times with 'file mtime', 'file atime' and
+ * the open-r/open-w/fcopy implementation of
+ * 'file copy'. */
+ Tcl_FSLinkProc *linkProc; /* Function to process a 'Tcl_FSLink()' call.
+ * Should be implemented only if the
+ * filesystem supports links (reading or
+ * creating). */
+ Tcl_FSListVolumesProc *listVolumesProc;
+ /* Function to list any filesystem volumes
+ * added by this filesystem. Should be
+ * implemented only if the filesystem adds
+ * volumes at the head of the filesystem. */
+ Tcl_FSFileAttrStringsProc *fileAttrStringsProc;
+ /* Function to list all attributes strings
+ * which are valid for this filesystem. If not
+ * implemented the filesystem will not support
+ * the 'file attributes' command. This allows
+ * arbitrary additional information to be
+ * attached to files in the filesystem. */
+ Tcl_FSFileAttrsGetProc *fileAttrsGetProc;
+ /* Function to process a
+ * 'Tcl_FSFileAttrsGet()' call, used by 'file
+ * attributes'. */
+ Tcl_FSFileAttrsSetProc *fileAttrsSetProc;
+ /* Function to process a
+ * 'Tcl_FSFileAttrsSet()' call, used by 'file
+ * attributes'. */
+ Tcl_FSCreateDirectoryProc *createDirectoryProc;
+ /* Function to process a
+ * 'Tcl_FSCreateDirectory()' call. Should be
+ * implemented unless the FS is read-only. */
+ Tcl_FSRemoveDirectoryProc *removeDirectoryProc;
+ /* Function to process a
+ * 'Tcl_FSRemoveDirectory()' call. Should be
+ * implemented unless the FS is read-only. */
+ Tcl_FSDeleteFileProc *deleteFileProc;
+ /* Function to process a 'Tcl_FSDeleteFile()'
+ * call. Should be implemented unless the FS
+ * is read-only. */
+ Tcl_FSCopyFileProc *copyFileProc;
+ /* Function to process a 'Tcl_FSCopyFile()'
+ * call. If not implemented Tcl will fall back
+ * on open-r, open-w and fcopy as a copying
+ * mechanism, for copying actions initiated in
+ * Tcl (not C). */
+ Tcl_FSRenameFileProc *renameFileProc;
+ /* Function to process a 'Tcl_FSRenameFile()'
+ * call. If not implemented, Tcl will fall
+ * back on a copy and delete mechanism, for
+ * rename actions initiated in Tcl (not C). */
+ Tcl_FSCopyDirectoryProc *copyDirectoryProc;
+ /* Function to process a
+ * 'Tcl_FSCopyDirectory()' call. If not
+ * implemented, Tcl will fall back on a
+ * recursive create-dir, file copy mechanism,
+ * for copying actions initiated in Tcl (not
+ * C). */
+ Tcl_FSLstatProc *lstatProc; /* Function to process a 'Tcl_FSLstat()' call.
+ * If not implemented, Tcl will attempt to use
+ * the 'statProc' defined above instead. */
+ Tcl_FSLoadFileProc *loadFileProc;
+ /* Function to process a 'Tcl_FSLoadFile()'
+ * call. If not implemented, Tcl will fall
+ * back on a copy to native-temp followed by a
+ * Tcl_FSLoadFile on that temporary copy. */
+ Tcl_FSGetCwdProc *getCwdProc;
+ /* Function to process a 'Tcl_FSGetCwd()'
+ * call. Most filesystems need not implement
+ * this. It will usually only be called once,
+ * if 'getcwd' is called before 'chdir'. May
+ * be NULL. */
+ Tcl_FSChdirProc *chdirProc; /* Function to process a 'Tcl_FSChdir()' call.
+ * If filesystems do not implement this, it
+ * will be emulated by a series of directory
+ * access checks. Otherwise, virtual
+ * filesystems which do implement it need only
+ * respond with a positive return result if
+ * the dirName is a valid directory in their
+ * filesystem. They need not remember the
+ * result, since that will be automatically
+ * remembered for use by GetCwd. Real
+ * filesystems should carry out the correct
+ * action (i.e. call the correct system
+ * 'chdir' api). If not implemented, then 'cd'
+ * and 'pwd' will fail inside the
+ * filesystem. */
+} Tcl_Filesystem;
+
+/*
+ * The following definitions are used as values for the 'linkAction' flag to
+ * Tcl_FSLink, or the linkProc of any filesystem. Any combination of flags can
+ * be given. For link creation, the linkProc should create a link which
+ * matches any of the types given.
+ *
+ * TCL_CREATE_SYMBOLIC_LINK - Create a symbolic or soft link.
+ * TCL_CREATE_HARD_LINK - Create a hard link.
+ */
+
+#define TCL_CREATE_SYMBOLIC_LINK 0x01
+#define TCL_CREATE_HARD_LINK 0x02
+
+/*
+ *----------------------------------------------------------------------------
+ * The following structure represents the Notifier functions that you can
+ * override with the Tcl_SetNotifier call.
+ */
+
+typedef struct Tcl_NotifierProcs {
+ Tcl_SetTimerProc *setTimerProc;
+ Tcl_WaitForEventProc *waitForEventProc;
+ Tcl_CreateFileHandlerProc *createFileHandlerProc;
+ Tcl_DeleteFileHandlerProc *deleteFileHandlerProc;
+ Tcl_InitNotifierProc *initNotifierProc;
+ Tcl_FinalizeNotifierProc *finalizeNotifierProc;
+ Tcl_AlertNotifierProc *alertNotifierProc;
+ Tcl_ServiceModeHookProc *serviceModeHookProc;
+} Tcl_NotifierProcs;
+
+/*
+ *----------------------------------------------------------------------------
+ * The following data structures and declarations are for the new Tcl parser.
+ *
+ * For each word of a command, and for each piece of a word such as a variable
+ * reference, one of the following structures is created to describe the
+ * token.
+ */
+
+typedef struct Tcl_Token {
+ int type; /* Type of token, such as TCL_TOKEN_WORD; see
+ * below for valid types. */
+ const char *start; /* First character in token. */
+ int size; /* Number of bytes in token. */
+ int numComponents; /* If this token is composed of other tokens,
+ * this field tells how many of them there are
+ * (including components of components, etc.).
+ * The component tokens immediately follow
+ * this one. */
+} Tcl_Token;
+
+/*
+ * Type values defined for Tcl_Token structures. These values are defined as
+ * mask bits so that it's easy to check for collections of types.
+ *
+ * TCL_TOKEN_WORD - The token describes one word of a command,
+ * from the first non-blank character of the word
+ * (which may be " or {) up to but not including
+ * the space, semicolon, or bracket that
+ * terminates the word. NumComponents counts the
+ * total number of sub-tokens that make up the
+ * word. This includes, for example, sub-tokens
+ * of TCL_TOKEN_VARIABLE tokens.
+ * TCL_TOKEN_SIMPLE_WORD - This token is just like TCL_TOKEN_WORD except
+ * that the word is guaranteed to consist of a
+ * single TCL_TOKEN_TEXT sub-token.
+ * TCL_TOKEN_TEXT - The token describes a range of literal text
+ * that is part of a word. NumComponents is
+ * always 0.
+ * TCL_TOKEN_BS - The token describes a backslash sequence that
+ * must be collapsed. NumComponents is always 0.
+ * TCL_TOKEN_COMMAND - The token describes a command whose result
+ * must be substituted into the word. The token
+ * includes the enclosing brackets. NumComponents
+ * is always 0.
+ * TCL_TOKEN_VARIABLE - The token describes a variable substitution,
+ * including the dollar sign, variable name, and
+ * array index (if there is one) up through the
+ * right parentheses. NumComponents tells how
+ * many additional tokens follow to represent the
+ * variable name. The first token will be a
+ * TCL_TOKEN_TEXT token that describes the
+ * variable name. If the variable is an array
+ * reference then there will be one or more
+ * additional tokens, of type TCL_TOKEN_TEXT,
+ * TCL_TOKEN_BS, TCL_TOKEN_COMMAND, and
+ * TCL_TOKEN_VARIABLE, that describe the array
+ * index; numComponents counts the total number
+ * of nested tokens that make up the variable
+ * reference, including sub-tokens of
+ * TCL_TOKEN_VARIABLE tokens.
+ * TCL_TOKEN_SUB_EXPR - The token describes one subexpression of an
+ * expression, from the first non-blank character
+ * of the subexpression up to but not including
+ * the space, brace, or bracket that terminates
+ * the subexpression. NumComponents counts the
+ * total number of following subtokens that make
+ * up the subexpression; this includes all
+ * subtokens for any nested TCL_TOKEN_SUB_EXPR
+ * tokens. For example, a numeric value used as a
+ * primitive operand is described by a
+ * TCL_TOKEN_SUB_EXPR token followed by a
+ * TCL_TOKEN_TEXT token. A binary subexpression
+ * is described by a TCL_TOKEN_SUB_EXPR token
+ * followed by the TCL_TOKEN_OPERATOR token for
+ * the operator, then TCL_TOKEN_SUB_EXPR tokens
+ * for the left then the right operands.
+ * TCL_TOKEN_OPERATOR - The token describes one expression operator.
+ * An operator might be the name of a math
+ * function such as "abs". A TCL_TOKEN_OPERATOR
+ * token is always preceeded by one
+ * TCL_TOKEN_SUB_EXPR token for the operator's
+ * subexpression, and is followed by zero or more
+ * TCL_TOKEN_SUB_EXPR tokens for the operator's
+ * operands. NumComponents is always 0.
+ * TCL_TOKEN_EXPAND_WORD - This token is just like TCL_TOKEN_WORD except
+ * that it marks a word that began with the
+ * literal character prefix "{*}". This word is
+ * marked to be expanded - that is, broken into
+ * words after substitution is complete.
+ */
+
+#define TCL_TOKEN_WORD 1
+#define TCL_TOKEN_SIMPLE_WORD 2
+#define TCL_TOKEN_TEXT 4
+#define TCL_TOKEN_BS 8
+#define TCL_TOKEN_COMMAND 16
+#define TCL_TOKEN_VARIABLE 32
+#define TCL_TOKEN_SUB_EXPR 64
+#define TCL_TOKEN_OPERATOR 128
+#define TCL_TOKEN_EXPAND_WORD 256
+
+/*
+ * Parsing error types. On any parsing error, one of these values will be
+ * stored in the error field of the Tcl_Parse structure defined below.
+ */
+
+#define TCL_PARSE_SUCCESS 0
+#define TCL_PARSE_QUOTE_EXTRA 1
+#define TCL_PARSE_BRACE_EXTRA 2
+#define TCL_PARSE_MISSING_BRACE 3
+#define TCL_PARSE_MISSING_BRACKET 4
+#define TCL_PARSE_MISSING_PAREN 5
+#define TCL_PARSE_MISSING_QUOTE 6
+#define TCL_PARSE_MISSING_VAR_BRACE 7
+#define TCL_PARSE_SYNTAX 8
+#define TCL_PARSE_BAD_NUMBER 9
+
+/*
+ * A structure of the following type is filled in by Tcl_ParseCommand. It
+ * describes a single command parsed from an input string.
+ */
+
+#define NUM_STATIC_TOKENS 20
+
+typedef struct Tcl_Parse {
+ const char *commentStart; /* Pointer to # that begins the first of one
+ * or more comments preceding the command. */
+ int commentSize; /* Number of bytes in comments (up through
+ * newline character that terminates the last
+ * comment). If there were no comments, this
+ * field is 0. */
+ const char *commandStart; /* First character in first word of
+ * command. */
+ int commandSize; /* Number of bytes in command, including first
+ * character of first word, up through the
+ * terminating newline, close bracket, or
+ * semicolon. */
+ int numWords; /* Total number of words in command. May be
+ * 0. */
+ Tcl_Token *tokenPtr; /* Pointer to first token representing the
+ * words of the command. Initially points to
+ * staticTokens, but may change to point to
+ * malloc-ed space if command exceeds space in
+ * staticTokens. */
+ int numTokens; /* Total number of tokens in command. */
+ int tokensAvailable; /* Total number of tokens available at
+ * *tokenPtr. */
+ int errorType; /* One of the parsing error types defined
+ * above. */
+
+ /*
+ * The fields below are intended only for the private use of the parser.
+ * They should not be used by functions that invoke Tcl_ParseCommand.
+ */
+
+ const char *string; /* The original command string passed to
+ * Tcl_ParseCommand. */
+ const char *end; /* Points to the character just after the last
+ * one in the command string. */
+ Tcl_Interp *interp; /* Interpreter to use for error reporting, or
+ * NULL. */
+ const char *term; /* Points to character in string that
+ * terminated most recent token. Filled in by
+ * ParseTokens. If an error occurs, points to
+ * beginning of region where the error
+ * occurred (e.g. the open brace if the close
+ * brace is missing). */
+ int incomplete; /* This field is set to 1 by Tcl_ParseCommand
+ * if the command appears to be incomplete.
+ * This information is used by
+ * Tcl_CommandComplete. */
+ Tcl_Token staticTokens[NUM_STATIC_TOKENS];
+ /* Initial space for tokens for command. This
+ * space should be large enough to accommodate
+ * most commands; dynamic space is allocated
+ * for very large commands that don't fit
+ * here. */
+} Tcl_Parse;
+
+/*
+ *----------------------------------------------------------------------------
+ * The following structure represents a user-defined encoding. It collects
+ * together all the functions that are used by the specific encoding.
+ */
+
+typedef struct Tcl_EncodingType {
+ const char *encodingName; /* The name of the encoding, e.g. "euc-jp".
+ * This name is the unique key for this
+ * encoding type. */
+ Tcl_EncodingConvertProc *toUtfProc;
+ /* Function to convert from external encoding
+ * into UTF-8. */
+ Tcl_EncodingConvertProc *fromUtfProc;
+ /* Function to convert from UTF-8 into
+ * external encoding. */
+ Tcl_EncodingFreeProc *freeProc;
+ /* If non-NULL, function to call when this
+ * encoding is deleted. */
+ ClientData clientData; /* Arbitrary value associated with encoding
+ * type. Passed to conversion functions. */
+ int nullSize; /* Number of zero bytes that signify
+ * end-of-string in this encoding. This number
+ * is used to determine the source string
+ * length when the srcLen argument is
+ * negative. Must be 1 or 2. */
+} Tcl_EncodingType;
+
+/*
+ * The following definitions are used as values for the conversion control
+ * flags argument when converting text from one character set to another:
+ *
+ * TCL_ENCODING_START - Signifies that the source buffer is the first
+ * block in a (potentially multi-block) input
+ * stream. Tells the conversion function to reset
+ * to an initial state and perform any
+ * initialization that needs to occur before the
+ * first byte is converted. If the source buffer
+ * contains the entire input stream to be
+ * converted, this flag should be set.
+ * TCL_ENCODING_END - Signifies that the source buffer is the last
+ * block in a (potentially multi-block) input
+ * stream. Tells the conversion routine to
+ * perform any finalization that needs to occur
+ * after the last byte is converted and then to
+ * reset to an initial state. If the source
+ * buffer contains the entire input stream to be
+ * converted, this flag should be set.
+ * TCL_ENCODING_STOPONERROR - If set, then the converter will return
+ * immediately upon encountering an invalid byte
+ * sequence or a source character that has no
+ * mapping in the target encoding. If clear, then
+ * the converter will skip the problem,
+ * substituting one or more "close" characters in
+ * the destination buffer and then continue to
+ * convert the source.
+ */
+
+#define TCL_ENCODING_START 0x01
+#define TCL_ENCODING_END 0x02
+#define TCL_ENCODING_STOPONERROR 0x04
+
+/*
+ * The following definitions are the error codes returned by the conversion
+ * routines:
+ *
+ * TCL_OK - All characters were converted.
+ * TCL_CONVERT_NOSPACE - The output buffer would not have been large
+ * enough for all of the converted data; as many
+ * characters as could fit were converted though.
+ * TCL_CONVERT_MULTIBYTE - The last few bytes in the source string were
+ * the beginning of a multibyte sequence, but
+ * more bytes were needed to complete this
+ * sequence. A subsequent call to the conversion
+ * routine should pass the beginning of this
+ * unconverted sequence plus additional bytes
+ * from the source stream to properly convert the
+ * formerly split-up multibyte sequence.
+ * TCL_CONVERT_SYNTAX - The source stream contained an invalid
+ * character sequence. This may occur if the
+ * input stream has been damaged or if the input
+ * encoding method was misidentified. This error
+ * is reported only if TCL_ENCODING_STOPONERROR
+ * was specified.
+ * TCL_CONVERT_UNKNOWN - The source string contained a character that
+ * could not be represented in the target
+ * encoding. This error is reported only if
+ * TCL_ENCODING_STOPONERROR was specified.
+ */
+
+#define TCL_CONVERT_MULTIBYTE (-1)
+#define TCL_CONVERT_SYNTAX (-2)
+#define TCL_CONVERT_UNKNOWN (-3)
+#define TCL_CONVERT_NOSPACE (-4)
+
+/*
+ * The maximum number of bytes that are necessary to represent a single
+ * Unicode character in UTF-8. The valid values should be 3, 4 or 6
+ * (or perhaps 1 if we want to support a non-unicode enabled core). If 3 or
+ * 4, then Tcl_UniChar must be 2-bytes in size (UCS-2) (the default). If 6,
+ * then Tcl_UniChar must be 4-bytes in size (UCS-4). At this time UCS-2 mode
+ * is the default and recommended mode. UCS-4 is experimental and not
+ * recommended. It works for the core, but most extensions expect UCS-2.
+ */
+
+#ifndef TCL_UTF_MAX
+#define TCL_UTF_MAX 3
+#endif
+
+/*
+ * This represents a Unicode character. Any changes to this should also be
+ * reflected in regcustom.h.
+ */
+
+#if TCL_UTF_MAX > 4
+ /*
+ * unsigned int isn't 100% accurate as it should be a strict 4-byte value
+ * (perhaps wchar_t). 64-bit systems may have troubles. The size of this
+ * value must be reflected correctly in regcustom.h and
+ * in tclEncoding.c.
+ * XXX: Tcl is currently UCS-2 and planning UTF-16 for the Unicode
+ * XXX: string rep that Tcl_UniChar represents. Changing the size
+ * XXX: of Tcl_UniChar is /not/ supported.
+ */
+typedef unsigned int Tcl_UniChar;
+#else
+typedef unsigned short Tcl_UniChar;
+#endif
+
+/*
+ *----------------------------------------------------------------------------
+ * TIP #59: The following structure is used in calls 'Tcl_RegisterConfig' to
+ * provide the system with the embedded configuration data.
+ */
+
+typedef struct Tcl_Config {
+ const char *key; /* Configuration key to register. ASCII
+ * encoded, thus UTF-8. */
+ const char *value; /* The value associated with the key. System
+ * encoding. */
+} Tcl_Config;
+
+/*
+ *----------------------------------------------------------------------------
+ * Flags for TIP#143 limits, detailing which limits are active in an
+ * interpreter. Used for Tcl_{Add,Remove}LimitHandler type argument.
+ */
+
+#define TCL_LIMIT_COMMANDS 0x01
+#define TCL_LIMIT_TIME 0x02
+
+/*
+ * Structure containing information about a limit handler to be called when a
+ * command- or time-limit is exceeded by an interpreter.
+ */
+
+typedef void (Tcl_LimitHandlerProc) (ClientData clientData, Tcl_Interp *interp);
+typedef void (Tcl_LimitHandlerDeleteProc) (ClientData clientData);
+
+/*
+ *----------------------------------------------------------------------------
+ * Override definitions for libtommath.
+ */
+
+typedef struct mp_int mp_int;
+#define MP_INT_DECLARED
+typedef unsigned int mp_digit;
+#define MP_DIGIT_DECLARED
+
+/*
+ *----------------------------------------------------------------------------
+ * Definitions needed for Tcl_ParseArgvObj routines.
+ * Based on tkArgv.c.
+ * Modifications from the original are copyright (c) Sam Bromley 2006
+ */
+
+typedef struct {
+ int type; /* Indicates the option type; see below. */
+ const char *keyStr; /* The key string that flags the option in the
+ * argv array. */
+ void *srcPtr; /* Value to be used in setting dst; usage
+ * depends on type.*/
+ void *dstPtr; /* Address of value to be modified; usage
+ * depends on type.*/
+ const char *helpStr; /* Documentation message describing this
+ * option. */
+ ClientData clientData; /* Word to pass to function callbacks. */
+} Tcl_ArgvInfo;
+
+/*
+ * Legal values for the type field of a Tcl_ArgInfo: see the user
+ * documentation for details.
+ */
+
+#define TCL_ARGV_CONSTANT 15
+#define TCL_ARGV_INT 16
+#define TCL_ARGV_STRING 17
+#define TCL_ARGV_REST 18
+#define TCL_ARGV_FLOAT 19
+#define TCL_ARGV_FUNC 20
+#define TCL_ARGV_GENFUNC 21
+#define TCL_ARGV_HELP 22
+#define TCL_ARGV_END 23
+
+/*
+ * Types of callback functions for the TCL_ARGV_FUNC and TCL_ARGV_GENFUNC
+ * argument types:
+ */
+
+typedef int (Tcl_ArgvFuncProc)(ClientData clientData, Tcl_Obj *objPtr,
+ void *dstPtr);
+typedef int (Tcl_ArgvGenFuncProc)(ClientData clientData, Tcl_Interp *interp,
+ int objc, Tcl_Obj *const *objv, void *dstPtr);
+
+/*
+ * Shorthand for commonly used argTable entries.
+ */
+
+#define TCL_ARGV_AUTO_HELP \
+ {TCL_ARGV_HELP, "-help", NULL, NULL, \
+ "Print summary of command-line options and abort", NULL}
+#define TCL_ARGV_AUTO_REST \
+ {TCL_ARGV_REST, "--", NULL, NULL, \
+ "Marks the end of the options", NULL}
+#define TCL_ARGV_TABLE_END \
+ {TCL_ARGV_END, NULL, NULL, NULL, NULL, NULL}
+
+/*
+ *----------------------------------------------------------------------------
+ * Definitions needed for Tcl_Zlib routines. [TIP #234]
+ *
+ * Constants for the format flags describing what sort of data format is
+ * desired/expected for the Tcl_ZlibDeflate, Tcl_ZlibInflate and
+ * Tcl_ZlibStreamInit functions.
+ */
+
+#define TCL_ZLIB_FORMAT_RAW 1
+#define TCL_ZLIB_FORMAT_ZLIB 2
+#define TCL_ZLIB_FORMAT_GZIP 4
+#define TCL_ZLIB_FORMAT_AUTO 8
+
+/*
+ * Constants that describe whether the stream is to operate in compressing or
+ * decompressing mode.
+ */
+
+#define TCL_ZLIB_STREAM_DEFLATE 16
+#define TCL_ZLIB_STREAM_INFLATE 32
+
+/*
+ * Constants giving compression levels. Use of TCL_ZLIB_COMPRESS_DEFAULT is
+ * recommended.
+ */
+
+#define TCL_ZLIB_COMPRESS_NONE 0
+#define TCL_ZLIB_COMPRESS_FAST 1
+#define TCL_ZLIB_COMPRESS_BEST 9
+#define TCL_ZLIB_COMPRESS_DEFAULT (-1)
+
+/*
+ * Constants for types of flushing, used with Tcl_ZlibFlush.
+ */
+
+#define TCL_ZLIB_NO_FLUSH 0
+#define TCL_ZLIB_FLUSH 2
+#define TCL_ZLIB_FULLFLUSH 3
+#define TCL_ZLIB_FINALIZE 4
+
+/*
+ *----------------------------------------------------------------------------
+ * Definitions needed for the Tcl_LoadFile function. [TIP #416]
+ */
+
+#define TCL_LOAD_GLOBAL 1
+#define TCL_LOAD_LAZY 2
+
+/*
+ *----------------------------------------------------------------------------
+ * Single public declaration for NRE.
+ */
+
+typedef int (Tcl_NRPostProc) (ClientData data[], Tcl_Interp *interp,
+ int result);
+
+/*
+ *----------------------------------------------------------------------------
+ * The following constant is used to test for older versions of Tcl in the
+ * stubs tables.
+ *
+ * Jan Nijtman's plus patch uses 0xFCA1BACF, so we need to pick a different
+ * value since the stubs tables don't match.
+ */
+
+#define TCL_STUB_MAGIC ((int) 0xFCA3BACF)
+
+/*
+ * The following function is required to be defined in all stubs aware
+ * extensions. The function is actually implemented in the stub library, not
+ * the main Tcl library, although there is a trivial implementation in the
+ * main library in case an extension is statically linked into an application.
+ */
+
+const char * Tcl_InitStubs(Tcl_Interp *interp, const char *version,
+ int exact);
+const char * TclTomMathInitializeStubs(Tcl_Interp *interp,
+ const char *version, int epoch, int revision);
+
+/*
+ * When not using stubs, make it a macro.
+ */
+
+#ifndef USE_TCL_STUBS
+#define Tcl_InitStubs(interp, version, exact) \
+ Tcl_PkgInitStubsCheck(interp, version, exact)
+#endif
+
+/*
+ * TODO - tommath stubs export goes here!
+ */
+
+/*
+ * Public functions that are not accessible via the stubs table.
+ * Tcl_GetMemoryInfo is needed for AOLserver. [Bug 1868171]
+ */
+
+#define Tcl_Main(argc, argv, proc) Tcl_MainEx(argc, argv, proc, \
+ (Tcl_FindExecutable(argv[0]), (Tcl_CreateInterp)()))
+EXTERN void Tcl_MainEx(int argc, char **argv,
+ Tcl_AppInitProc *appInitProc, Tcl_Interp *interp);
+EXTERN const char * Tcl_PkgInitStubsCheck(Tcl_Interp *interp,
+ const char *version, int exact);
+#if defined(TCL_THREADS) && defined(USE_THREAD_ALLOC)
+EXTERN void Tcl_GetMemoryInfo(Tcl_DString *dsPtr);
+#endif
+
+/*
+ *----------------------------------------------------------------------------
+ * Include the public function declarations that are accessible via the stubs
+ * table.
+ */
+
+#include "tclDecls.h"
+
+/*
+ * Include platform specific public function declarations that are accessible
+ * via the stubs table.
+ */
+
+#include "tclPlatDecls.h"
+
+/*
+ *----------------------------------------------------------------------------
+ * The following declarations either map ckalloc and ckfree to malloc and
+ * free, or they map them to functions with all sorts of debugging hooks
+ * defined in tclCkalloc.c.
+ */
+
+#ifdef TCL_MEM_DEBUG
+
+# define ckalloc(x) \
+ ((VOID *) Tcl_DbCkalloc((unsigned)(x), __FILE__, __LINE__))
+# define ckfree(x) \
+ Tcl_DbCkfree((char *)(x), __FILE__, __LINE__)
+# define ckrealloc(x,y) \
+ ((VOID *) Tcl_DbCkrealloc((char *)(x), (unsigned)(y), __FILE__, __LINE__))
+# define attemptckalloc(x) \
+ ((VOID *) Tcl_AttemptDbCkalloc((unsigned)(x), __FILE__, __LINE__))
+# define attemptckrealloc(x,y) \
+ ((VOID *) Tcl_AttemptDbCkrealloc((char *)(x), (unsigned)(y), __FILE__, __LINE__))
+
+#else /* !TCL_MEM_DEBUG */
+
+/*
+ * If we are not using the debugging allocator, we should call the Tcl_Alloc,
+ * et al. routines in order to guarantee that every module is using the same
+ * memory allocator both inside and outside of the Tcl library.
+ */
+
+# define ckalloc(x) \
+ ((VOID *) Tcl_Alloc((unsigned)(x)))
+# define ckfree(x) \
+ Tcl_Free((char *)(x))
+# define ckrealloc(x,y) \
+ ((VOID *) Tcl_Realloc((char *)(x), (unsigned)(y)))
+# define attemptckalloc(x) \
+ ((VOID *) Tcl_AttemptAlloc((unsigned)(x)))
+# define attemptckrealloc(x,y) \
+ ((VOID *) Tcl_AttemptRealloc((char *)(x), (unsigned)(y)))
+# undef Tcl_InitMemory
+# define Tcl_InitMemory(x)
+# undef Tcl_DumpActiveMemory
+# define Tcl_DumpActiveMemory(x)
+# undef Tcl_ValidateAllMemory
+# define Tcl_ValidateAllMemory(x,y)
+
+#endif /* !TCL_MEM_DEBUG */
+
+#ifdef TCL_MEM_DEBUG
+# define Tcl_IncrRefCount(objPtr) \
+ Tcl_DbIncrRefCount(objPtr, __FILE__, __LINE__)
+# define Tcl_DecrRefCount(objPtr) \
+ Tcl_DbDecrRefCount(objPtr, __FILE__, __LINE__)
+# define Tcl_IsShared(objPtr) \
+ Tcl_DbIsShared(objPtr, __FILE__, __LINE__)
+#else
+# define Tcl_IncrRefCount(objPtr) \
+ ++(objPtr)->refCount
+ /*
+ * Use do/while0 idiom for optimum correctness without compiler warnings.
+ * http://c2.com/cgi/wiki?TrivialDoWhileLoop
+ */
+# define Tcl_DecrRefCount(objPtr) \
+ do { \
+ Tcl_Obj *_objPtr = (objPtr); \
+ if (--(_objPtr)->refCount <= 0) { \
+ TclFreeObj(_objPtr); \
+ } \
+ } while(0)
+# define Tcl_IsShared(objPtr) \
+ ((objPtr)->refCount > 1)
+#endif
+
+/*
+ * Macros and definitions that help to debug the use of Tcl objects. When
+ * TCL_MEM_DEBUG is defined, the Tcl_New declarations are overridden to call
+ * debugging versions of the object creation functions.
+ */
+
+#ifdef TCL_MEM_DEBUG
+# undef Tcl_NewBignumObj
+# define Tcl_NewBignumObj(val) \
+ Tcl_DbNewBignumObj(val, __FILE__, __LINE__)
+# undef Tcl_NewBooleanObj
+# define Tcl_NewBooleanObj(val) \
+ Tcl_DbNewBooleanObj(val, __FILE__, __LINE__)
+# undef Tcl_NewByteArrayObj
+# define Tcl_NewByteArrayObj(bytes, len) \
+ Tcl_DbNewByteArrayObj(bytes, len, __FILE__, __LINE__)
+# undef Tcl_NewDoubleObj
+# define Tcl_NewDoubleObj(val) \
+ Tcl_DbNewDoubleObj(val, __FILE__, __LINE__)
+# undef Tcl_NewIntObj
+# define Tcl_NewIntObj(val) \
+ Tcl_DbNewLongObj(val, __FILE__, __LINE__)
+# undef Tcl_NewListObj
+# define Tcl_NewListObj(objc, objv) \
+ Tcl_DbNewListObj(objc, objv, __FILE__, __LINE__)
+# undef Tcl_NewLongObj
+# define Tcl_NewLongObj(val) \
+ Tcl_DbNewLongObj(val, __FILE__, __LINE__)
+# undef Tcl_NewObj
+# define Tcl_NewObj() \
+ Tcl_DbNewObj(__FILE__, __LINE__)
+# undef Tcl_NewStringObj
+# define Tcl_NewStringObj(bytes, len) \
+ Tcl_DbNewStringObj(bytes, len, __FILE__, __LINE__)
+# undef Tcl_NewWideIntObj
+# define Tcl_NewWideIntObj(val) \
+ Tcl_DbNewWideIntObj(val, __FILE__, __LINE__)
+#endif /* TCL_MEM_DEBUG */
+
+/*
+ *----------------------------------------------------------------------------
+ * Macros for clients to use to access fields of hash entries:
+ */
+
+#define Tcl_GetHashValue(h) ((h)->clientData)
+#define Tcl_SetHashValue(h, value) ((h)->clientData = (ClientData) (value))
+#define Tcl_GetHashKey(tablePtr, h) \
+ ((void *) (((tablePtr)->keyType == TCL_ONE_WORD_KEYS || \
+ (tablePtr)->keyType == TCL_CUSTOM_PTR_KEYS) \
+ ? (h)->key.oneWordValue \
+ : (h)->key.string))
+
+/*
+ * Macros to use for clients to use to invoke find and create functions for
+ * hash tables:
+ */
+
+#undef Tcl_FindHashEntry
+#define Tcl_FindHashEntry(tablePtr, key) \
+ (*((tablePtr)->findProc))(tablePtr, (const char *)(key))
+#undef Tcl_CreateHashEntry
+#define Tcl_CreateHashEntry(tablePtr, key, newPtr) \
+ (*((tablePtr)->createProc))(tablePtr, (const char *)(key), newPtr)
+
+/*
+ *----------------------------------------------------------------------------
+ * Macros that eliminate the overhead of the thread synchronization functions
+ * when compiling without thread support.
+ */
+
+#ifndef TCL_THREADS
+#undef Tcl_MutexLock
+#define Tcl_MutexLock(mutexPtr)
+#undef Tcl_MutexUnlock
+#define Tcl_MutexUnlock(mutexPtr)
+#undef Tcl_MutexFinalize
+#define Tcl_MutexFinalize(mutexPtr)
+#undef Tcl_ConditionNotify
+#define Tcl_ConditionNotify(condPtr)
+#undef Tcl_ConditionWait
+#define Tcl_ConditionWait(condPtr, mutexPtr, timePtr)
+#undef Tcl_ConditionFinalize
+#define Tcl_ConditionFinalize(condPtr)
+#endif /* TCL_THREADS */
+
+/*
+ *----------------------------------------------------------------------------
+ * Deprecated Tcl functions:
+ */
+
+#ifndef TCL_NO_DEPRECATED
+# undef Tcl_EvalObj
+# define Tcl_EvalObj(interp,objPtr) \
+ Tcl_EvalObjEx((interp),(objPtr),0)
+# undef Tcl_GlobalEvalObj
+# define Tcl_GlobalEvalObj(interp,objPtr) \
+ Tcl_EvalObjEx((interp),(objPtr),TCL_EVAL_GLOBAL)
+
+/*
+ * These function have been renamed. The old names are deprecated, but we
+ * define these macros for backwards compatibilty.
+ */
+
+# define Tcl_Ckalloc Tcl_Alloc
+# define Tcl_Ckfree Tcl_Free
+# define Tcl_Ckrealloc Tcl_Realloc
+# define Tcl_Return Tcl_SetResult
+# define Tcl_TildeSubst Tcl_TranslateFileName
+# define panic Tcl_Panic
+# define panicVA Tcl_PanicVA
+#endif /* !TCL_NO_DEPRECATED */
+
+/*
+ *----------------------------------------------------------------------------
+ * Convenience declaration of Tcl_AppInit for backwards compatibility. This
+ * function is not *implemented* by the tcl library, so the storage class is
+ * neither DLLEXPORT nor DLLIMPORT.
+ */
+
+extern Tcl_AppInitProc Tcl_AppInit;
+
+#endif /* RC_INVOKED */
+
+/*
+ * end block for C++
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TCL */
+
+/*
+ * Local Variables:
+ * mode: c
+ * c-basic-offset: 4
+ * fill-column: 78
+ * End:
+ */
ADDED compat/tcl-8.6/generic/tclDecls.h
Index: compat/tcl-8.6/generic/tclDecls.h
==================================================================
--- compat/tcl-8.6/generic/tclDecls.h
+++ compat/tcl-8.6/generic/tclDecls.h
@@ -0,0 +1,3806 @@
+/*
+ * tclDecls.h --
+ *
+ * Declarations of functions in the platform independent public Tcl API.
+ *
+ * Copyright (c) 1998-1999 by Scriptics Corporation.
+ *
+ * See the file "license.terms" for information on usage and redistribution
+ * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+ */
+
+#ifndef _TCLDECLS
+#define _TCLDECLS
+
+#undef TCL_STORAGE_CLASS
+#ifdef BUILD_tcl
+# define TCL_STORAGE_CLASS DLLEXPORT
+#else
+# ifdef USE_TCL_STUBS
+# define TCL_STORAGE_CLASS
+# else
+# define TCL_STORAGE_CLASS DLLIMPORT
+# endif
+#endif
+
+/*
+ * WARNING: This file is automatically generated by the tools/genStubs.tcl
+ * script. Any modifications to the function declarations below should be made
+ * in the generic/tcl.decls script.
+ */
+
+/* !BEGIN!: Do not edit below this line. */
+
+/*
+ * Exported function declarations:
+ */
+
+/* 0 */
+EXTERN int Tcl_PkgProvideEx(Tcl_Interp *interp,
+ const char *name, const char *version,
+ const void *clientData);
+/* 1 */
+EXTERN CONST84_RETURN char * Tcl_PkgRequireEx(Tcl_Interp *interp,
+ const char *name, const char *version,
+ int exact, void *clientDataPtr);
+/* 2 */
+EXTERN void Tcl_Panic(const char *format, ...) TCL_FORMAT_PRINTF(1, 2);
+/* 3 */
+EXTERN char * Tcl_Alloc(unsigned int size);
+/* 4 */
+EXTERN void Tcl_Free(char *ptr);
+/* 5 */
+EXTERN char * Tcl_Realloc(char *ptr, unsigned int size);
+/* 6 */
+EXTERN char * Tcl_DbCkalloc(unsigned int size, const char *file,
+ int line);
+/* 7 */
+EXTERN void Tcl_DbCkfree(char *ptr, const char *file, int line);
+/* 8 */
+EXTERN char * Tcl_DbCkrealloc(char *ptr, unsigned int size,
+ const char *file, int line);
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+/* 9 */
+EXTERN void Tcl_CreateFileHandler(int fd, int mask,
+ Tcl_FileProc *proc, ClientData clientData);
+#endif /* UNIX */
+#ifdef MAC_OSX_TCL /* MACOSX */
+/* 9 */
+EXTERN void Tcl_CreateFileHandler(int fd, int mask,
+ Tcl_FileProc *proc, ClientData clientData);
+#endif /* MACOSX */
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+/* 10 */
+EXTERN void Tcl_DeleteFileHandler(int fd);
+#endif /* UNIX */
+#ifdef MAC_OSX_TCL /* MACOSX */
+/* 10 */
+EXTERN void Tcl_DeleteFileHandler(int fd);
+#endif /* MACOSX */
+/* 11 */
+EXTERN void Tcl_SetTimer(const Tcl_Time *timePtr);
+/* 12 */
+EXTERN void Tcl_Sleep(int ms);
+/* 13 */
+EXTERN int Tcl_WaitForEvent(const Tcl_Time *timePtr);
+/* 14 */
+EXTERN int Tcl_AppendAllObjTypes(Tcl_Interp *interp,
+ Tcl_Obj *objPtr);
+/* 15 */
+EXTERN void Tcl_AppendStringsToObj(Tcl_Obj *objPtr, ...);
+/* 16 */
+EXTERN void Tcl_AppendToObj(Tcl_Obj *objPtr, const char *bytes,
+ int length);
+/* 17 */
+EXTERN Tcl_Obj * Tcl_ConcatObj(int objc, Tcl_Obj *const objv[]);
+/* 18 */
+EXTERN int Tcl_ConvertToType(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, const Tcl_ObjType *typePtr);
+/* 19 */
+EXTERN void Tcl_DbDecrRefCount(Tcl_Obj *objPtr, const char *file,
+ int line);
+/* 20 */
+EXTERN void Tcl_DbIncrRefCount(Tcl_Obj *objPtr, const char *file,
+ int line);
+/* 21 */
+EXTERN int Tcl_DbIsShared(Tcl_Obj *objPtr, const char *file,
+ int line);
+/* 22 */
+EXTERN Tcl_Obj * Tcl_DbNewBooleanObj(int boolValue, const char *file,
+ int line);
+/* 23 */
+EXTERN Tcl_Obj * Tcl_DbNewByteArrayObj(const unsigned char *bytes,
+ int length, const char *file, int line);
+/* 24 */
+EXTERN Tcl_Obj * Tcl_DbNewDoubleObj(double doubleValue,
+ const char *file, int line);
+/* 25 */
+EXTERN Tcl_Obj * Tcl_DbNewListObj(int objc, Tcl_Obj *const *objv,
+ const char *file, int line);
+/* 26 */
+EXTERN Tcl_Obj * Tcl_DbNewLongObj(long longValue, const char *file,
+ int line);
+/* 27 */
+EXTERN Tcl_Obj * Tcl_DbNewObj(const char *file, int line);
+/* 28 */
+EXTERN Tcl_Obj * Tcl_DbNewStringObj(const char *bytes, int length,
+ const char *file, int line);
+/* 29 */
+EXTERN Tcl_Obj * Tcl_DuplicateObj(Tcl_Obj *objPtr);
+/* 30 */
+EXTERN void TclFreeObj(Tcl_Obj *objPtr);
+/* 31 */
+EXTERN int Tcl_GetBoolean(Tcl_Interp *interp, const char *src,
+ int *boolPtr);
+/* 32 */
+EXTERN int Tcl_GetBooleanFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, int *boolPtr);
+/* 33 */
+EXTERN unsigned char * Tcl_GetByteArrayFromObj(Tcl_Obj *objPtr,
+ int *lengthPtr);
+/* 34 */
+EXTERN int Tcl_GetDouble(Tcl_Interp *interp, const char *src,
+ double *doublePtr);
+/* 35 */
+EXTERN int Tcl_GetDoubleFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, double *doublePtr);
+/* 36 */
+EXTERN int Tcl_GetIndexFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr,
+ CONST84 char *const *tablePtr,
+ const char *msg, int flags, int *indexPtr);
+/* 37 */
+EXTERN int Tcl_GetInt(Tcl_Interp *interp, const char *src,
+ int *intPtr);
+/* 38 */
+EXTERN int Tcl_GetIntFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, int *intPtr);
+/* 39 */
+EXTERN int Tcl_GetLongFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, long *longPtr);
+/* 40 */
+EXTERN CONST86 Tcl_ObjType * Tcl_GetObjType(const char *typeName);
+/* 41 */
+EXTERN char * Tcl_GetStringFromObj(Tcl_Obj *objPtr, int *lengthPtr);
+/* 42 */
+EXTERN void Tcl_InvalidateStringRep(Tcl_Obj *objPtr);
+/* 43 */
+EXTERN int Tcl_ListObjAppendList(Tcl_Interp *interp,
+ Tcl_Obj *listPtr, Tcl_Obj *elemListPtr);
+/* 44 */
+EXTERN int Tcl_ListObjAppendElement(Tcl_Interp *interp,
+ Tcl_Obj *listPtr, Tcl_Obj *objPtr);
+/* 45 */
+EXTERN int Tcl_ListObjGetElements(Tcl_Interp *interp,
+ Tcl_Obj *listPtr, int *objcPtr,
+ Tcl_Obj ***objvPtr);
+/* 46 */
+EXTERN int Tcl_ListObjIndex(Tcl_Interp *interp,
+ Tcl_Obj *listPtr, int index,
+ Tcl_Obj **objPtrPtr);
+/* 47 */
+EXTERN int Tcl_ListObjLength(Tcl_Interp *interp,
+ Tcl_Obj *listPtr, int *lengthPtr);
+/* 48 */
+EXTERN int Tcl_ListObjReplace(Tcl_Interp *interp,
+ Tcl_Obj *listPtr, int first, int count,
+ int objc, Tcl_Obj *const objv[]);
+/* 49 */
+EXTERN Tcl_Obj * Tcl_NewBooleanObj(int boolValue);
+/* 50 */
+EXTERN Tcl_Obj * Tcl_NewByteArrayObj(const unsigned char *bytes,
+ int length);
+/* 51 */
+EXTERN Tcl_Obj * Tcl_NewDoubleObj(double doubleValue);
+/* 52 */
+EXTERN Tcl_Obj * Tcl_NewIntObj(int intValue);
+/* 53 */
+EXTERN Tcl_Obj * Tcl_NewListObj(int objc, Tcl_Obj *const objv[]);
+/* 54 */
+EXTERN Tcl_Obj * Tcl_NewLongObj(long longValue);
+/* 55 */
+EXTERN Tcl_Obj * Tcl_NewObj(void);
+/* 56 */
+EXTERN Tcl_Obj * Tcl_NewStringObj(const char *bytes, int length);
+/* 57 */
+EXTERN void Tcl_SetBooleanObj(Tcl_Obj *objPtr, int boolValue);
+/* 58 */
+EXTERN unsigned char * Tcl_SetByteArrayLength(Tcl_Obj *objPtr, int length);
+/* 59 */
+EXTERN void Tcl_SetByteArrayObj(Tcl_Obj *objPtr,
+ const unsigned char *bytes, int length);
+/* 60 */
+EXTERN void Tcl_SetDoubleObj(Tcl_Obj *objPtr, double doubleValue);
+/* 61 */
+EXTERN void Tcl_SetIntObj(Tcl_Obj *objPtr, int intValue);
+/* 62 */
+EXTERN void Tcl_SetListObj(Tcl_Obj *objPtr, int objc,
+ Tcl_Obj *const objv[]);
+/* 63 */
+EXTERN void Tcl_SetLongObj(Tcl_Obj *objPtr, long longValue);
+/* 64 */
+EXTERN void Tcl_SetObjLength(Tcl_Obj *objPtr, int length);
+/* 65 */
+EXTERN void Tcl_SetStringObj(Tcl_Obj *objPtr, const char *bytes,
+ int length);
+/* 66 */
+EXTERN void Tcl_AddErrorInfo(Tcl_Interp *interp,
+ const char *message);
+/* 67 */
+EXTERN void Tcl_AddObjErrorInfo(Tcl_Interp *interp,
+ const char *message, int length);
+/* 68 */
+EXTERN void Tcl_AllowExceptions(Tcl_Interp *interp);
+/* 69 */
+EXTERN void Tcl_AppendElement(Tcl_Interp *interp,
+ const char *element);
+/* 70 */
+EXTERN void Tcl_AppendResult(Tcl_Interp *interp, ...);
+/* 71 */
+EXTERN Tcl_AsyncHandler Tcl_AsyncCreate(Tcl_AsyncProc *proc,
+ ClientData clientData);
+/* 72 */
+EXTERN void Tcl_AsyncDelete(Tcl_AsyncHandler async);
+/* 73 */
+EXTERN int Tcl_AsyncInvoke(Tcl_Interp *interp, int code);
+/* 74 */
+EXTERN void Tcl_AsyncMark(Tcl_AsyncHandler async);
+/* 75 */
+EXTERN int Tcl_AsyncReady(void);
+/* 76 */
+EXTERN void Tcl_BackgroundError(Tcl_Interp *interp);
+/* 77 */
+EXTERN char Tcl_Backslash(const char *src, int *readPtr);
+/* 78 */
+EXTERN int Tcl_BadChannelOption(Tcl_Interp *interp,
+ const char *optionName,
+ const char *optionList);
+/* 79 */
+EXTERN void Tcl_CallWhenDeleted(Tcl_Interp *interp,
+ Tcl_InterpDeleteProc *proc,
+ ClientData clientData);
+/* 80 */
+EXTERN void Tcl_CancelIdleCall(Tcl_IdleProc *idleProc,
+ ClientData clientData);
+/* 81 */
+EXTERN int Tcl_Close(Tcl_Interp *interp, Tcl_Channel chan);
+/* 82 */
+EXTERN int Tcl_CommandComplete(const char *cmd);
+/* 83 */
+EXTERN char * Tcl_Concat(int argc, CONST84 char *const *argv);
+/* 84 */
+EXTERN int Tcl_ConvertElement(const char *src, char *dst,
+ int flags);
+/* 85 */
+EXTERN int Tcl_ConvertCountedElement(const char *src,
+ int length, char *dst, int flags);
+/* 86 */
+EXTERN int Tcl_CreateAlias(Tcl_Interp *slave,
+ const char *slaveCmd, Tcl_Interp *target,
+ const char *targetCmd, int argc,
+ CONST84 char *const *argv);
+/* 87 */
+EXTERN int Tcl_CreateAliasObj(Tcl_Interp *slave,
+ const char *slaveCmd, Tcl_Interp *target,
+ const char *targetCmd, int objc,
+ Tcl_Obj *const objv[]);
+/* 88 */
+EXTERN Tcl_Channel Tcl_CreateChannel(const Tcl_ChannelType *typePtr,
+ const char *chanName,
+ ClientData instanceData, int mask);
+/* 89 */
+EXTERN void Tcl_CreateChannelHandler(Tcl_Channel chan, int mask,
+ Tcl_ChannelProc *proc, ClientData clientData);
+/* 90 */
+EXTERN void Tcl_CreateCloseHandler(Tcl_Channel chan,
+ Tcl_CloseProc *proc, ClientData clientData);
+/* 91 */
+EXTERN Tcl_Command Tcl_CreateCommand(Tcl_Interp *interp,
+ const char *cmdName, Tcl_CmdProc *proc,
+ ClientData clientData,
+ Tcl_CmdDeleteProc *deleteProc);
+/* 92 */
+EXTERN void Tcl_CreateEventSource(Tcl_EventSetupProc *setupProc,
+ Tcl_EventCheckProc *checkProc,
+ ClientData clientData);
+/* 93 */
+EXTERN void Tcl_CreateExitHandler(Tcl_ExitProc *proc,
+ ClientData clientData);
+/* 94 */
+EXTERN Tcl_Interp * Tcl_CreateInterp(void);
+/* 95 */
+EXTERN void Tcl_CreateMathFunc(Tcl_Interp *interp,
+ const char *name, int numArgs,
+ Tcl_ValueType *argTypes, Tcl_MathProc *proc,
+ ClientData clientData);
+/* 96 */
+EXTERN Tcl_Command Tcl_CreateObjCommand(Tcl_Interp *interp,
+ const char *cmdName, Tcl_ObjCmdProc *proc,
+ ClientData clientData,
+ Tcl_CmdDeleteProc *deleteProc);
+/* 97 */
+EXTERN Tcl_Interp * Tcl_CreateSlave(Tcl_Interp *interp,
+ const char *slaveName, int isSafe);
+/* 98 */
+EXTERN Tcl_TimerToken Tcl_CreateTimerHandler(int milliseconds,
+ Tcl_TimerProc *proc, ClientData clientData);
+/* 99 */
+EXTERN Tcl_Trace Tcl_CreateTrace(Tcl_Interp *interp, int level,
+ Tcl_CmdTraceProc *proc,
+ ClientData clientData);
+/* 100 */
+EXTERN void Tcl_DeleteAssocData(Tcl_Interp *interp,
+ const char *name);
+/* 101 */
+EXTERN void Tcl_DeleteChannelHandler(Tcl_Channel chan,
+ Tcl_ChannelProc *proc, ClientData clientData);
+/* 102 */
+EXTERN void Tcl_DeleteCloseHandler(Tcl_Channel chan,
+ Tcl_CloseProc *proc, ClientData clientData);
+/* 103 */
+EXTERN int Tcl_DeleteCommand(Tcl_Interp *interp,
+ const char *cmdName);
+/* 104 */
+EXTERN int Tcl_DeleteCommandFromToken(Tcl_Interp *interp,
+ Tcl_Command command);
+/* 105 */
+EXTERN void Tcl_DeleteEvents(Tcl_EventDeleteProc *proc,
+ ClientData clientData);
+/* 106 */
+EXTERN void Tcl_DeleteEventSource(Tcl_EventSetupProc *setupProc,
+ Tcl_EventCheckProc *checkProc,
+ ClientData clientData);
+/* 107 */
+EXTERN void Tcl_DeleteExitHandler(Tcl_ExitProc *proc,
+ ClientData clientData);
+/* 108 */
+EXTERN void Tcl_DeleteHashEntry(Tcl_HashEntry *entryPtr);
+/* 109 */
+EXTERN void Tcl_DeleteHashTable(Tcl_HashTable *tablePtr);
+/* 110 */
+EXTERN void Tcl_DeleteInterp(Tcl_Interp *interp);
+/* 111 */
+EXTERN void Tcl_DetachPids(int numPids, Tcl_Pid *pidPtr);
+/* 112 */
+EXTERN void Tcl_DeleteTimerHandler(Tcl_TimerToken token);
+/* 113 */
+EXTERN void Tcl_DeleteTrace(Tcl_Interp *interp, Tcl_Trace trace);
+/* 114 */
+EXTERN void Tcl_DontCallWhenDeleted(Tcl_Interp *interp,
+ Tcl_InterpDeleteProc *proc,
+ ClientData clientData);
+/* 115 */
+EXTERN int Tcl_DoOneEvent(int flags);
+/* 116 */
+EXTERN void Tcl_DoWhenIdle(Tcl_IdleProc *proc,
+ ClientData clientData);
+/* 117 */
+EXTERN char * Tcl_DStringAppend(Tcl_DString *dsPtr,
+ const char *bytes, int length);
+/* 118 */
+EXTERN char * Tcl_DStringAppendElement(Tcl_DString *dsPtr,
+ const char *element);
+/* 119 */
+EXTERN void Tcl_DStringEndSublist(Tcl_DString *dsPtr);
+/* 120 */
+EXTERN void Tcl_DStringFree(Tcl_DString *dsPtr);
+/* 121 */
+EXTERN void Tcl_DStringGetResult(Tcl_Interp *interp,
+ Tcl_DString *dsPtr);
+/* 122 */
+EXTERN void Tcl_DStringInit(Tcl_DString *dsPtr);
+/* 123 */
+EXTERN void Tcl_DStringResult(Tcl_Interp *interp,
+ Tcl_DString *dsPtr);
+/* 124 */
+EXTERN void Tcl_DStringSetLength(Tcl_DString *dsPtr, int length);
+/* 125 */
+EXTERN void Tcl_DStringStartSublist(Tcl_DString *dsPtr);
+/* 126 */
+EXTERN int Tcl_Eof(Tcl_Channel chan);
+/* 127 */
+EXTERN CONST84_RETURN char * Tcl_ErrnoId(void);
+/* 128 */
+EXTERN CONST84_RETURN char * Tcl_ErrnoMsg(int err);
+/* 129 */
+EXTERN int Tcl_Eval(Tcl_Interp *interp, const char *script);
+/* 130 */
+EXTERN int Tcl_EvalFile(Tcl_Interp *interp,
+ const char *fileName);
+/* 131 */
+EXTERN int Tcl_EvalObj(Tcl_Interp *interp, Tcl_Obj *objPtr);
+/* 132 */
+EXTERN void Tcl_EventuallyFree(ClientData clientData,
+ Tcl_FreeProc *freeProc);
+/* 133 */
+EXTERN void Tcl_Exit(int status);
+/* 134 */
+EXTERN int Tcl_ExposeCommand(Tcl_Interp *interp,
+ const char *hiddenCmdToken,
+ const char *cmdName);
+/* 135 */
+EXTERN int Tcl_ExprBoolean(Tcl_Interp *interp, const char *expr,
+ int *ptr);
+/* 136 */
+EXTERN int Tcl_ExprBooleanObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, int *ptr);
+/* 137 */
+EXTERN int Tcl_ExprDouble(Tcl_Interp *interp, const char *expr,
+ double *ptr);
+/* 138 */
+EXTERN int Tcl_ExprDoubleObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, double *ptr);
+/* 139 */
+EXTERN int Tcl_ExprLong(Tcl_Interp *interp, const char *expr,
+ long *ptr);
+/* 140 */
+EXTERN int Tcl_ExprLongObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
+ long *ptr);
+/* 141 */
+EXTERN int Tcl_ExprObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
+ Tcl_Obj **resultPtrPtr);
+/* 142 */
+EXTERN int Tcl_ExprString(Tcl_Interp *interp, const char *expr);
+/* 143 */
+EXTERN void Tcl_Finalize(void);
+/* 144 */
+EXTERN void Tcl_FindExecutable(const char *argv0);
+/* 145 */
+EXTERN Tcl_HashEntry * Tcl_FirstHashEntry(Tcl_HashTable *tablePtr,
+ Tcl_HashSearch *searchPtr);
+/* 146 */
+EXTERN int Tcl_Flush(Tcl_Channel chan);
+/* 147 */
+EXTERN void Tcl_FreeResult(Tcl_Interp *interp);
+/* 148 */
+EXTERN int Tcl_GetAlias(Tcl_Interp *interp,
+ const char *slaveCmd,
+ Tcl_Interp **targetInterpPtr,
+ CONST84 char **targetCmdPtr, int *argcPtr,
+ CONST84 char ***argvPtr);
+/* 149 */
+EXTERN int Tcl_GetAliasObj(Tcl_Interp *interp,
+ const char *slaveCmd,
+ Tcl_Interp **targetInterpPtr,
+ CONST84 char **targetCmdPtr, int *objcPtr,
+ Tcl_Obj ***objv);
+/* 150 */
+EXTERN ClientData Tcl_GetAssocData(Tcl_Interp *interp,
+ const char *name,
+ Tcl_InterpDeleteProc **procPtr);
+/* 151 */
+EXTERN Tcl_Channel Tcl_GetChannel(Tcl_Interp *interp,
+ const char *chanName, int *modePtr);
+/* 152 */
+EXTERN int Tcl_GetChannelBufferSize(Tcl_Channel chan);
+/* 153 */
+EXTERN int Tcl_GetChannelHandle(Tcl_Channel chan, int direction,
+ ClientData *handlePtr);
+/* 154 */
+EXTERN ClientData Tcl_GetChannelInstanceData(Tcl_Channel chan);
+/* 155 */
+EXTERN int Tcl_GetChannelMode(Tcl_Channel chan);
+/* 156 */
+EXTERN CONST84_RETURN char * Tcl_GetChannelName(Tcl_Channel chan);
+/* 157 */
+EXTERN int Tcl_GetChannelOption(Tcl_Interp *interp,
+ Tcl_Channel chan, const char *optionName,
+ Tcl_DString *dsPtr);
+/* 158 */
+EXTERN CONST86 Tcl_ChannelType * Tcl_GetChannelType(Tcl_Channel chan);
+/* 159 */
+EXTERN int Tcl_GetCommandInfo(Tcl_Interp *interp,
+ const char *cmdName, Tcl_CmdInfo *infoPtr);
+/* 160 */
+EXTERN CONST84_RETURN char * Tcl_GetCommandName(Tcl_Interp *interp,
+ Tcl_Command command);
+/* 161 */
+EXTERN int Tcl_GetErrno(void);
+/* 162 */
+EXTERN CONST84_RETURN char * Tcl_GetHostName(void);
+/* 163 */
+EXTERN int Tcl_GetInterpPath(Tcl_Interp *askInterp,
+ Tcl_Interp *slaveInterp);
+/* 164 */
+EXTERN Tcl_Interp * Tcl_GetMaster(Tcl_Interp *interp);
+/* 165 */
+EXTERN const char * Tcl_GetNameOfExecutable(void);
+/* 166 */
+EXTERN Tcl_Obj * Tcl_GetObjResult(Tcl_Interp *interp);
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+/* 167 */
+EXTERN int Tcl_GetOpenFile(Tcl_Interp *interp,
+ const char *chanID, int forWriting,
+ int checkUsage, ClientData *filePtr);
+#endif /* UNIX */
+#ifdef MAC_OSX_TCL /* MACOSX */
+/* 167 */
+EXTERN int Tcl_GetOpenFile(Tcl_Interp *interp,
+ const char *chanID, int forWriting,
+ int checkUsage, ClientData *filePtr);
+#endif /* MACOSX */
+/* 168 */
+EXTERN Tcl_PathType Tcl_GetPathType(const char *path);
+/* 169 */
+EXTERN int Tcl_Gets(Tcl_Channel chan, Tcl_DString *dsPtr);
+/* 170 */
+EXTERN int Tcl_GetsObj(Tcl_Channel chan, Tcl_Obj *objPtr);
+/* 171 */
+EXTERN int Tcl_GetServiceMode(void);
+/* 172 */
+EXTERN Tcl_Interp * Tcl_GetSlave(Tcl_Interp *interp,
+ const char *slaveName);
+/* 173 */
+EXTERN Tcl_Channel Tcl_GetStdChannel(int type);
+/* 174 */
+EXTERN CONST84_RETURN char * Tcl_GetStringResult(Tcl_Interp *interp);
+/* 175 */
+EXTERN CONST84_RETURN char * Tcl_GetVar(Tcl_Interp *interp,
+ const char *varName, int flags);
+/* 176 */
+EXTERN CONST84_RETURN char * Tcl_GetVar2(Tcl_Interp *interp,
+ const char *part1, const char *part2,
+ int flags);
+/* 177 */
+EXTERN int Tcl_GlobalEval(Tcl_Interp *interp,
+ const char *command);
+/* 178 */
+EXTERN int Tcl_GlobalEvalObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr);
+/* 179 */
+EXTERN int Tcl_HideCommand(Tcl_Interp *interp,
+ const char *cmdName,
+ const char *hiddenCmdToken);
+/* 180 */
+EXTERN int Tcl_Init(Tcl_Interp *interp);
+/* 181 */
+EXTERN void Tcl_InitHashTable(Tcl_HashTable *tablePtr,
+ int keyType);
+/* 182 */
+EXTERN int Tcl_InputBlocked(Tcl_Channel chan);
+/* 183 */
+EXTERN int Tcl_InputBuffered(Tcl_Channel chan);
+/* 184 */
+EXTERN int Tcl_InterpDeleted(Tcl_Interp *interp);
+/* 185 */
+EXTERN int Tcl_IsSafe(Tcl_Interp *interp);
+/* 186 */
+EXTERN char * Tcl_JoinPath(int argc, CONST84 char *const *argv,
+ Tcl_DString *resultPtr);
+/* 187 */
+EXTERN int Tcl_LinkVar(Tcl_Interp *interp, const char *varName,
+ char *addr, int type);
+/* Slot 188 is reserved */
+/* 189 */
+EXTERN Tcl_Channel Tcl_MakeFileChannel(ClientData handle, int mode);
+/* 190 */
+EXTERN int Tcl_MakeSafe(Tcl_Interp *interp);
+/* 191 */
+EXTERN Tcl_Channel Tcl_MakeTcpClientChannel(ClientData tcpSocket);
+/* 192 */
+EXTERN char * Tcl_Merge(int argc, CONST84 char *const *argv);
+/* 193 */
+EXTERN Tcl_HashEntry * Tcl_NextHashEntry(Tcl_HashSearch *searchPtr);
+/* 194 */
+EXTERN void Tcl_NotifyChannel(Tcl_Channel channel, int mask);
+/* 195 */
+EXTERN Tcl_Obj * Tcl_ObjGetVar2(Tcl_Interp *interp, Tcl_Obj *part1Ptr,
+ Tcl_Obj *part2Ptr, int flags);
+/* 196 */
+EXTERN Tcl_Obj * Tcl_ObjSetVar2(Tcl_Interp *interp, Tcl_Obj *part1Ptr,
+ Tcl_Obj *part2Ptr, Tcl_Obj *newValuePtr,
+ int flags);
+/* 197 */
+EXTERN Tcl_Channel Tcl_OpenCommandChannel(Tcl_Interp *interp, int argc,
+ CONST84 char **argv, int flags);
+/* 198 */
+EXTERN Tcl_Channel Tcl_OpenFileChannel(Tcl_Interp *interp,
+ const char *fileName, const char *modeString,
+ int permissions);
+/* 199 */
+EXTERN Tcl_Channel Tcl_OpenTcpClient(Tcl_Interp *interp, int port,
+ const char *address, const char *myaddr,
+ int myport, int async);
+/* 200 */
+EXTERN Tcl_Channel Tcl_OpenTcpServer(Tcl_Interp *interp, int port,
+ const char *host,
+ Tcl_TcpAcceptProc *acceptProc,
+ ClientData callbackData);
+/* 201 */
+EXTERN void Tcl_Preserve(ClientData data);
+/* 202 */
+EXTERN void Tcl_PrintDouble(Tcl_Interp *interp, double value,
+ char *dst);
+/* 203 */
+EXTERN int Tcl_PutEnv(const char *assignment);
+/* 204 */
+EXTERN CONST84_RETURN char * Tcl_PosixError(Tcl_Interp *interp);
+/* 205 */
+EXTERN void Tcl_QueueEvent(Tcl_Event *evPtr,
+ Tcl_QueuePosition position);
+/* 206 */
+EXTERN int Tcl_Read(Tcl_Channel chan, char *bufPtr, int toRead);
+/* 207 */
+EXTERN void Tcl_ReapDetachedProcs(void);
+/* 208 */
+EXTERN int Tcl_RecordAndEval(Tcl_Interp *interp,
+ const char *cmd, int flags);
+/* 209 */
+EXTERN int Tcl_RecordAndEvalObj(Tcl_Interp *interp,
+ Tcl_Obj *cmdPtr, int flags);
+/* 210 */
+EXTERN void Tcl_RegisterChannel(Tcl_Interp *interp,
+ Tcl_Channel chan);
+/* 211 */
+EXTERN void Tcl_RegisterObjType(const Tcl_ObjType *typePtr);
+/* 212 */
+EXTERN Tcl_RegExp Tcl_RegExpCompile(Tcl_Interp *interp,
+ const char *pattern);
+/* 213 */
+EXTERN int Tcl_RegExpExec(Tcl_Interp *interp, Tcl_RegExp regexp,
+ const char *text, const char *start);
+/* 214 */
+EXTERN int Tcl_RegExpMatch(Tcl_Interp *interp, const char *text,
+ const char *pattern);
+/* 215 */
+EXTERN void Tcl_RegExpRange(Tcl_RegExp regexp, int index,
+ CONST84 char **startPtr,
+ CONST84 char **endPtr);
+/* 216 */
+EXTERN void Tcl_Release(ClientData clientData);
+/* 217 */
+EXTERN void Tcl_ResetResult(Tcl_Interp *interp);
+/* 218 */
+EXTERN int Tcl_ScanElement(const char *src, int *flagPtr);
+/* 219 */
+EXTERN int Tcl_ScanCountedElement(const char *src, int length,
+ int *flagPtr);
+/* 220 */
+EXTERN int Tcl_SeekOld(Tcl_Channel chan, int offset, int mode);
+/* 221 */
+EXTERN int Tcl_ServiceAll(void);
+/* 222 */
+EXTERN int Tcl_ServiceEvent(int flags);
+/* 223 */
+EXTERN void Tcl_SetAssocData(Tcl_Interp *interp,
+ const char *name, Tcl_InterpDeleteProc *proc,
+ ClientData clientData);
+/* 224 */
+EXTERN void Tcl_SetChannelBufferSize(Tcl_Channel chan, int sz);
+/* 225 */
+EXTERN int Tcl_SetChannelOption(Tcl_Interp *interp,
+ Tcl_Channel chan, const char *optionName,
+ const char *newValue);
+/* 226 */
+EXTERN int Tcl_SetCommandInfo(Tcl_Interp *interp,
+ const char *cmdName,
+ const Tcl_CmdInfo *infoPtr);
+/* 227 */
+EXTERN void Tcl_SetErrno(int err);
+/* 228 */
+EXTERN void Tcl_SetErrorCode(Tcl_Interp *interp, ...);
+/* 229 */
+EXTERN void Tcl_SetMaxBlockTime(const Tcl_Time *timePtr);
+/* 230 */
+EXTERN void Tcl_SetPanicProc(Tcl_PanicProc *panicProc);
+/* 231 */
+EXTERN int Tcl_SetRecursionLimit(Tcl_Interp *interp, int depth);
+/* 232 */
+EXTERN void Tcl_SetResult(Tcl_Interp *interp, char *result,
+ Tcl_FreeProc *freeProc);
+/* 233 */
+EXTERN int Tcl_SetServiceMode(int mode);
+/* 234 */
+EXTERN void Tcl_SetObjErrorCode(Tcl_Interp *interp,
+ Tcl_Obj *errorObjPtr);
+/* 235 */
+EXTERN void Tcl_SetObjResult(Tcl_Interp *interp,
+ Tcl_Obj *resultObjPtr);
+/* 236 */
+EXTERN void Tcl_SetStdChannel(Tcl_Channel channel, int type);
+/* 237 */
+EXTERN CONST84_RETURN char * Tcl_SetVar(Tcl_Interp *interp,
+ const char *varName, const char *newValue,
+ int flags);
+/* 238 */
+EXTERN CONST84_RETURN char * Tcl_SetVar2(Tcl_Interp *interp,
+ const char *part1, const char *part2,
+ const char *newValue, int flags);
+/* 239 */
+EXTERN CONST84_RETURN char * Tcl_SignalId(int sig);
+/* 240 */
+EXTERN CONST84_RETURN char * Tcl_SignalMsg(int sig);
+/* 241 */
+EXTERN void Tcl_SourceRCFile(Tcl_Interp *interp);
+/* 242 */
+EXTERN int Tcl_SplitList(Tcl_Interp *interp,
+ const char *listStr, int *argcPtr,
+ CONST84 char ***argvPtr);
+/* 243 */
+EXTERN void Tcl_SplitPath(const char *path, int *argcPtr,
+ CONST84 char ***argvPtr);
+/* 244 */
+EXTERN void Tcl_StaticPackage(Tcl_Interp *interp,
+ const char *pkgName,
+ Tcl_PackageInitProc *initProc,
+ Tcl_PackageInitProc *safeInitProc);
+/* 245 */
+EXTERN int Tcl_StringMatch(const char *str, const char *pattern);
+/* 246 */
+EXTERN int Tcl_TellOld(Tcl_Channel chan);
+/* 247 */
+EXTERN int Tcl_TraceVar(Tcl_Interp *interp, const char *varName,
+ int flags, Tcl_VarTraceProc *proc,
+ ClientData clientData);
+/* 248 */
+EXTERN int Tcl_TraceVar2(Tcl_Interp *interp, const char *part1,
+ const char *part2, int flags,
+ Tcl_VarTraceProc *proc,
+ ClientData clientData);
+/* 249 */
+EXTERN char * Tcl_TranslateFileName(Tcl_Interp *interp,
+ const char *name, Tcl_DString *bufferPtr);
+/* 250 */
+EXTERN int Tcl_Ungets(Tcl_Channel chan, const char *str,
+ int len, int atHead);
+/* 251 */
+EXTERN void Tcl_UnlinkVar(Tcl_Interp *interp,
+ const char *varName);
+/* 252 */
+EXTERN int Tcl_UnregisterChannel(Tcl_Interp *interp,
+ Tcl_Channel chan);
+/* 253 */
+EXTERN int Tcl_UnsetVar(Tcl_Interp *interp, const char *varName,
+ int flags);
+/* 254 */
+EXTERN int Tcl_UnsetVar2(Tcl_Interp *interp, const char *part1,
+ const char *part2, int flags);
+/* 255 */
+EXTERN void Tcl_UntraceVar(Tcl_Interp *interp,
+ const char *varName, int flags,
+ Tcl_VarTraceProc *proc,
+ ClientData clientData);
+/* 256 */
+EXTERN void Tcl_UntraceVar2(Tcl_Interp *interp,
+ const char *part1, const char *part2,
+ int flags, Tcl_VarTraceProc *proc,
+ ClientData clientData);
+/* 257 */
+EXTERN void Tcl_UpdateLinkedVar(Tcl_Interp *interp,
+ const char *varName);
+/* 258 */
+EXTERN int Tcl_UpVar(Tcl_Interp *interp, const char *frameName,
+ const char *varName, const char *localName,
+ int flags);
+/* 259 */
+EXTERN int Tcl_UpVar2(Tcl_Interp *interp, const char *frameName,
+ const char *part1, const char *part2,
+ const char *localName, int flags);
+/* 260 */
+EXTERN int Tcl_VarEval(Tcl_Interp *interp, ...);
+/* 261 */
+EXTERN ClientData Tcl_VarTraceInfo(Tcl_Interp *interp,
+ const char *varName, int flags,
+ Tcl_VarTraceProc *procPtr,
+ ClientData prevClientData);
+/* 262 */
+EXTERN ClientData Tcl_VarTraceInfo2(Tcl_Interp *interp,
+ const char *part1, const char *part2,
+ int flags, Tcl_VarTraceProc *procPtr,
+ ClientData prevClientData);
+/* 263 */
+EXTERN int Tcl_Write(Tcl_Channel chan, const char *s, int slen);
+/* 264 */
+EXTERN void Tcl_WrongNumArgs(Tcl_Interp *interp, int objc,
+ Tcl_Obj *const objv[], const char *message);
+/* 265 */
+EXTERN int Tcl_DumpActiveMemory(const char *fileName);
+/* 266 */
+EXTERN void Tcl_ValidateAllMemory(const char *file, int line);
+/* 267 */
+EXTERN void Tcl_AppendResultVA(Tcl_Interp *interp,
+ va_list argList);
+/* 268 */
+EXTERN void Tcl_AppendStringsToObjVA(Tcl_Obj *objPtr,
+ va_list argList);
+/* 269 */
+EXTERN char * Tcl_HashStats(Tcl_HashTable *tablePtr);
+/* 270 */
+EXTERN CONST84_RETURN char * Tcl_ParseVar(Tcl_Interp *interp,
+ const char *start, CONST84 char **termPtr);
+/* 271 */
+EXTERN CONST84_RETURN char * Tcl_PkgPresent(Tcl_Interp *interp,
+ const char *name, const char *version,
+ int exact);
+/* 272 */
+EXTERN CONST84_RETURN char * Tcl_PkgPresentEx(Tcl_Interp *interp,
+ const char *name, const char *version,
+ int exact, void *clientDataPtr);
+/* 273 */
+EXTERN int Tcl_PkgProvide(Tcl_Interp *interp, const char *name,
+ const char *version);
+/* 274 */
+EXTERN CONST84_RETURN char * Tcl_PkgRequire(Tcl_Interp *interp,
+ const char *name, const char *version,
+ int exact);
+/* 275 */
+EXTERN void Tcl_SetErrorCodeVA(Tcl_Interp *interp,
+ va_list argList);
+/* 276 */
+EXTERN int Tcl_VarEvalVA(Tcl_Interp *interp, va_list argList);
+/* 277 */
+EXTERN Tcl_Pid Tcl_WaitPid(Tcl_Pid pid, int *statPtr, int options);
+/* 278 */
+EXTERN void Tcl_PanicVA(const char *format, va_list argList);
+/* 279 */
+EXTERN void Tcl_GetVersion(int *major, int *minor,
+ int *patchLevel, int *type);
+/* 280 */
+EXTERN void Tcl_InitMemory(Tcl_Interp *interp);
+/* 281 */
+EXTERN Tcl_Channel Tcl_StackChannel(Tcl_Interp *interp,
+ const Tcl_ChannelType *typePtr,
+ ClientData instanceData, int mask,
+ Tcl_Channel prevChan);
+/* 282 */
+EXTERN int Tcl_UnstackChannel(Tcl_Interp *interp,
+ Tcl_Channel chan);
+/* 283 */
+EXTERN Tcl_Channel Tcl_GetStackedChannel(Tcl_Channel chan);
+/* 284 */
+EXTERN void Tcl_SetMainLoop(Tcl_MainLoopProc *proc);
+/* Slot 285 is reserved */
+/* 286 */
+EXTERN void Tcl_AppendObjToObj(Tcl_Obj *objPtr,
+ Tcl_Obj *appendObjPtr);
+/* 287 */
+EXTERN Tcl_Encoding Tcl_CreateEncoding(const Tcl_EncodingType *typePtr);
+/* 288 */
+EXTERN void Tcl_CreateThreadExitHandler(Tcl_ExitProc *proc,
+ ClientData clientData);
+/* 289 */
+EXTERN void Tcl_DeleteThreadExitHandler(Tcl_ExitProc *proc,
+ ClientData clientData);
+/* 290 */
+EXTERN void Tcl_DiscardResult(Tcl_SavedResult *statePtr);
+/* 291 */
+EXTERN int Tcl_EvalEx(Tcl_Interp *interp, const char *script,
+ int numBytes, int flags);
+/* 292 */
+EXTERN int Tcl_EvalObjv(Tcl_Interp *interp, int objc,
+ Tcl_Obj *const objv[], int flags);
+/* 293 */
+EXTERN int Tcl_EvalObjEx(Tcl_Interp *interp, Tcl_Obj *objPtr,
+ int flags);
+/* 294 */
+EXTERN void Tcl_ExitThread(int status);
+/* 295 */
+EXTERN int Tcl_ExternalToUtf(Tcl_Interp *interp,
+ Tcl_Encoding encoding, const char *src,
+ int srcLen, int flags,
+ Tcl_EncodingState *statePtr, char *dst,
+ int dstLen, int *srcReadPtr,
+ int *dstWrotePtr, int *dstCharsPtr);
+/* 296 */
+EXTERN char * Tcl_ExternalToUtfDString(Tcl_Encoding encoding,
+ const char *src, int srcLen,
+ Tcl_DString *dsPtr);
+/* 297 */
+EXTERN void Tcl_FinalizeThread(void);
+/* 298 */
+EXTERN void Tcl_FinalizeNotifier(ClientData clientData);
+/* 299 */
+EXTERN void Tcl_FreeEncoding(Tcl_Encoding encoding);
+/* 300 */
+EXTERN Tcl_ThreadId Tcl_GetCurrentThread(void);
+/* 301 */
+EXTERN Tcl_Encoding Tcl_GetEncoding(Tcl_Interp *interp, const char *name);
+/* 302 */
+EXTERN CONST84_RETURN char * Tcl_GetEncodingName(Tcl_Encoding encoding);
+/* 303 */
+EXTERN void Tcl_GetEncodingNames(Tcl_Interp *interp);
+/* 304 */
+EXTERN int Tcl_GetIndexFromObjStruct(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, const void *tablePtr,
+ int offset, const char *msg, int flags,
+ int *indexPtr);
+/* 305 */
+EXTERN void * Tcl_GetThreadData(Tcl_ThreadDataKey *keyPtr,
+ int size);
+/* 306 */
+EXTERN Tcl_Obj * Tcl_GetVar2Ex(Tcl_Interp *interp, const char *part1,
+ const char *part2, int flags);
+/* 307 */
+EXTERN ClientData Tcl_InitNotifier(void);
+/* 308 */
+EXTERN void Tcl_MutexLock(Tcl_Mutex *mutexPtr);
+/* 309 */
+EXTERN void Tcl_MutexUnlock(Tcl_Mutex *mutexPtr);
+/* 310 */
+EXTERN void Tcl_ConditionNotify(Tcl_Condition *condPtr);
+/* 311 */
+EXTERN void Tcl_ConditionWait(Tcl_Condition *condPtr,
+ Tcl_Mutex *mutexPtr, const Tcl_Time *timePtr);
+/* 312 */
+EXTERN int Tcl_NumUtfChars(const char *src, int length);
+/* 313 */
+EXTERN int Tcl_ReadChars(Tcl_Channel channel, Tcl_Obj *objPtr,
+ int charsToRead, int appendFlag);
+/* 314 */
+EXTERN void Tcl_RestoreResult(Tcl_Interp *interp,
+ Tcl_SavedResult *statePtr);
+/* 315 */
+EXTERN void Tcl_SaveResult(Tcl_Interp *interp,
+ Tcl_SavedResult *statePtr);
+/* 316 */
+EXTERN int Tcl_SetSystemEncoding(Tcl_Interp *interp,
+ const char *name);
+/* 317 */
+EXTERN Tcl_Obj * Tcl_SetVar2Ex(Tcl_Interp *interp, const char *part1,
+ const char *part2, Tcl_Obj *newValuePtr,
+ int flags);
+/* 318 */
+EXTERN void Tcl_ThreadAlert(Tcl_ThreadId threadId);
+/* 319 */
+EXTERN void Tcl_ThreadQueueEvent(Tcl_ThreadId threadId,
+ Tcl_Event *evPtr, Tcl_QueuePosition position);
+/* 320 */
+EXTERN Tcl_UniChar Tcl_UniCharAtIndex(const char *src, int index);
+/* 321 */
+EXTERN Tcl_UniChar Tcl_UniCharToLower(int ch);
+/* 322 */
+EXTERN Tcl_UniChar Tcl_UniCharToTitle(int ch);
+/* 323 */
+EXTERN Tcl_UniChar Tcl_UniCharToUpper(int ch);
+/* 324 */
+EXTERN int Tcl_UniCharToUtf(int ch, char *buf);
+/* 325 */
+EXTERN CONST84_RETURN char * Tcl_UtfAtIndex(const char *src, int index);
+/* 326 */
+EXTERN int Tcl_UtfCharComplete(const char *src, int length);
+/* 327 */
+EXTERN int Tcl_UtfBackslash(const char *src, int *readPtr,
+ char *dst);
+/* 328 */
+EXTERN CONST84_RETURN char * Tcl_UtfFindFirst(const char *src, int ch);
+/* 329 */
+EXTERN CONST84_RETURN char * Tcl_UtfFindLast(const char *src, int ch);
+/* 330 */
+EXTERN CONST84_RETURN char * Tcl_UtfNext(const char *src);
+/* 331 */
+EXTERN CONST84_RETURN char * Tcl_UtfPrev(const char *src, const char *start);
+/* 332 */
+EXTERN int Tcl_UtfToExternal(Tcl_Interp *interp,
+ Tcl_Encoding encoding, const char *src,
+ int srcLen, int flags,
+ Tcl_EncodingState *statePtr, char *dst,
+ int dstLen, int *srcReadPtr,
+ int *dstWrotePtr, int *dstCharsPtr);
+/* 333 */
+EXTERN char * Tcl_UtfToExternalDString(Tcl_Encoding encoding,
+ const char *src, int srcLen,
+ Tcl_DString *dsPtr);
+/* 334 */
+EXTERN int Tcl_UtfToLower(char *src);
+/* 335 */
+EXTERN int Tcl_UtfToTitle(char *src);
+/* 336 */
+EXTERN int Tcl_UtfToUniChar(const char *src, Tcl_UniChar *chPtr);
+/* 337 */
+EXTERN int Tcl_UtfToUpper(char *src);
+/* 338 */
+EXTERN int Tcl_WriteChars(Tcl_Channel chan, const char *src,
+ int srcLen);
+/* 339 */
+EXTERN int Tcl_WriteObj(Tcl_Channel chan, Tcl_Obj *objPtr);
+/* 340 */
+EXTERN char * Tcl_GetString(Tcl_Obj *objPtr);
+/* 341 */
+EXTERN CONST84_RETURN char * Tcl_GetDefaultEncodingDir(void);
+/* 342 */
+EXTERN void Tcl_SetDefaultEncodingDir(const char *path);
+/* 343 */
+EXTERN void Tcl_AlertNotifier(ClientData clientData);
+/* 344 */
+EXTERN void Tcl_ServiceModeHook(int mode);
+/* 345 */
+EXTERN int Tcl_UniCharIsAlnum(int ch);
+/* 346 */
+EXTERN int Tcl_UniCharIsAlpha(int ch);
+/* 347 */
+EXTERN int Tcl_UniCharIsDigit(int ch);
+/* 348 */
+EXTERN int Tcl_UniCharIsLower(int ch);
+/* 349 */
+EXTERN int Tcl_UniCharIsSpace(int ch);
+/* 350 */
+EXTERN int Tcl_UniCharIsUpper(int ch);
+/* 351 */
+EXTERN int Tcl_UniCharIsWordChar(int ch);
+/* 352 */
+EXTERN int Tcl_UniCharLen(const Tcl_UniChar *uniStr);
+/* 353 */
+EXTERN int Tcl_UniCharNcmp(const Tcl_UniChar *ucs,
+ const Tcl_UniChar *uct,
+ unsigned long numChars);
+/* 354 */
+EXTERN char * Tcl_UniCharToUtfDString(const Tcl_UniChar *uniStr,
+ int uniLength, Tcl_DString *dsPtr);
+/* 355 */
+EXTERN Tcl_UniChar * Tcl_UtfToUniCharDString(const char *src, int length,
+ Tcl_DString *dsPtr);
+/* 356 */
+EXTERN Tcl_RegExp Tcl_GetRegExpFromObj(Tcl_Interp *interp,
+ Tcl_Obj *patObj, int flags);
+/* 357 */
+EXTERN Tcl_Obj * Tcl_EvalTokens(Tcl_Interp *interp,
+ Tcl_Token *tokenPtr, int count);
+/* 358 */
+EXTERN void Tcl_FreeParse(Tcl_Parse *parsePtr);
+/* 359 */
+EXTERN void Tcl_LogCommandInfo(Tcl_Interp *interp,
+ const char *script, const char *command,
+ int length);
+/* 360 */
+EXTERN int Tcl_ParseBraces(Tcl_Interp *interp,
+ const char *start, int numBytes,
+ Tcl_Parse *parsePtr, int append,
+ CONST84 char **termPtr);
+/* 361 */
+EXTERN int Tcl_ParseCommand(Tcl_Interp *interp,
+ const char *start, int numBytes, int nested,
+ Tcl_Parse *parsePtr);
+/* 362 */
+EXTERN int Tcl_ParseExpr(Tcl_Interp *interp, const char *start,
+ int numBytes, Tcl_Parse *parsePtr);
+/* 363 */
+EXTERN int Tcl_ParseQuotedString(Tcl_Interp *interp,
+ const char *start, int numBytes,
+ Tcl_Parse *parsePtr, int append,
+ CONST84 char **termPtr);
+/* 364 */
+EXTERN int Tcl_ParseVarName(Tcl_Interp *interp,
+ const char *start, int numBytes,
+ Tcl_Parse *parsePtr, int append);
+/* 365 */
+EXTERN char * Tcl_GetCwd(Tcl_Interp *interp, Tcl_DString *cwdPtr);
+/* 366 */
+EXTERN int Tcl_Chdir(const char *dirName);
+/* 367 */
+EXTERN int Tcl_Access(const char *path, int mode);
+/* 368 */
+EXTERN int Tcl_Stat(const char *path, struct stat *bufPtr);
+/* 369 */
+EXTERN int Tcl_UtfNcmp(const char *s1, const char *s2,
+ unsigned long n);
+/* 370 */
+EXTERN int Tcl_UtfNcasecmp(const char *s1, const char *s2,
+ unsigned long n);
+/* 371 */
+EXTERN int Tcl_StringCaseMatch(const char *str,
+ const char *pattern, int nocase);
+/* 372 */
+EXTERN int Tcl_UniCharIsControl(int ch);
+/* 373 */
+EXTERN int Tcl_UniCharIsGraph(int ch);
+/* 374 */
+EXTERN int Tcl_UniCharIsPrint(int ch);
+/* 375 */
+EXTERN int Tcl_UniCharIsPunct(int ch);
+/* 376 */
+EXTERN int Tcl_RegExpExecObj(Tcl_Interp *interp,
+ Tcl_RegExp regexp, Tcl_Obj *textObj,
+ int offset, int nmatches, int flags);
+/* 377 */
+EXTERN void Tcl_RegExpGetInfo(Tcl_RegExp regexp,
+ Tcl_RegExpInfo *infoPtr);
+/* 378 */
+EXTERN Tcl_Obj * Tcl_NewUnicodeObj(const Tcl_UniChar *unicode,
+ int numChars);
+/* 379 */
+EXTERN void Tcl_SetUnicodeObj(Tcl_Obj *objPtr,
+ const Tcl_UniChar *unicode, int numChars);
+/* 380 */
+EXTERN int Tcl_GetCharLength(Tcl_Obj *objPtr);
+/* 381 */
+EXTERN Tcl_UniChar Tcl_GetUniChar(Tcl_Obj *objPtr, int index);
+/* 382 */
+EXTERN Tcl_UniChar * Tcl_GetUnicode(Tcl_Obj *objPtr);
+/* 383 */
+EXTERN Tcl_Obj * Tcl_GetRange(Tcl_Obj *objPtr, int first, int last);
+/* 384 */
+EXTERN void Tcl_AppendUnicodeToObj(Tcl_Obj *objPtr,
+ const Tcl_UniChar *unicode, int length);
+/* 385 */
+EXTERN int Tcl_RegExpMatchObj(Tcl_Interp *interp,
+ Tcl_Obj *textObj, Tcl_Obj *patternObj);
+/* 386 */
+EXTERN void Tcl_SetNotifier(Tcl_NotifierProcs *notifierProcPtr);
+/* 387 */
+EXTERN Tcl_Mutex * Tcl_GetAllocMutex(void);
+/* 388 */
+EXTERN int Tcl_GetChannelNames(Tcl_Interp *interp);
+/* 389 */
+EXTERN int Tcl_GetChannelNamesEx(Tcl_Interp *interp,
+ const char *pattern);
+/* 390 */
+EXTERN int Tcl_ProcObjCmd(ClientData clientData,
+ Tcl_Interp *interp, int objc,
+ Tcl_Obj *const objv[]);
+/* 391 */
+EXTERN void Tcl_ConditionFinalize(Tcl_Condition *condPtr);
+/* 392 */
+EXTERN void Tcl_MutexFinalize(Tcl_Mutex *mutex);
+/* 393 */
+EXTERN int Tcl_CreateThread(Tcl_ThreadId *idPtr,
+ Tcl_ThreadCreateProc *proc,
+ ClientData clientData, int stackSize,
+ int flags);
+/* 394 */
+EXTERN int Tcl_ReadRaw(Tcl_Channel chan, char *dst,
+ int bytesToRead);
+/* 395 */
+EXTERN int Tcl_WriteRaw(Tcl_Channel chan, const char *src,
+ int srcLen);
+/* 396 */
+EXTERN Tcl_Channel Tcl_GetTopChannel(Tcl_Channel chan);
+/* 397 */
+EXTERN int Tcl_ChannelBuffered(Tcl_Channel chan);
+/* 398 */
+EXTERN CONST84_RETURN char * Tcl_ChannelName(
+ const Tcl_ChannelType *chanTypePtr);
+/* 399 */
+EXTERN Tcl_ChannelTypeVersion Tcl_ChannelVersion(
+ const Tcl_ChannelType *chanTypePtr);
+/* 400 */
+EXTERN Tcl_DriverBlockModeProc * Tcl_ChannelBlockModeProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 401 */
+EXTERN Tcl_DriverCloseProc * Tcl_ChannelCloseProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 402 */
+EXTERN Tcl_DriverClose2Proc * Tcl_ChannelClose2Proc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 403 */
+EXTERN Tcl_DriverInputProc * Tcl_ChannelInputProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 404 */
+EXTERN Tcl_DriverOutputProc * Tcl_ChannelOutputProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 405 */
+EXTERN Tcl_DriverSeekProc * Tcl_ChannelSeekProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 406 */
+EXTERN Tcl_DriverSetOptionProc * Tcl_ChannelSetOptionProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 407 */
+EXTERN Tcl_DriverGetOptionProc * Tcl_ChannelGetOptionProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 408 */
+EXTERN Tcl_DriverWatchProc * Tcl_ChannelWatchProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 409 */
+EXTERN Tcl_DriverGetHandleProc * Tcl_ChannelGetHandleProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 410 */
+EXTERN Tcl_DriverFlushProc * Tcl_ChannelFlushProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 411 */
+EXTERN Tcl_DriverHandlerProc * Tcl_ChannelHandlerProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 412 */
+EXTERN int Tcl_JoinThread(Tcl_ThreadId threadId, int *result);
+/* 413 */
+EXTERN int Tcl_IsChannelShared(Tcl_Channel channel);
+/* 414 */
+EXTERN int Tcl_IsChannelRegistered(Tcl_Interp *interp,
+ Tcl_Channel channel);
+/* 415 */
+EXTERN void Tcl_CutChannel(Tcl_Channel channel);
+/* 416 */
+EXTERN void Tcl_SpliceChannel(Tcl_Channel channel);
+/* 417 */
+EXTERN void Tcl_ClearChannelHandlers(Tcl_Channel channel);
+/* 418 */
+EXTERN int Tcl_IsChannelExisting(const char *channelName);
+/* 419 */
+EXTERN int Tcl_UniCharNcasecmp(const Tcl_UniChar *ucs,
+ const Tcl_UniChar *uct,
+ unsigned long numChars);
+/* 420 */
+EXTERN int Tcl_UniCharCaseMatch(const Tcl_UniChar *uniStr,
+ const Tcl_UniChar *uniPattern, int nocase);
+/* 421 */
+EXTERN Tcl_HashEntry * Tcl_FindHashEntry(Tcl_HashTable *tablePtr,
+ const void *key);
+/* 422 */
+EXTERN Tcl_HashEntry * Tcl_CreateHashEntry(Tcl_HashTable *tablePtr,
+ const void *key, int *newPtr);
+/* 423 */
+EXTERN void Tcl_InitCustomHashTable(Tcl_HashTable *tablePtr,
+ int keyType, const Tcl_HashKeyType *typePtr);
+/* 424 */
+EXTERN void Tcl_InitObjHashTable(Tcl_HashTable *tablePtr);
+/* 425 */
+EXTERN ClientData Tcl_CommandTraceInfo(Tcl_Interp *interp,
+ const char *varName, int flags,
+ Tcl_CommandTraceProc *procPtr,
+ ClientData prevClientData);
+/* 426 */
+EXTERN int Tcl_TraceCommand(Tcl_Interp *interp,
+ const char *varName, int flags,
+ Tcl_CommandTraceProc *proc,
+ ClientData clientData);
+/* 427 */
+EXTERN void Tcl_UntraceCommand(Tcl_Interp *interp,
+ const char *varName, int flags,
+ Tcl_CommandTraceProc *proc,
+ ClientData clientData);
+/* 428 */
+EXTERN char * Tcl_AttemptAlloc(unsigned int size);
+/* 429 */
+EXTERN char * Tcl_AttemptDbCkalloc(unsigned int size,
+ const char *file, int line);
+/* 430 */
+EXTERN char * Tcl_AttemptRealloc(char *ptr, unsigned int size);
+/* 431 */
+EXTERN char * Tcl_AttemptDbCkrealloc(char *ptr, unsigned int size,
+ const char *file, int line);
+/* 432 */
+EXTERN int Tcl_AttemptSetObjLength(Tcl_Obj *objPtr, int length);
+/* 433 */
+EXTERN Tcl_ThreadId Tcl_GetChannelThread(Tcl_Channel channel);
+/* 434 */
+EXTERN Tcl_UniChar * Tcl_GetUnicodeFromObj(Tcl_Obj *objPtr,
+ int *lengthPtr);
+/* 435 */
+EXTERN int Tcl_GetMathFuncInfo(Tcl_Interp *interp,
+ const char *name, int *numArgsPtr,
+ Tcl_ValueType **argTypesPtr,
+ Tcl_MathProc **procPtr,
+ ClientData *clientDataPtr);
+/* 436 */
+EXTERN Tcl_Obj * Tcl_ListMathFuncs(Tcl_Interp *interp,
+ const char *pattern);
+/* 437 */
+EXTERN Tcl_Obj * Tcl_SubstObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
+ int flags);
+/* 438 */
+EXTERN int Tcl_DetachChannel(Tcl_Interp *interp,
+ Tcl_Channel channel);
+/* 439 */
+EXTERN int Tcl_IsStandardChannel(Tcl_Channel channel);
+/* 440 */
+EXTERN int Tcl_FSCopyFile(Tcl_Obj *srcPathPtr,
+ Tcl_Obj *destPathPtr);
+/* 441 */
+EXTERN int Tcl_FSCopyDirectory(Tcl_Obj *srcPathPtr,
+ Tcl_Obj *destPathPtr, Tcl_Obj **errorPtr);
+/* 442 */
+EXTERN int Tcl_FSCreateDirectory(Tcl_Obj *pathPtr);
+/* 443 */
+EXTERN int Tcl_FSDeleteFile(Tcl_Obj *pathPtr);
+/* 444 */
+EXTERN int Tcl_FSLoadFile(Tcl_Interp *interp, Tcl_Obj *pathPtr,
+ const char *sym1, const char *sym2,
+ Tcl_PackageInitProc **proc1Ptr,
+ Tcl_PackageInitProc **proc2Ptr,
+ Tcl_LoadHandle *handlePtr,
+ Tcl_FSUnloadFileProc **unloadProcPtr);
+/* 445 */
+EXTERN int Tcl_FSMatchInDirectory(Tcl_Interp *interp,
+ Tcl_Obj *result, Tcl_Obj *pathPtr,
+ const char *pattern, Tcl_GlobTypeData *types);
+/* 446 */
+EXTERN Tcl_Obj * Tcl_FSLink(Tcl_Obj *pathPtr, Tcl_Obj *toPtr,
+ int linkAction);
+/* 447 */
+EXTERN int Tcl_FSRemoveDirectory(Tcl_Obj *pathPtr,
+ int recursive, Tcl_Obj **errorPtr);
+/* 448 */
+EXTERN int Tcl_FSRenameFile(Tcl_Obj *srcPathPtr,
+ Tcl_Obj *destPathPtr);
+/* 449 */
+EXTERN int Tcl_FSLstat(Tcl_Obj *pathPtr, Tcl_StatBuf *buf);
+/* 450 */
+EXTERN int Tcl_FSUtime(Tcl_Obj *pathPtr, struct utimbuf *tval);
+/* 451 */
+EXTERN int Tcl_FSFileAttrsGet(Tcl_Interp *interp, int index,
+ Tcl_Obj *pathPtr, Tcl_Obj **objPtrRef);
+/* 452 */
+EXTERN int Tcl_FSFileAttrsSet(Tcl_Interp *interp, int index,
+ Tcl_Obj *pathPtr, Tcl_Obj *objPtr);
+/* 453 */
+EXTERN const char *CONST86 * Tcl_FSFileAttrStrings(Tcl_Obj *pathPtr,
+ Tcl_Obj **objPtrRef);
+/* 454 */
+EXTERN int Tcl_FSStat(Tcl_Obj *pathPtr, Tcl_StatBuf *buf);
+/* 455 */
+EXTERN int Tcl_FSAccess(Tcl_Obj *pathPtr, int mode);
+/* 456 */
+EXTERN Tcl_Channel Tcl_FSOpenFileChannel(Tcl_Interp *interp,
+ Tcl_Obj *pathPtr, const char *modeString,
+ int permissions);
+/* 457 */
+EXTERN Tcl_Obj * Tcl_FSGetCwd(Tcl_Interp *interp);
+/* 458 */
+EXTERN int Tcl_FSChdir(Tcl_Obj *pathPtr);
+/* 459 */
+EXTERN int Tcl_FSConvertToPathType(Tcl_Interp *interp,
+ Tcl_Obj *pathPtr);
+/* 460 */
+EXTERN Tcl_Obj * Tcl_FSJoinPath(Tcl_Obj *listObj, int elements);
+/* 461 */
+EXTERN Tcl_Obj * Tcl_FSSplitPath(Tcl_Obj *pathPtr, int *lenPtr);
+/* 462 */
+EXTERN int Tcl_FSEqualPaths(Tcl_Obj *firstPtr,
+ Tcl_Obj *secondPtr);
+/* 463 */
+EXTERN Tcl_Obj * Tcl_FSGetNormalizedPath(Tcl_Interp *interp,
+ Tcl_Obj *pathPtr);
+/* 464 */
+EXTERN Tcl_Obj * Tcl_FSJoinToPath(Tcl_Obj *pathPtr, int objc,
+ Tcl_Obj *const objv[]);
+/* 465 */
+EXTERN ClientData Tcl_FSGetInternalRep(Tcl_Obj *pathPtr,
+ const Tcl_Filesystem *fsPtr);
+/* 466 */
+EXTERN Tcl_Obj * Tcl_FSGetTranslatedPath(Tcl_Interp *interp,
+ Tcl_Obj *pathPtr);
+/* 467 */
+EXTERN int Tcl_FSEvalFile(Tcl_Interp *interp, Tcl_Obj *fileName);
+/* 468 */
+EXTERN Tcl_Obj * Tcl_FSNewNativePath(
+ const Tcl_Filesystem *fromFilesystem,
+ ClientData clientData);
+/* 469 */
+EXTERN const void * Tcl_FSGetNativePath(Tcl_Obj *pathPtr);
+/* 470 */
+EXTERN Tcl_Obj * Tcl_FSFileSystemInfo(Tcl_Obj *pathPtr);
+/* 471 */
+EXTERN Tcl_Obj * Tcl_FSPathSeparator(Tcl_Obj *pathPtr);
+/* 472 */
+EXTERN Tcl_Obj * Tcl_FSListVolumes(void);
+/* 473 */
+EXTERN int Tcl_FSRegister(ClientData clientData,
+ const Tcl_Filesystem *fsPtr);
+/* 474 */
+EXTERN int Tcl_FSUnregister(const Tcl_Filesystem *fsPtr);
+/* 475 */
+EXTERN ClientData Tcl_FSData(const Tcl_Filesystem *fsPtr);
+/* 476 */
+EXTERN const char * Tcl_FSGetTranslatedStringPath(Tcl_Interp *interp,
+ Tcl_Obj *pathPtr);
+/* 477 */
+EXTERN CONST86 Tcl_Filesystem * Tcl_FSGetFileSystemForPath(Tcl_Obj *pathPtr);
+/* 478 */
+EXTERN Tcl_PathType Tcl_FSGetPathType(Tcl_Obj *pathPtr);
+/* 479 */
+EXTERN int Tcl_OutputBuffered(Tcl_Channel chan);
+/* 480 */
+EXTERN void Tcl_FSMountsChanged(const Tcl_Filesystem *fsPtr);
+/* 481 */
+EXTERN int Tcl_EvalTokensStandard(Tcl_Interp *interp,
+ Tcl_Token *tokenPtr, int count);
+/* 482 */
+EXTERN void Tcl_GetTime(Tcl_Time *timeBuf);
+/* 483 */
+EXTERN Tcl_Trace Tcl_CreateObjTrace(Tcl_Interp *interp, int level,
+ int flags, Tcl_CmdObjTraceProc *objProc,
+ ClientData clientData,
+ Tcl_CmdObjTraceDeleteProc *delProc);
+/* 484 */
+EXTERN int Tcl_GetCommandInfoFromToken(Tcl_Command token,
+ Tcl_CmdInfo *infoPtr);
+/* 485 */
+EXTERN int Tcl_SetCommandInfoFromToken(Tcl_Command token,
+ const Tcl_CmdInfo *infoPtr);
+/* 486 */
+EXTERN Tcl_Obj * Tcl_DbNewWideIntObj(Tcl_WideInt wideValue,
+ const char *file, int line);
+/* 487 */
+EXTERN int Tcl_GetWideIntFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, Tcl_WideInt *widePtr);
+/* 488 */
+EXTERN Tcl_Obj * Tcl_NewWideIntObj(Tcl_WideInt wideValue);
+/* 489 */
+EXTERN void Tcl_SetWideIntObj(Tcl_Obj *objPtr,
+ Tcl_WideInt wideValue);
+/* 490 */
+EXTERN Tcl_StatBuf * Tcl_AllocStatBuf(void);
+/* 491 */
+EXTERN Tcl_WideInt Tcl_Seek(Tcl_Channel chan, Tcl_WideInt offset,
+ int mode);
+/* 492 */
+EXTERN Tcl_WideInt Tcl_Tell(Tcl_Channel chan);
+/* 493 */
+EXTERN Tcl_DriverWideSeekProc * Tcl_ChannelWideSeekProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 494 */
+EXTERN int Tcl_DictObjPut(Tcl_Interp *interp, Tcl_Obj *dictPtr,
+ Tcl_Obj *keyPtr, Tcl_Obj *valuePtr);
+/* 495 */
+EXTERN int Tcl_DictObjGet(Tcl_Interp *interp, Tcl_Obj *dictPtr,
+ Tcl_Obj *keyPtr, Tcl_Obj **valuePtrPtr);
+/* 496 */
+EXTERN int Tcl_DictObjRemove(Tcl_Interp *interp,
+ Tcl_Obj *dictPtr, Tcl_Obj *keyPtr);
+/* 497 */
+EXTERN int Tcl_DictObjSize(Tcl_Interp *interp, Tcl_Obj *dictPtr,
+ int *sizePtr);
+/* 498 */
+EXTERN int Tcl_DictObjFirst(Tcl_Interp *interp,
+ Tcl_Obj *dictPtr, Tcl_DictSearch *searchPtr,
+ Tcl_Obj **keyPtrPtr, Tcl_Obj **valuePtrPtr,
+ int *donePtr);
+/* 499 */
+EXTERN void Tcl_DictObjNext(Tcl_DictSearch *searchPtr,
+ Tcl_Obj **keyPtrPtr, Tcl_Obj **valuePtrPtr,
+ int *donePtr);
+/* 500 */
+EXTERN void Tcl_DictObjDone(Tcl_DictSearch *searchPtr);
+/* 501 */
+EXTERN int Tcl_DictObjPutKeyList(Tcl_Interp *interp,
+ Tcl_Obj *dictPtr, int keyc,
+ Tcl_Obj *const *keyv, Tcl_Obj *valuePtr);
+/* 502 */
+EXTERN int Tcl_DictObjRemoveKeyList(Tcl_Interp *interp,
+ Tcl_Obj *dictPtr, int keyc,
+ Tcl_Obj *const *keyv);
+/* 503 */
+EXTERN Tcl_Obj * Tcl_NewDictObj(void);
+/* 504 */
+EXTERN Tcl_Obj * Tcl_DbNewDictObj(const char *file, int line);
+/* 505 */
+EXTERN void Tcl_RegisterConfig(Tcl_Interp *interp,
+ const char *pkgName,
+ const Tcl_Config *configuration,
+ const char *valEncoding);
+/* 506 */
+EXTERN Tcl_Namespace * Tcl_CreateNamespace(Tcl_Interp *interp,
+ const char *name, ClientData clientData,
+ Tcl_NamespaceDeleteProc *deleteProc);
+/* 507 */
+EXTERN void Tcl_DeleteNamespace(Tcl_Namespace *nsPtr);
+/* 508 */
+EXTERN int Tcl_AppendExportList(Tcl_Interp *interp,
+ Tcl_Namespace *nsPtr, Tcl_Obj *objPtr);
+/* 509 */
+EXTERN int Tcl_Export(Tcl_Interp *interp, Tcl_Namespace *nsPtr,
+ const char *pattern, int resetListFirst);
+/* 510 */
+EXTERN int Tcl_Import(Tcl_Interp *interp, Tcl_Namespace *nsPtr,
+ const char *pattern, int allowOverwrite);
+/* 511 */
+EXTERN int Tcl_ForgetImport(Tcl_Interp *interp,
+ Tcl_Namespace *nsPtr, const char *pattern);
+/* 512 */
+EXTERN Tcl_Namespace * Tcl_GetCurrentNamespace(Tcl_Interp *interp);
+/* 513 */
+EXTERN Tcl_Namespace * Tcl_GetGlobalNamespace(Tcl_Interp *interp);
+/* 514 */
+EXTERN Tcl_Namespace * Tcl_FindNamespace(Tcl_Interp *interp,
+ const char *name,
+ Tcl_Namespace *contextNsPtr, int flags);
+/* 515 */
+EXTERN Tcl_Command Tcl_FindCommand(Tcl_Interp *interp, const char *name,
+ Tcl_Namespace *contextNsPtr, int flags);
+/* 516 */
+EXTERN Tcl_Command Tcl_GetCommandFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr);
+/* 517 */
+EXTERN void Tcl_GetCommandFullName(Tcl_Interp *interp,
+ Tcl_Command command, Tcl_Obj *objPtr);
+/* 518 */
+EXTERN int Tcl_FSEvalFileEx(Tcl_Interp *interp,
+ Tcl_Obj *fileName, const char *encodingName);
+/* 519 */
+EXTERN Tcl_ExitProc * Tcl_SetExitProc(Tcl_ExitProc *proc);
+/* 520 */
+EXTERN void Tcl_LimitAddHandler(Tcl_Interp *interp, int type,
+ Tcl_LimitHandlerProc *handlerProc,
+ ClientData clientData,
+ Tcl_LimitHandlerDeleteProc *deleteProc);
+/* 521 */
+EXTERN void Tcl_LimitRemoveHandler(Tcl_Interp *interp, int type,
+ Tcl_LimitHandlerProc *handlerProc,
+ ClientData clientData);
+/* 522 */
+EXTERN int Tcl_LimitReady(Tcl_Interp *interp);
+/* 523 */
+EXTERN int Tcl_LimitCheck(Tcl_Interp *interp);
+/* 524 */
+EXTERN int Tcl_LimitExceeded(Tcl_Interp *interp);
+/* 525 */
+EXTERN void Tcl_LimitSetCommands(Tcl_Interp *interp,
+ int commandLimit);
+/* 526 */
+EXTERN void Tcl_LimitSetTime(Tcl_Interp *interp,
+ Tcl_Time *timeLimitPtr);
+/* 527 */
+EXTERN void Tcl_LimitSetGranularity(Tcl_Interp *interp, int type,
+ int granularity);
+/* 528 */
+EXTERN int Tcl_LimitTypeEnabled(Tcl_Interp *interp, int type);
+/* 529 */
+EXTERN int Tcl_LimitTypeExceeded(Tcl_Interp *interp, int type);
+/* 530 */
+EXTERN void Tcl_LimitTypeSet(Tcl_Interp *interp, int type);
+/* 531 */
+EXTERN void Tcl_LimitTypeReset(Tcl_Interp *interp, int type);
+/* 532 */
+EXTERN int Tcl_LimitGetCommands(Tcl_Interp *interp);
+/* 533 */
+EXTERN void Tcl_LimitGetTime(Tcl_Interp *interp,
+ Tcl_Time *timeLimitPtr);
+/* 534 */
+EXTERN int Tcl_LimitGetGranularity(Tcl_Interp *interp, int type);
+/* 535 */
+EXTERN Tcl_InterpState Tcl_SaveInterpState(Tcl_Interp *interp, int status);
+/* 536 */
+EXTERN int Tcl_RestoreInterpState(Tcl_Interp *interp,
+ Tcl_InterpState state);
+/* 537 */
+EXTERN void Tcl_DiscardInterpState(Tcl_InterpState state);
+/* 538 */
+EXTERN int Tcl_SetReturnOptions(Tcl_Interp *interp,
+ Tcl_Obj *options);
+/* 539 */
+EXTERN Tcl_Obj * Tcl_GetReturnOptions(Tcl_Interp *interp, int result);
+/* 540 */
+EXTERN int Tcl_IsEnsemble(Tcl_Command token);
+/* 541 */
+EXTERN Tcl_Command Tcl_CreateEnsemble(Tcl_Interp *interp,
+ const char *name,
+ Tcl_Namespace *namespacePtr, int flags);
+/* 542 */
+EXTERN Tcl_Command Tcl_FindEnsemble(Tcl_Interp *interp,
+ Tcl_Obj *cmdNameObj, int flags);
+/* 543 */
+EXTERN int Tcl_SetEnsembleSubcommandList(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj *subcmdList);
+/* 544 */
+EXTERN int Tcl_SetEnsembleMappingDict(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj *mapDict);
+/* 545 */
+EXTERN int Tcl_SetEnsembleUnknownHandler(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj *unknownList);
+/* 546 */
+EXTERN int Tcl_SetEnsembleFlags(Tcl_Interp *interp,
+ Tcl_Command token, int flags);
+/* 547 */
+EXTERN int Tcl_GetEnsembleSubcommandList(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj **subcmdListPtr);
+/* 548 */
+EXTERN int Tcl_GetEnsembleMappingDict(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj **mapDictPtr);
+/* 549 */
+EXTERN int Tcl_GetEnsembleUnknownHandler(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj **unknownListPtr);
+/* 550 */
+EXTERN int Tcl_GetEnsembleFlags(Tcl_Interp *interp,
+ Tcl_Command token, int *flagsPtr);
+/* 551 */
+EXTERN int Tcl_GetEnsembleNamespace(Tcl_Interp *interp,
+ Tcl_Command token,
+ Tcl_Namespace **namespacePtrPtr);
+/* 552 */
+EXTERN void Tcl_SetTimeProc(Tcl_GetTimeProc *getProc,
+ Tcl_ScaleTimeProc *scaleProc,
+ ClientData clientData);
+/* 553 */
+EXTERN void Tcl_QueryTimeProc(Tcl_GetTimeProc **getProc,
+ Tcl_ScaleTimeProc **scaleProc,
+ ClientData *clientData);
+/* 554 */
+EXTERN Tcl_DriverThreadActionProc * Tcl_ChannelThreadActionProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 555 */
+EXTERN Tcl_Obj * Tcl_NewBignumObj(mp_int *value);
+/* 556 */
+EXTERN Tcl_Obj * Tcl_DbNewBignumObj(mp_int *value, const char *file,
+ int line);
+/* 557 */
+EXTERN void Tcl_SetBignumObj(Tcl_Obj *obj, mp_int *value);
+/* 558 */
+EXTERN int Tcl_GetBignumFromObj(Tcl_Interp *interp,
+ Tcl_Obj *obj, mp_int *value);
+/* 559 */
+EXTERN int Tcl_TakeBignumFromObj(Tcl_Interp *interp,
+ Tcl_Obj *obj, mp_int *value);
+/* 560 */
+EXTERN int Tcl_TruncateChannel(Tcl_Channel chan,
+ Tcl_WideInt length);
+/* 561 */
+EXTERN Tcl_DriverTruncateProc * Tcl_ChannelTruncateProc(
+ const Tcl_ChannelType *chanTypePtr);
+/* 562 */
+EXTERN void Tcl_SetChannelErrorInterp(Tcl_Interp *interp,
+ Tcl_Obj *msg);
+/* 563 */
+EXTERN void Tcl_GetChannelErrorInterp(Tcl_Interp *interp,
+ Tcl_Obj **msg);
+/* 564 */
+EXTERN void Tcl_SetChannelError(Tcl_Channel chan, Tcl_Obj *msg);
+/* 565 */
+EXTERN void Tcl_GetChannelError(Tcl_Channel chan, Tcl_Obj **msg);
+/* 566 */
+EXTERN int Tcl_InitBignumFromDouble(Tcl_Interp *interp,
+ double initval, mp_int *toInit);
+/* 567 */
+EXTERN Tcl_Obj * Tcl_GetNamespaceUnknownHandler(Tcl_Interp *interp,
+ Tcl_Namespace *nsPtr);
+/* 568 */
+EXTERN int Tcl_SetNamespaceUnknownHandler(Tcl_Interp *interp,
+ Tcl_Namespace *nsPtr, Tcl_Obj *handlerPtr);
+/* 569 */
+EXTERN int Tcl_GetEncodingFromObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, Tcl_Encoding *encodingPtr);
+/* 570 */
+EXTERN Tcl_Obj * Tcl_GetEncodingSearchPath(void);
+/* 571 */
+EXTERN int Tcl_SetEncodingSearchPath(Tcl_Obj *searchPath);
+/* 572 */
+EXTERN const char * Tcl_GetEncodingNameFromEnvironment(
+ Tcl_DString *bufPtr);
+/* 573 */
+EXTERN int Tcl_PkgRequireProc(Tcl_Interp *interp,
+ const char *name, int objc,
+ Tcl_Obj *const objv[], void *clientDataPtr);
+/* 574 */
+EXTERN void Tcl_AppendObjToErrorInfo(Tcl_Interp *interp,
+ Tcl_Obj *objPtr);
+/* 575 */
+EXTERN void Tcl_AppendLimitedToObj(Tcl_Obj *objPtr,
+ const char *bytes, int length, int limit,
+ const char *ellipsis);
+/* 576 */
+EXTERN Tcl_Obj * Tcl_Format(Tcl_Interp *interp, const char *format,
+ int objc, Tcl_Obj *const objv[]);
+/* 577 */
+EXTERN int Tcl_AppendFormatToObj(Tcl_Interp *interp,
+ Tcl_Obj *objPtr, const char *format,
+ int objc, Tcl_Obj *const objv[]);
+/* 578 */
+EXTERN Tcl_Obj * Tcl_ObjPrintf(const char *format, ...) TCL_FORMAT_PRINTF(1, 2);
+/* 579 */
+EXTERN void Tcl_AppendPrintfToObj(Tcl_Obj *objPtr,
+ const char *format, ...) TCL_FORMAT_PRINTF(2, 3);
+/* 580 */
+EXTERN int Tcl_CancelEval(Tcl_Interp *interp,
+ Tcl_Obj *resultObjPtr, ClientData clientData,
+ int flags);
+/* 581 */
+EXTERN int Tcl_Canceled(Tcl_Interp *interp, int flags);
+/* 582 */
+EXTERN int Tcl_CreatePipe(Tcl_Interp *interp,
+ Tcl_Channel *rchan, Tcl_Channel *wchan,
+ int flags);
+/* 583 */
+EXTERN Tcl_Command Tcl_NRCreateCommand(Tcl_Interp *interp,
+ const char *cmdName, Tcl_ObjCmdProc *proc,
+ Tcl_ObjCmdProc *nreProc,
+ ClientData clientData,
+ Tcl_CmdDeleteProc *deleteProc);
+/* 584 */
+EXTERN int Tcl_NREvalObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
+ int flags);
+/* 585 */
+EXTERN int Tcl_NREvalObjv(Tcl_Interp *interp, int objc,
+ Tcl_Obj *const objv[], int flags);
+/* 586 */
+EXTERN int Tcl_NRCmdSwap(Tcl_Interp *interp, Tcl_Command cmd,
+ int objc, Tcl_Obj *const objv[], int flags);
+/* 587 */
+EXTERN void Tcl_NRAddCallback(Tcl_Interp *interp,
+ Tcl_NRPostProc *postProcPtr,
+ ClientData data0, ClientData data1,
+ ClientData data2, ClientData data3);
+/* 588 */
+EXTERN int Tcl_NRCallObjProc(Tcl_Interp *interp,
+ Tcl_ObjCmdProc *objProc,
+ ClientData clientData, int objc,
+ Tcl_Obj *const objv[]);
+/* 589 */
+EXTERN unsigned Tcl_GetFSDeviceFromStat(const Tcl_StatBuf *statPtr);
+/* 590 */
+EXTERN unsigned Tcl_GetFSInodeFromStat(const Tcl_StatBuf *statPtr);
+/* 591 */
+EXTERN unsigned Tcl_GetModeFromStat(const Tcl_StatBuf *statPtr);
+/* 592 */
+EXTERN int Tcl_GetLinkCountFromStat(const Tcl_StatBuf *statPtr);
+/* 593 */
+EXTERN int Tcl_GetUserIdFromStat(const Tcl_StatBuf *statPtr);
+/* 594 */
+EXTERN int Tcl_GetGroupIdFromStat(const Tcl_StatBuf *statPtr);
+/* 595 */
+EXTERN int Tcl_GetDeviceTypeFromStat(const Tcl_StatBuf *statPtr);
+/* 596 */
+EXTERN Tcl_WideInt Tcl_GetAccessTimeFromStat(const Tcl_StatBuf *statPtr);
+/* 597 */
+EXTERN Tcl_WideInt Tcl_GetModificationTimeFromStat(
+ const Tcl_StatBuf *statPtr);
+/* 598 */
+EXTERN Tcl_WideInt Tcl_GetChangeTimeFromStat(const Tcl_StatBuf *statPtr);
+/* 599 */
+EXTERN Tcl_WideUInt Tcl_GetSizeFromStat(const Tcl_StatBuf *statPtr);
+/* 600 */
+EXTERN Tcl_WideUInt Tcl_GetBlocksFromStat(const Tcl_StatBuf *statPtr);
+/* 601 */
+EXTERN unsigned Tcl_GetBlockSizeFromStat(const Tcl_StatBuf *statPtr);
+/* 602 */
+EXTERN int Tcl_SetEnsembleParameterList(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj *paramList);
+/* 603 */
+EXTERN int Tcl_GetEnsembleParameterList(Tcl_Interp *interp,
+ Tcl_Command token, Tcl_Obj **paramListPtr);
+/* 604 */
+EXTERN int Tcl_ParseArgsObjv(Tcl_Interp *interp,
+ const Tcl_ArgvInfo *argTable, int *objcPtr,
+ Tcl_Obj *const *objv, Tcl_Obj ***remObjv);
+/* 605 */
+EXTERN int Tcl_GetErrorLine(Tcl_Interp *interp);
+/* 606 */
+EXTERN void Tcl_SetErrorLine(Tcl_Interp *interp, int lineNum);
+/* 607 */
+EXTERN void Tcl_TransferResult(Tcl_Interp *sourceInterp,
+ int result, Tcl_Interp *targetInterp);
+/* 608 */
+EXTERN int Tcl_InterpActive(Tcl_Interp *interp);
+/* 609 */
+EXTERN void Tcl_BackgroundException(Tcl_Interp *interp, int code);
+/* 610 */
+EXTERN int Tcl_ZlibDeflate(Tcl_Interp *interp, int format,
+ Tcl_Obj *data, int level,
+ Tcl_Obj *gzipHeaderDictObj);
+/* 611 */
+EXTERN int Tcl_ZlibInflate(Tcl_Interp *interp, int format,
+ Tcl_Obj *data, int buffersize,
+ Tcl_Obj *gzipHeaderDictObj);
+/* 612 */
+EXTERN unsigned int Tcl_ZlibCRC32(unsigned int crc,
+ const unsigned char *buf, int len);
+/* 613 */
+EXTERN unsigned int Tcl_ZlibAdler32(unsigned int adler,
+ const unsigned char *buf, int len);
+/* 614 */
+EXTERN int Tcl_ZlibStreamInit(Tcl_Interp *interp, int mode,
+ int format, int level, Tcl_Obj *dictObj,
+ Tcl_ZlibStream *zshandle);
+/* 615 */
+EXTERN Tcl_Obj * Tcl_ZlibStreamGetCommandName(Tcl_ZlibStream zshandle);
+/* 616 */
+EXTERN int Tcl_ZlibStreamEof(Tcl_ZlibStream zshandle);
+/* 617 */
+EXTERN int Tcl_ZlibStreamChecksum(Tcl_ZlibStream zshandle);
+/* 618 */
+EXTERN int Tcl_ZlibStreamPut(Tcl_ZlibStream zshandle,
+ Tcl_Obj *data, int flush);
+/* 619 */
+EXTERN int Tcl_ZlibStreamGet(Tcl_ZlibStream zshandle,
+ Tcl_Obj *data, int count);
+/* 620 */
+EXTERN int Tcl_ZlibStreamClose(Tcl_ZlibStream zshandle);
+/* 621 */
+EXTERN int Tcl_ZlibStreamReset(Tcl_ZlibStream zshandle);
+/* 622 */
+EXTERN void Tcl_SetStartupScript(Tcl_Obj *path,
+ const char *encoding);
+/* 623 */
+EXTERN Tcl_Obj * Tcl_GetStartupScript(const char **encodingPtr);
+/* 624 */
+EXTERN int Tcl_CloseEx(Tcl_Interp *interp, Tcl_Channel chan,
+ int flags);
+/* 625 */
+EXTERN int Tcl_NRExprObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
+ Tcl_Obj *resultPtr);
+/* 626 */
+EXTERN int Tcl_NRSubstObj(Tcl_Interp *interp, Tcl_Obj *objPtr,
+ int flags);
+/* 627 */
+EXTERN int Tcl_LoadFile(Tcl_Interp *interp, Tcl_Obj *pathPtr,
+ const char *const symv[], int flags,
+ void *procPtrs, Tcl_LoadHandle *handlePtr);
+/* 628 */
+EXTERN void * Tcl_FindSymbol(Tcl_Interp *interp,
+ Tcl_LoadHandle handle, const char *symbol);
+/* 629 */
+EXTERN int Tcl_FSUnloadFile(Tcl_Interp *interp,
+ Tcl_LoadHandle handlePtr);
+/* 630 */
+EXTERN void Tcl_ZlibStreamSetCompressionDictionary(
+ Tcl_ZlibStream zhandle,
+ Tcl_Obj *compressionDictionaryObj);
+
+typedef struct {
+ const struct TclPlatStubs *tclPlatStubs;
+ const struct TclIntStubs *tclIntStubs;
+ const struct TclIntPlatStubs *tclIntPlatStubs;
+} TclStubHooks;
+
+typedef struct TclStubs {
+ int magic;
+ const TclStubHooks *hooks;
+
+ int (*tcl_PkgProvideEx) (Tcl_Interp *interp, const char *name, const char *version, const void *clientData); /* 0 */
+ CONST84_RETURN char * (*tcl_PkgRequireEx) (Tcl_Interp *interp, const char *name, const char *version, int exact, void *clientDataPtr); /* 1 */
+ void (*tcl_Panic) (const char *format, ...) TCL_FORMAT_PRINTF(1, 2); /* 2 */
+ char * (*tcl_Alloc) (unsigned int size); /* 3 */
+ void (*tcl_Free) (char *ptr); /* 4 */
+ char * (*tcl_Realloc) (char *ptr, unsigned int size); /* 5 */
+ char * (*tcl_DbCkalloc) (unsigned int size, const char *file, int line); /* 6 */
+ void (*tcl_DbCkfree) (char *ptr, const char *file, int line); /* 7 */
+ char * (*tcl_DbCkrealloc) (char *ptr, unsigned int size, const char *file, int line); /* 8 */
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+ void (*tcl_CreateFileHandler) (int fd, int mask, Tcl_FileProc *proc, ClientData clientData); /* 9 */
+#endif /* UNIX */
+#if defined(__WIN32__) /* WIN */
+ void (*reserved9)(void);
+#endif /* WIN */
+#ifdef MAC_OSX_TCL /* MACOSX */
+ void (*tcl_CreateFileHandler) (int fd, int mask, Tcl_FileProc *proc, ClientData clientData); /* 9 */
+#endif /* MACOSX */
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+ void (*tcl_DeleteFileHandler) (int fd); /* 10 */
+#endif /* UNIX */
+#if defined(__WIN32__) /* WIN */
+ void (*reserved10)(void);
+#endif /* WIN */
+#ifdef MAC_OSX_TCL /* MACOSX */
+ void (*tcl_DeleteFileHandler) (int fd); /* 10 */
+#endif /* MACOSX */
+ void (*tcl_SetTimer) (const Tcl_Time *timePtr); /* 11 */
+ void (*tcl_Sleep) (int ms); /* 12 */
+ int (*tcl_WaitForEvent) (const Tcl_Time *timePtr); /* 13 */
+ int (*tcl_AppendAllObjTypes) (Tcl_Interp *interp, Tcl_Obj *objPtr); /* 14 */
+ void (*tcl_AppendStringsToObj) (Tcl_Obj *objPtr, ...); /* 15 */
+ void (*tcl_AppendToObj) (Tcl_Obj *objPtr, const char *bytes, int length); /* 16 */
+ Tcl_Obj * (*tcl_ConcatObj) (int objc, Tcl_Obj *const objv[]); /* 17 */
+ int (*tcl_ConvertToType) (Tcl_Interp *interp, Tcl_Obj *objPtr, const Tcl_ObjType *typePtr); /* 18 */
+ void (*tcl_DbDecrRefCount) (Tcl_Obj *objPtr, const char *file, int line); /* 19 */
+ void (*tcl_DbIncrRefCount) (Tcl_Obj *objPtr, const char *file, int line); /* 20 */
+ int (*tcl_DbIsShared) (Tcl_Obj *objPtr, const char *file, int line); /* 21 */
+ Tcl_Obj * (*tcl_DbNewBooleanObj) (int boolValue, const char *file, int line); /* 22 */
+ Tcl_Obj * (*tcl_DbNewByteArrayObj) (const unsigned char *bytes, int length, const char *file, int line); /* 23 */
+ Tcl_Obj * (*tcl_DbNewDoubleObj) (double doubleValue, const char *file, int line); /* 24 */
+ Tcl_Obj * (*tcl_DbNewListObj) (int objc, Tcl_Obj *const *objv, const char *file, int line); /* 25 */
+ Tcl_Obj * (*tcl_DbNewLongObj) (long longValue, const char *file, int line); /* 26 */
+ Tcl_Obj * (*tcl_DbNewObj) (const char *file, int line); /* 27 */
+ Tcl_Obj * (*tcl_DbNewStringObj) (const char *bytes, int length, const char *file, int line); /* 28 */
+ Tcl_Obj * (*tcl_DuplicateObj) (Tcl_Obj *objPtr); /* 29 */
+ void (*tclFreeObj) (Tcl_Obj *objPtr); /* 30 */
+ int (*tcl_GetBoolean) (Tcl_Interp *interp, const char *src, int *boolPtr); /* 31 */
+ int (*tcl_GetBooleanFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, int *boolPtr); /* 32 */
+ unsigned char * (*tcl_GetByteArrayFromObj) (Tcl_Obj *objPtr, int *lengthPtr); /* 33 */
+ int (*tcl_GetDouble) (Tcl_Interp *interp, const char *src, double *doublePtr); /* 34 */
+ int (*tcl_GetDoubleFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, double *doublePtr); /* 35 */
+ int (*tcl_GetIndexFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, CONST84 char *const *tablePtr, const char *msg, int flags, int *indexPtr); /* 36 */
+ int (*tcl_GetInt) (Tcl_Interp *interp, const char *src, int *intPtr); /* 37 */
+ int (*tcl_GetIntFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, int *intPtr); /* 38 */
+ int (*tcl_GetLongFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, long *longPtr); /* 39 */
+ CONST86 Tcl_ObjType * (*tcl_GetObjType) (const char *typeName); /* 40 */
+ char * (*tcl_GetStringFromObj) (Tcl_Obj *objPtr, int *lengthPtr); /* 41 */
+ void (*tcl_InvalidateStringRep) (Tcl_Obj *objPtr); /* 42 */
+ int (*tcl_ListObjAppendList) (Tcl_Interp *interp, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr); /* 43 */
+ int (*tcl_ListObjAppendElement) (Tcl_Interp *interp, Tcl_Obj *listPtr, Tcl_Obj *objPtr); /* 44 */
+ int (*tcl_ListObjGetElements) (Tcl_Interp *interp, Tcl_Obj *listPtr, int *objcPtr, Tcl_Obj ***objvPtr); /* 45 */
+ int (*tcl_ListObjIndex) (Tcl_Interp *interp, Tcl_Obj *listPtr, int index, Tcl_Obj **objPtrPtr); /* 46 */
+ int (*tcl_ListObjLength) (Tcl_Interp *interp, Tcl_Obj *listPtr, int *lengthPtr); /* 47 */
+ int (*tcl_ListObjReplace) (Tcl_Interp *interp, Tcl_Obj *listPtr, int first, int count, int objc, Tcl_Obj *const objv[]); /* 48 */
+ Tcl_Obj * (*tcl_NewBooleanObj) (int boolValue); /* 49 */
+ Tcl_Obj * (*tcl_NewByteArrayObj) (const unsigned char *bytes, int length); /* 50 */
+ Tcl_Obj * (*tcl_NewDoubleObj) (double doubleValue); /* 51 */
+ Tcl_Obj * (*tcl_NewIntObj) (int intValue); /* 52 */
+ Tcl_Obj * (*tcl_NewListObj) (int objc, Tcl_Obj *const objv[]); /* 53 */
+ Tcl_Obj * (*tcl_NewLongObj) (long longValue); /* 54 */
+ Tcl_Obj * (*tcl_NewObj) (void); /* 55 */
+ Tcl_Obj * (*tcl_NewStringObj) (const char *bytes, int length); /* 56 */
+ void (*tcl_SetBooleanObj) (Tcl_Obj *objPtr, int boolValue); /* 57 */
+ unsigned char * (*tcl_SetByteArrayLength) (Tcl_Obj *objPtr, int length); /* 58 */
+ void (*tcl_SetByteArrayObj) (Tcl_Obj *objPtr, const unsigned char *bytes, int length); /* 59 */
+ void (*tcl_SetDoubleObj) (Tcl_Obj *objPtr, double doubleValue); /* 60 */
+ void (*tcl_SetIntObj) (Tcl_Obj *objPtr, int intValue); /* 61 */
+ void (*tcl_SetListObj) (Tcl_Obj *objPtr, int objc, Tcl_Obj *const objv[]); /* 62 */
+ void (*tcl_SetLongObj) (Tcl_Obj *objPtr, long longValue); /* 63 */
+ void (*tcl_SetObjLength) (Tcl_Obj *objPtr, int length); /* 64 */
+ void (*tcl_SetStringObj) (Tcl_Obj *objPtr, const char *bytes, int length); /* 65 */
+ void (*tcl_AddErrorInfo) (Tcl_Interp *interp, const char *message); /* 66 */
+ void (*tcl_AddObjErrorInfo) (Tcl_Interp *interp, const char *message, int length); /* 67 */
+ void (*tcl_AllowExceptions) (Tcl_Interp *interp); /* 68 */
+ void (*tcl_AppendElement) (Tcl_Interp *interp, const char *element); /* 69 */
+ void (*tcl_AppendResult) (Tcl_Interp *interp, ...); /* 70 */
+ Tcl_AsyncHandler (*tcl_AsyncCreate) (Tcl_AsyncProc *proc, ClientData clientData); /* 71 */
+ void (*tcl_AsyncDelete) (Tcl_AsyncHandler async); /* 72 */
+ int (*tcl_AsyncInvoke) (Tcl_Interp *interp, int code); /* 73 */
+ void (*tcl_AsyncMark) (Tcl_AsyncHandler async); /* 74 */
+ int (*tcl_AsyncReady) (void); /* 75 */
+ void (*tcl_BackgroundError) (Tcl_Interp *interp); /* 76 */
+ char (*tcl_Backslash) (const char *src, int *readPtr); /* 77 */
+ int (*tcl_BadChannelOption) (Tcl_Interp *interp, const char *optionName, const char *optionList); /* 78 */
+ void (*tcl_CallWhenDeleted) (Tcl_Interp *interp, Tcl_InterpDeleteProc *proc, ClientData clientData); /* 79 */
+ void (*tcl_CancelIdleCall) (Tcl_IdleProc *idleProc, ClientData clientData); /* 80 */
+ int (*tcl_Close) (Tcl_Interp *interp, Tcl_Channel chan); /* 81 */
+ int (*tcl_CommandComplete) (const char *cmd); /* 82 */
+ char * (*tcl_Concat) (int argc, CONST84 char *const *argv); /* 83 */
+ int (*tcl_ConvertElement) (const char *src, char *dst, int flags); /* 84 */
+ int (*tcl_ConvertCountedElement) (const char *src, int length, char *dst, int flags); /* 85 */
+ int (*tcl_CreateAlias) (Tcl_Interp *slave, const char *slaveCmd, Tcl_Interp *target, const char *targetCmd, int argc, CONST84 char *const *argv); /* 86 */
+ int (*tcl_CreateAliasObj) (Tcl_Interp *slave, const char *slaveCmd, Tcl_Interp *target, const char *targetCmd, int objc, Tcl_Obj *const objv[]); /* 87 */
+ Tcl_Channel (*tcl_CreateChannel) (const Tcl_ChannelType *typePtr, const char *chanName, ClientData instanceData, int mask); /* 88 */
+ void (*tcl_CreateChannelHandler) (Tcl_Channel chan, int mask, Tcl_ChannelProc *proc, ClientData clientData); /* 89 */
+ void (*tcl_CreateCloseHandler) (Tcl_Channel chan, Tcl_CloseProc *proc, ClientData clientData); /* 90 */
+ Tcl_Command (*tcl_CreateCommand) (Tcl_Interp *interp, const char *cmdName, Tcl_CmdProc *proc, ClientData clientData, Tcl_CmdDeleteProc *deleteProc); /* 91 */
+ void (*tcl_CreateEventSource) (Tcl_EventSetupProc *setupProc, Tcl_EventCheckProc *checkProc, ClientData clientData); /* 92 */
+ void (*tcl_CreateExitHandler) (Tcl_ExitProc *proc, ClientData clientData); /* 93 */
+ Tcl_Interp * (*tcl_CreateInterp) (void); /* 94 */
+ void (*tcl_CreateMathFunc) (Tcl_Interp *interp, const char *name, int numArgs, Tcl_ValueType *argTypes, Tcl_MathProc *proc, ClientData clientData); /* 95 */
+ Tcl_Command (*tcl_CreateObjCommand) (Tcl_Interp *interp, const char *cmdName, Tcl_ObjCmdProc *proc, ClientData clientData, Tcl_CmdDeleteProc *deleteProc); /* 96 */
+ Tcl_Interp * (*tcl_CreateSlave) (Tcl_Interp *interp, const char *slaveName, int isSafe); /* 97 */
+ Tcl_TimerToken (*tcl_CreateTimerHandler) (int milliseconds, Tcl_TimerProc *proc, ClientData clientData); /* 98 */
+ Tcl_Trace (*tcl_CreateTrace) (Tcl_Interp *interp, int level, Tcl_CmdTraceProc *proc, ClientData clientData); /* 99 */
+ void (*tcl_DeleteAssocData) (Tcl_Interp *interp, const char *name); /* 100 */
+ void (*tcl_DeleteChannelHandler) (Tcl_Channel chan, Tcl_ChannelProc *proc, ClientData clientData); /* 101 */
+ void (*tcl_DeleteCloseHandler) (Tcl_Channel chan, Tcl_CloseProc *proc, ClientData clientData); /* 102 */
+ int (*tcl_DeleteCommand) (Tcl_Interp *interp, const char *cmdName); /* 103 */
+ int (*tcl_DeleteCommandFromToken) (Tcl_Interp *interp, Tcl_Command command); /* 104 */
+ void (*tcl_DeleteEvents) (Tcl_EventDeleteProc *proc, ClientData clientData); /* 105 */
+ void (*tcl_DeleteEventSource) (Tcl_EventSetupProc *setupProc, Tcl_EventCheckProc *checkProc, ClientData clientData); /* 106 */
+ void (*tcl_DeleteExitHandler) (Tcl_ExitProc *proc, ClientData clientData); /* 107 */
+ void (*tcl_DeleteHashEntry) (Tcl_HashEntry *entryPtr); /* 108 */
+ void (*tcl_DeleteHashTable) (Tcl_HashTable *tablePtr); /* 109 */
+ void (*tcl_DeleteInterp) (Tcl_Interp *interp); /* 110 */
+ void (*tcl_DetachPids) (int numPids, Tcl_Pid *pidPtr); /* 111 */
+ void (*tcl_DeleteTimerHandler) (Tcl_TimerToken token); /* 112 */
+ void (*tcl_DeleteTrace) (Tcl_Interp *interp, Tcl_Trace trace); /* 113 */
+ void (*tcl_DontCallWhenDeleted) (Tcl_Interp *interp, Tcl_InterpDeleteProc *proc, ClientData clientData); /* 114 */
+ int (*tcl_DoOneEvent) (int flags); /* 115 */
+ void (*tcl_DoWhenIdle) (Tcl_IdleProc *proc, ClientData clientData); /* 116 */
+ char * (*tcl_DStringAppend) (Tcl_DString *dsPtr, const char *bytes, int length); /* 117 */
+ char * (*tcl_DStringAppendElement) (Tcl_DString *dsPtr, const char *element); /* 118 */
+ void (*tcl_DStringEndSublist) (Tcl_DString *dsPtr); /* 119 */
+ void (*tcl_DStringFree) (Tcl_DString *dsPtr); /* 120 */
+ void (*tcl_DStringGetResult) (Tcl_Interp *interp, Tcl_DString *dsPtr); /* 121 */
+ void (*tcl_DStringInit) (Tcl_DString *dsPtr); /* 122 */
+ void (*tcl_DStringResult) (Tcl_Interp *interp, Tcl_DString *dsPtr); /* 123 */
+ void (*tcl_DStringSetLength) (Tcl_DString *dsPtr, int length); /* 124 */
+ void (*tcl_DStringStartSublist) (Tcl_DString *dsPtr); /* 125 */
+ int (*tcl_Eof) (Tcl_Channel chan); /* 126 */
+ CONST84_RETURN char * (*tcl_ErrnoId) (void); /* 127 */
+ CONST84_RETURN char * (*tcl_ErrnoMsg) (int err); /* 128 */
+ int (*tcl_Eval) (Tcl_Interp *interp, const char *script); /* 129 */
+ int (*tcl_EvalFile) (Tcl_Interp *interp, const char *fileName); /* 130 */
+ int (*tcl_EvalObj) (Tcl_Interp *interp, Tcl_Obj *objPtr); /* 131 */
+ void (*tcl_EventuallyFree) (ClientData clientData, Tcl_FreeProc *freeProc); /* 132 */
+ void (*tcl_Exit) (int status); /* 133 */
+ int (*tcl_ExposeCommand) (Tcl_Interp *interp, const char *hiddenCmdToken, const char *cmdName); /* 134 */
+ int (*tcl_ExprBoolean) (Tcl_Interp *interp, const char *expr, int *ptr); /* 135 */
+ int (*tcl_ExprBooleanObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, int *ptr); /* 136 */
+ int (*tcl_ExprDouble) (Tcl_Interp *interp, const char *expr, double *ptr); /* 137 */
+ int (*tcl_ExprDoubleObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, double *ptr); /* 138 */
+ int (*tcl_ExprLong) (Tcl_Interp *interp, const char *expr, long *ptr); /* 139 */
+ int (*tcl_ExprLongObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, long *ptr); /* 140 */
+ int (*tcl_ExprObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, Tcl_Obj **resultPtrPtr); /* 141 */
+ int (*tcl_ExprString) (Tcl_Interp *interp, const char *expr); /* 142 */
+ void (*tcl_Finalize) (void); /* 143 */
+ void (*tcl_FindExecutable) (const char *argv0); /* 144 */
+ Tcl_HashEntry * (*tcl_FirstHashEntry) (Tcl_HashTable *tablePtr, Tcl_HashSearch *searchPtr); /* 145 */
+ int (*tcl_Flush) (Tcl_Channel chan); /* 146 */
+ void (*tcl_FreeResult) (Tcl_Interp *interp); /* 147 */
+ int (*tcl_GetAlias) (Tcl_Interp *interp, const char *slaveCmd, Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr, int *argcPtr, CONST84 char ***argvPtr); /* 148 */
+ int (*tcl_GetAliasObj) (Tcl_Interp *interp, const char *slaveCmd, Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr, int *objcPtr, Tcl_Obj ***objv); /* 149 */
+ ClientData (*tcl_GetAssocData) (Tcl_Interp *interp, const char *name, Tcl_InterpDeleteProc **procPtr); /* 150 */
+ Tcl_Channel (*tcl_GetChannel) (Tcl_Interp *interp, const char *chanName, int *modePtr); /* 151 */
+ int (*tcl_GetChannelBufferSize) (Tcl_Channel chan); /* 152 */
+ int (*tcl_GetChannelHandle) (Tcl_Channel chan, int direction, ClientData *handlePtr); /* 153 */
+ ClientData (*tcl_GetChannelInstanceData) (Tcl_Channel chan); /* 154 */
+ int (*tcl_GetChannelMode) (Tcl_Channel chan); /* 155 */
+ CONST84_RETURN char * (*tcl_GetChannelName) (Tcl_Channel chan); /* 156 */
+ int (*tcl_GetChannelOption) (Tcl_Interp *interp, Tcl_Channel chan, const char *optionName, Tcl_DString *dsPtr); /* 157 */
+ CONST86 Tcl_ChannelType * (*tcl_GetChannelType) (Tcl_Channel chan); /* 158 */
+ int (*tcl_GetCommandInfo) (Tcl_Interp *interp, const char *cmdName, Tcl_CmdInfo *infoPtr); /* 159 */
+ CONST84_RETURN char * (*tcl_GetCommandName) (Tcl_Interp *interp, Tcl_Command command); /* 160 */
+ int (*tcl_GetErrno) (void); /* 161 */
+ CONST84_RETURN char * (*tcl_GetHostName) (void); /* 162 */
+ int (*tcl_GetInterpPath) (Tcl_Interp *askInterp, Tcl_Interp *slaveInterp); /* 163 */
+ Tcl_Interp * (*tcl_GetMaster) (Tcl_Interp *interp); /* 164 */
+ const char * (*tcl_GetNameOfExecutable) (void); /* 165 */
+ Tcl_Obj * (*tcl_GetObjResult) (Tcl_Interp *interp); /* 166 */
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+ int (*tcl_GetOpenFile) (Tcl_Interp *interp, const char *chanID, int forWriting, int checkUsage, ClientData *filePtr); /* 167 */
+#endif /* UNIX */
+#if defined(__WIN32__) /* WIN */
+ void (*reserved167)(void);
+#endif /* WIN */
+#ifdef MAC_OSX_TCL /* MACOSX */
+ int (*tcl_GetOpenFile) (Tcl_Interp *interp, const char *chanID, int forWriting, int checkUsage, ClientData *filePtr); /* 167 */
+#endif /* MACOSX */
+ Tcl_PathType (*tcl_GetPathType) (const char *path); /* 168 */
+ int (*tcl_Gets) (Tcl_Channel chan, Tcl_DString *dsPtr); /* 169 */
+ int (*tcl_GetsObj) (Tcl_Channel chan, Tcl_Obj *objPtr); /* 170 */
+ int (*tcl_GetServiceMode) (void); /* 171 */
+ Tcl_Interp * (*tcl_GetSlave) (Tcl_Interp *interp, const char *slaveName); /* 172 */
+ Tcl_Channel (*tcl_GetStdChannel) (int type); /* 173 */
+ CONST84_RETURN char * (*tcl_GetStringResult) (Tcl_Interp *interp); /* 174 */
+ CONST84_RETURN char * (*tcl_GetVar) (Tcl_Interp *interp, const char *varName, int flags); /* 175 */
+ CONST84_RETURN char * (*tcl_GetVar2) (Tcl_Interp *interp, const char *part1, const char *part2, int flags); /* 176 */
+ int (*tcl_GlobalEval) (Tcl_Interp *interp, const char *command); /* 177 */
+ int (*tcl_GlobalEvalObj) (Tcl_Interp *interp, Tcl_Obj *objPtr); /* 178 */
+ int (*tcl_HideCommand) (Tcl_Interp *interp, const char *cmdName, const char *hiddenCmdToken); /* 179 */
+ int (*tcl_Init) (Tcl_Interp *interp); /* 180 */
+ void (*tcl_InitHashTable) (Tcl_HashTable *tablePtr, int keyType); /* 181 */
+ int (*tcl_InputBlocked) (Tcl_Channel chan); /* 182 */
+ int (*tcl_InputBuffered) (Tcl_Channel chan); /* 183 */
+ int (*tcl_InterpDeleted) (Tcl_Interp *interp); /* 184 */
+ int (*tcl_IsSafe) (Tcl_Interp *interp); /* 185 */
+ char * (*tcl_JoinPath) (int argc, CONST84 char *const *argv, Tcl_DString *resultPtr); /* 186 */
+ int (*tcl_LinkVar) (Tcl_Interp *interp, const char *varName, char *addr, int type); /* 187 */
+ void (*reserved188)(void);
+ Tcl_Channel (*tcl_MakeFileChannel) (ClientData handle, int mode); /* 189 */
+ int (*tcl_MakeSafe) (Tcl_Interp *interp); /* 190 */
+ Tcl_Channel (*tcl_MakeTcpClientChannel) (ClientData tcpSocket); /* 191 */
+ char * (*tcl_Merge) (int argc, CONST84 char *const *argv); /* 192 */
+ Tcl_HashEntry * (*tcl_NextHashEntry) (Tcl_HashSearch *searchPtr); /* 193 */
+ void (*tcl_NotifyChannel) (Tcl_Channel channel, int mask); /* 194 */
+ Tcl_Obj * (*tcl_ObjGetVar2) (Tcl_Interp *interp, Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, int flags); /* 195 */
+ Tcl_Obj * (*tcl_ObjSetVar2) (Tcl_Interp *interp, Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, Tcl_Obj *newValuePtr, int flags); /* 196 */
+ Tcl_Channel (*tcl_OpenCommandChannel) (Tcl_Interp *interp, int argc, CONST84 char **argv, int flags); /* 197 */
+ Tcl_Channel (*tcl_OpenFileChannel) (Tcl_Interp *interp, const char *fileName, const char *modeString, int permissions); /* 198 */
+ Tcl_Channel (*tcl_OpenTcpClient) (Tcl_Interp *interp, int port, const char *address, const char *myaddr, int myport, int async); /* 199 */
+ Tcl_Channel (*tcl_OpenTcpServer) (Tcl_Interp *interp, int port, const char *host, Tcl_TcpAcceptProc *acceptProc, ClientData callbackData); /* 200 */
+ void (*tcl_Preserve) (ClientData data); /* 201 */
+ void (*tcl_PrintDouble) (Tcl_Interp *interp, double value, char *dst); /* 202 */
+ int (*tcl_PutEnv) (const char *assignment); /* 203 */
+ CONST84_RETURN char * (*tcl_PosixError) (Tcl_Interp *interp); /* 204 */
+ void (*tcl_QueueEvent) (Tcl_Event *evPtr, Tcl_QueuePosition position); /* 205 */
+ int (*tcl_Read) (Tcl_Channel chan, char *bufPtr, int toRead); /* 206 */
+ void (*tcl_ReapDetachedProcs) (void); /* 207 */
+ int (*tcl_RecordAndEval) (Tcl_Interp *interp, const char *cmd, int flags); /* 208 */
+ int (*tcl_RecordAndEvalObj) (Tcl_Interp *interp, Tcl_Obj *cmdPtr, int flags); /* 209 */
+ void (*tcl_RegisterChannel) (Tcl_Interp *interp, Tcl_Channel chan); /* 210 */
+ void (*tcl_RegisterObjType) (const Tcl_ObjType *typePtr); /* 211 */
+ Tcl_RegExp (*tcl_RegExpCompile) (Tcl_Interp *interp, const char *pattern); /* 212 */
+ int (*tcl_RegExpExec) (Tcl_Interp *interp, Tcl_RegExp regexp, const char *text, const char *start); /* 213 */
+ int (*tcl_RegExpMatch) (Tcl_Interp *interp, const char *text, const char *pattern); /* 214 */
+ void (*tcl_RegExpRange) (Tcl_RegExp regexp, int index, CONST84 char **startPtr, CONST84 char **endPtr); /* 215 */
+ void (*tcl_Release) (ClientData clientData); /* 216 */
+ void (*tcl_ResetResult) (Tcl_Interp *interp); /* 217 */
+ int (*tcl_ScanElement) (const char *src, int *flagPtr); /* 218 */
+ int (*tcl_ScanCountedElement) (const char *src, int length, int *flagPtr); /* 219 */
+ int (*tcl_SeekOld) (Tcl_Channel chan, int offset, int mode); /* 220 */
+ int (*tcl_ServiceAll) (void); /* 221 */
+ int (*tcl_ServiceEvent) (int flags); /* 222 */
+ void (*tcl_SetAssocData) (Tcl_Interp *interp, const char *name, Tcl_InterpDeleteProc *proc, ClientData clientData); /* 223 */
+ void (*tcl_SetChannelBufferSize) (Tcl_Channel chan, int sz); /* 224 */
+ int (*tcl_SetChannelOption) (Tcl_Interp *interp, Tcl_Channel chan, const char *optionName, const char *newValue); /* 225 */
+ int (*tcl_SetCommandInfo) (Tcl_Interp *interp, const char *cmdName, const Tcl_CmdInfo *infoPtr); /* 226 */
+ void (*tcl_SetErrno) (int err); /* 227 */
+ void (*tcl_SetErrorCode) (Tcl_Interp *interp, ...); /* 228 */
+ void (*tcl_SetMaxBlockTime) (const Tcl_Time *timePtr); /* 229 */
+ void (*tcl_SetPanicProc) (Tcl_PanicProc *panicProc); /* 230 */
+ int (*tcl_SetRecursionLimit) (Tcl_Interp *interp, int depth); /* 231 */
+ void (*tcl_SetResult) (Tcl_Interp *interp, char *result, Tcl_FreeProc *freeProc); /* 232 */
+ int (*tcl_SetServiceMode) (int mode); /* 233 */
+ void (*tcl_SetObjErrorCode) (Tcl_Interp *interp, Tcl_Obj *errorObjPtr); /* 234 */
+ void (*tcl_SetObjResult) (Tcl_Interp *interp, Tcl_Obj *resultObjPtr); /* 235 */
+ void (*tcl_SetStdChannel) (Tcl_Channel channel, int type); /* 236 */
+ CONST84_RETURN char * (*tcl_SetVar) (Tcl_Interp *interp, const char *varName, const char *newValue, int flags); /* 237 */
+ CONST84_RETURN char * (*tcl_SetVar2) (Tcl_Interp *interp, const char *part1, const char *part2, const char *newValue, int flags); /* 238 */
+ CONST84_RETURN char * (*tcl_SignalId) (int sig); /* 239 */
+ CONST84_RETURN char * (*tcl_SignalMsg) (int sig); /* 240 */
+ void (*tcl_SourceRCFile) (Tcl_Interp *interp); /* 241 */
+ int (*tcl_SplitList) (Tcl_Interp *interp, const char *listStr, int *argcPtr, CONST84 char ***argvPtr); /* 242 */
+ void (*tcl_SplitPath) (const char *path, int *argcPtr, CONST84 char ***argvPtr); /* 243 */
+ void (*tcl_StaticPackage) (Tcl_Interp *interp, const char *pkgName, Tcl_PackageInitProc *initProc, Tcl_PackageInitProc *safeInitProc); /* 244 */
+ int (*tcl_StringMatch) (const char *str, const char *pattern); /* 245 */
+ int (*tcl_TellOld) (Tcl_Channel chan); /* 246 */
+ int (*tcl_TraceVar) (Tcl_Interp *interp, const char *varName, int flags, Tcl_VarTraceProc *proc, ClientData clientData); /* 247 */
+ int (*tcl_TraceVar2) (Tcl_Interp *interp, const char *part1, const char *part2, int flags, Tcl_VarTraceProc *proc, ClientData clientData); /* 248 */
+ char * (*tcl_TranslateFileName) (Tcl_Interp *interp, const char *name, Tcl_DString *bufferPtr); /* 249 */
+ int (*tcl_Ungets) (Tcl_Channel chan, const char *str, int len, int atHead); /* 250 */
+ void (*tcl_UnlinkVar) (Tcl_Interp *interp, const char *varName); /* 251 */
+ int (*tcl_UnregisterChannel) (Tcl_Interp *interp, Tcl_Channel chan); /* 252 */
+ int (*tcl_UnsetVar) (Tcl_Interp *interp, const char *varName, int flags); /* 253 */
+ int (*tcl_UnsetVar2) (Tcl_Interp *interp, const char *part1, const char *part2, int flags); /* 254 */
+ void (*tcl_UntraceVar) (Tcl_Interp *interp, const char *varName, int flags, Tcl_VarTraceProc *proc, ClientData clientData); /* 255 */
+ void (*tcl_UntraceVar2) (Tcl_Interp *interp, const char *part1, const char *part2, int flags, Tcl_VarTraceProc *proc, ClientData clientData); /* 256 */
+ void (*tcl_UpdateLinkedVar) (Tcl_Interp *interp, const char *varName); /* 257 */
+ int (*tcl_UpVar) (Tcl_Interp *interp, const char *frameName, const char *varName, const char *localName, int flags); /* 258 */
+ int (*tcl_UpVar2) (Tcl_Interp *interp, const char *frameName, const char *part1, const char *part2, const char *localName, int flags); /* 259 */
+ int (*tcl_VarEval) (Tcl_Interp *interp, ...); /* 260 */
+ ClientData (*tcl_VarTraceInfo) (Tcl_Interp *interp, const char *varName, int flags, Tcl_VarTraceProc *procPtr, ClientData prevClientData); /* 261 */
+ ClientData (*tcl_VarTraceInfo2) (Tcl_Interp *interp, const char *part1, const char *part2, int flags, Tcl_VarTraceProc *procPtr, ClientData prevClientData); /* 262 */
+ int (*tcl_Write) (Tcl_Channel chan, const char *s, int slen); /* 263 */
+ void (*tcl_WrongNumArgs) (Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], const char *message); /* 264 */
+ int (*tcl_DumpActiveMemory) (const char *fileName); /* 265 */
+ void (*tcl_ValidateAllMemory) (const char *file, int line); /* 266 */
+ void (*tcl_AppendResultVA) (Tcl_Interp *interp, va_list argList); /* 267 */
+ void (*tcl_AppendStringsToObjVA) (Tcl_Obj *objPtr, va_list argList); /* 268 */
+ char * (*tcl_HashStats) (Tcl_HashTable *tablePtr); /* 269 */
+ CONST84_RETURN char * (*tcl_ParseVar) (Tcl_Interp *interp, const char *start, CONST84 char **termPtr); /* 270 */
+ CONST84_RETURN char * (*tcl_PkgPresent) (Tcl_Interp *interp, const char *name, const char *version, int exact); /* 271 */
+ CONST84_RETURN char * (*tcl_PkgPresentEx) (Tcl_Interp *interp, const char *name, const char *version, int exact, void *clientDataPtr); /* 272 */
+ int (*tcl_PkgProvide) (Tcl_Interp *interp, const char *name, const char *version); /* 273 */
+ CONST84_RETURN char * (*tcl_PkgRequire) (Tcl_Interp *interp, const char *name, const char *version, int exact); /* 274 */
+ void (*tcl_SetErrorCodeVA) (Tcl_Interp *interp, va_list argList); /* 275 */
+ int (*tcl_VarEvalVA) (Tcl_Interp *interp, va_list argList); /* 276 */
+ Tcl_Pid (*tcl_WaitPid) (Tcl_Pid pid, int *statPtr, int options); /* 277 */
+ void (*tcl_PanicVA) (const char *format, va_list argList); /* 278 */
+ void (*tcl_GetVersion) (int *major, int *minor, int *patchLevel, int *type); /* 279 */
+ void (*tcl_InitMemory) (Tcl_Interp *interp); /* 280 */
+ Tcl_Channel (*tcl_StackChannel) (Tcl_Interp *interp, const Tcl_ChannelType *typePtr, ClientData instanceData, int mask, Tcl_Channel prevChan); /* 281 */
+ int (*tcl_UnstackChannel) (Tcl_Interp *interp, Tcl_Channel chan); /* 282 */
+ Tcl_Channel (*tcl_GetStackedChannel) (Tcl_Channel chan); /* 283 */
+ void (*tcl_SetMainLoop) (Tcl_MainLoopProc *proc); /* 284 */
+ void (*reserved285)(void);
+ void (*tcl_AppendObjToObj) (Tcl_Obj *objPtr, Tcl_Obj *appendObjPtr); /* 286 */
+ Tcl_Encoding (*tcl_CreateEncoding) (const Tcl_EncodingType *typePtr); /* 287 */
+ void (*tcl_CreateThreadExitHandler) (Tcl_ExitProc *proc, ClientData clientData); /* 288 */
+ void (*tcl_DeleteThreadExitHandler) (Tcl_ExitProc *proc, ClientData clientData); /* 289 */
+ void (*tcl_DiscardResult) (Tcl_SavedResult *statePtr); /* 290 */
+ int (*tcl_EvalEx) (Tcl_Interp *interp, const char *script, int numBytes, int flags); /* 291 */
+ int (*tcl_EvalObjv) (Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], int flags); /* 292 */
+ int (*tcl_EvalObjEx) (Tcl_Interp *interp, Tcl_Obj *objPtr, int flags); /* 293 */
+ void (*tcl_ExitThread) (int status); /* 294 */
+ int (*tcl_ExternalToUtf) (Tcl_Interp *interp, Tcl_Encoding encoding, const char *src, int srcLen, int flags, Tcl_EncodingState *statePtr, char *dst, int dstLen, int *srcReadPtr, int *dstWrotePtr, int *dstCharsPtr); /* 295 */
+ char * (*tcl_ExternalToUtfDString) (Tcl_Encoding encoding, const char *src, int srcLen, Tcl_DString *dsPtr); /* 296 */
+ void (*tcl_FinalizeThread) (void); /* 297 */
+ void (*tcl_FinalizeNotifier) (ClientData clientData); /* 298 */
+ void (*tcl_FreeEncoding) (Tcl_Encoding encoding); /* 299 */
+ Tcl_ThreadId (*tcl_GetCurrentThread) (void); /* 300 */
+ Tcl_Encoding (*tcl_GetEncoding) (Tcl_Interp *interp, const char *name); /* 301 */
+ CONST84_RETURN char * (*tcl_GetEncodingName) (Tcl_Encoding encoding); /* 302 */
+ void (*tcl_GetEncodingNames) (Tcl_Interp *interp); /* 303 */
+ int (*tcl_GetIndexFromObjStruct) (Tcl_Interp *interp, Tcl_Obj *objPtr, const void *tablePtr, int offset, const char *msg, int flags, int *indexPtr); /* 304 */
+ void * (*tcl_GetThreadData) (Tcl_ThreadDataKey *keyPtr, int size); /* 305 */
+ Tcl_Obj * (*tcl_GetVar2Ex) (Tcl_Interp *interp, const char *part1, const char *part2, int flags); /* 306 */
+ ClientData (*tcl_InitNotifier) (void); /* 307 */
+ void (*tcl_MutexLock) (Tcl_Mutex *mutexPtr); /* 308 */
+ void (*tcl_MutexUnlock) (Tcl_Mutex *mutexPtr); /* 309 */
+ void (*tcl_ConditionNotify) (Tcl_Condition *condPtr); /* 310 */
+ void (*tcl_ConditionWait) (Tcl_Condition *condPtr, Tcl_Mutex *mutexPtr, const Tcl_Time *timePtr); /* 311 */
+ int (*tcl_NumUtfChars) (const char *src, int length); /* 312 */
+ int (*tcl_ReadChars) (Tcl_Channel channel, Tcl_Obj *objPtr, int charsToRead, int appendFlag); /* 313 */
+ void (*tcl_RestoreResult) (Tcl_Interp *interp, Tcl_SavedResult *statePtr); /* 314 */
+ void (*tcl_SaveResult) (Tcl_Interp *interp, Tcl_SavedResult *statePtr); /* 315 */
+ int (*tcl_SetSystemEncoding) (Tcl_Interp *interp, const char *name); /* 316 */
+ Tcl_Obj * (*tcl_SetVar2Ex) (Tcl_Interp *interp, const char *part1, const char *part2, Tcl_Obj *newValuePtr, int flags); /* 317 */
+ void (*tcl_ThreadAlert) (Tcl_ThreadId threadId); /* 318 */
+ void (*tcl_ThreadQueueEvent) (Tcl_ThreadId threadId, Tcl_Event *evPtr, Tcl_QueuePosition position); /* 319 */
+ Tcl_UniChar (*tcl_UniCharAtIndex) (const char *src, int index); /* 320 */
+ Tcl_UniChar (*tcl_UniCharToLower) (int ch); /* 321 */
+ Tcl_UniChar (*tcl_UniCharToTitle) (int ch); /* 322 */
+ Tcl_UniChar (*tcl_UniCharToUpper) (int ch); /* 323 */
+ int (*tcl_UniCharToUtf) (int ch, char *buf); /* 324 */
+ CONST84_RETURN char * (*tcl_UtfAtIndex) (const char *src, int index); /* 325 */
+ int (*tcl_UtfCharComplete) (const char *src, int length); /* 326 */
+ int (*tcl_UtfBackslash) (const char *src, int *readPtr, char *dst); /* 327 */
+ CONST84_RETURN char * (*tcl_UtfFindFirst) (const char *src, int ch); /* 328 */
+ CONST84_RETURN char * (*tcl_UtfFindLast) (const char *src, int ch); /* 329 */
+ CONST84_RETURN char * (*tcl_UtfNext) (const char *src); /* 330 */
+ CONST84_RETURN char * (*tcl_UtfPrev) (const char *src, const char *start); /* 331 */
+ int (*tcl_UtfToExternal) (Tcl_Interp *interp, Tcl_Encoding encoding, const char *src, int srcLen, int flags, Tcl_EncodingState *statePtr, char *dst, int dstLen, int *srcReadPtr, int *dstWrotePtr, int *dstCharsPtr); /* 332 */
+ char * (*tcl_UtfToExternalDString) (Tcl_Encoding encoding, const char *src, int srcLen, Tcl_DString *dsPtr); /* 333 */
+ int (*tcl_UtfToLower) (char *src); /* 334 */
+ int (*tcl_UtfToTitle) (char *src); /* 335 */
+ int (*tcl_UtfToUniChar) (const char *src, Tcl_UniChar *chPtr); /* 336 */
+ int (*tcl_UtfToUpper) (char *src); /* 337 */
+ int (*tcl_WriteChars) (Tcl_Channel chan, const char *src, int srcLen); /* 338 */
+ int (*tcl_WriteObj) (Tcl_Channel chan, Tcl_Obj *objPtr); /* 339 */
+ char * (*tcl_GetString) (Tcl_Obj *objPtr); /* 340 */
+ CONST84_RETURN char * (*tcl_GetDefaultEncodingDir) (void); /* 341 */
+ void (*tcl_SetDefaultEncodingDir) (const char *path); /* 342 */
+ void (*tcl_AlertNotifier) (ClientData clientData); /* 343 */
+ void (*tcl_ServiceModeHook) (int mode); /* 344 */
+ int (*tcl_UniCharIsAlnum) (int ch); /* 345 */
+ int (*tcl_UniCharIsAlpha) (int ch); /* 346 */
+ int (*tcl_UniCharIsDigit) (int ch); /* 347 */
+ int (*tcl_UniCharIsLower) (int ch); /* 348 */
+ int (*tcl_UniCharIsSpace) (int ch); /* 349 */
+ int (*tcl_UniCharIsUpper) (int ch); /* 350 */
+ int (*tcl_UniCharIsWordChar) (int ch); /* 351 */
+ int (*tcl_UniCharLen) (const Tcl_UniChar *uniStr); /* 352 */
+ int (*tcl_UniCharNcmp) (const Tcl_UniChar *ucs, const Tcl_UniChar *uct, unsigned long numChars); /* 353 */
+ char * (*tcl_UniCharToUtfDString) (const Tcl_UniChar *uniStr, int uniLength, Tcl_DString *dsPtr); /* 354 */
+ Tcl_UniChar * (*tcl_UtfToUniCharDString) (const char *src, int length, Tcl_DString *dsPtr); /* 355 */
+ Tcl_RegExp (*tcl_GetRegExpFromObj) (Tcl_Interp *interp, Tcl_Obj *patObj, int flags); /* 356 */
+ Tcl_Obj * (*tcl_EvalTokens) (Tcl_Interp *interp, Tcl_Token *tokenPtr, int count); /* 357 */
+ void (*tcl_FreeParse) (Tcl_Parse *parsePtr); /* 358 */
+ void (*tcl_LogCommandInfo) (Tcl_Interp *interp, const char *script, const char *command, int length); /* 359 */
+ int (*tcl_ParseBraces) (Tcl_Interp *interp, const char *start, int numBytes, Tcl_Parse *parsePtr, int append, CONST84 char **termPtr); /* 360 */
+ int (*tcl_ParseCommand) (Tcl_Interp *interp, const char *start, int numBytes, int nested, Tcl_Parse *parsePtr); /* 361 */
+ int (*tcl_ParseExpr) (Tcl_Interp *interp, const char *start, int numBytes, Tcl_Parse *parsePtr); /* 362 */
+ int (*tcl_ParseQuotedString) (Tcl_Interp *interp, const char *start, int numBytes, Tcl_Parse *parsePtr, int append, CONST84 char **termPtr); /* 363 */
+ int (*tcl_ParseVarName) (Tcl_Interp *interp, const char *start, int numBytes, Tcl_Parse *parsePtr, int append); /* 364 */
+ char * (*tcl_GetCwd) (Tcl_Interp *interp, Tcl_DString *cwdPtr); /* 365 */
+ int (*tcl_Chdir) (const char *dirName); /* 366 */
+ int (*tcl_Access) (const char *path, int mode); /* 367 */
+ int (*tcl_Stat) (const char *path, struct stat *bufPtr); /* 368 */
+ int (*tcl_UtfNcmp) (const char *s1, const char *s2, unsigned long n); /* 369 */
+ int (*tcl_UtfNcasecmp) (const char *s1, const char *s2, unsigned long n); /* 370 */
+ int (*tcl_StringCaseMatch) (const char *str, const char *pattern, int nocase); /* 371 */
+ int (*tcl_UniCharIsControl) (int ch); /* 372 */
+ int (*tcl_UniCharIsGraph) (int ch); /* 373 */
+ int (*tcl_UniCharIsPrint) (int ch); /* 374 */
+ int (*tcl_UniCharIsPunct) (int ch); /* 375 */
+ int (*tcl_RegExpExecObj) (Tcl_Interp *interp, Tcl_RegExp regexp, Tcl_Obj *textObj, int offset, int nmatches, int flags); /* 376 */
+ void (*tcl_RegExpGetInfo) (Tcl_RegExp regexp, Tcl_RegExpInfo *infoPtr); /* 377 */
+ Tcl_Obj * (*tcl_NewUnicodeObj) (const Tcl_UniChar *unicode, int numChars); /* 378 */
+ void (*tcl_SetUnicodeObj) (Tcl_Obj *objPtr, const Tcl_UniChar *unicode, int numChars); /* 379 */
+ int (*tcl_GetCharLength) (Tcl_Obj *objPtr); /* 380 */
+ Tcl_UniChar (*tcl_GetUniChar) (Tcl_Obj *objPtr, int index); /* 381 */
+ Tcl_UniChar * (*tcl_GetUnicode) (Tcl_Obj *objPtr); /* 382 */
+ Tcl_Obj * (*tcl_GetRange) (Tcl_Obj *objPtr, int first, int last); /* 383 */
+ void (*tcl_AppendUnicodeToObj) (Tcl_Obj *objPtr, const Tcl_UniChar *unicode, int length); /* 384 */
+ int (*tcl_RegExpMatchObj) (Tcl_Interp *interp, Tcl_Obj *textObj, Tcl_Obj *patternObj); /* 385 */
+ void (*tcl_SetNotifier) (Tcl_NotifierProcs *notifierProcPtr); /* 386 */
+ Tcl_Mutex * (*tcl_GetAllocMutex) (void); /* 387 */
+ int (*tcl_GetChannelNames) (Tcl_Interp *interp); /* 388 */
+ int (*tcl_GetChannelNamesEx) (Tcl_Interp *interp, const char *pattern); /* 389 */
+ int (*tcl_ProcObjCmd) (ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]); /* 390 */
+ void (*tcl_ConditionFinalize) (Tcl_Condition *condPtr); /* 391 */
+ void (*tcl_MutexFinalize) (Tcl_Mutex *mutex); /* 392 */
+ int (*tcl_CreateThread) (Tcl_ThreadId *idPtr, Tcl_ThreadCreateProc *proc, ClientData clientData, int stackSize, int flags); /* 393 */
+ int (*tcl_ReadRaw) (Tcl_Channel chan, char *dst, int bytesToRead); /* 394 */
+ int (*tcl_WriteRaw) (Tcl_Channel chan, const char *src, int srcLen); /* 395 */
+ Tcl_Channel (*tcl_GetTopChannel) (Tcl_Channel chan); /* 396 */
+ int (*tcl_ChannelBuffered) (Tcl_Channel chan); /* 397 */
+ CONST84_RETURN char * (*tcl_ChannelName) (const Tcl_ChannelType *chanTypePtr); /* 398 */
+ Tcl_ChannelTypeVersion (*tcl_ChannelVersion) (const Tcl_ChannelType *chanTypePtr); /* 399 */
+ Tcl_DriverBlockModeProc * (*tcl_ChannelBlockModeProc) (const Tcl_ChannelType *chanTypePtr); /* 400 */
+ Tcl_DriverCloseProc * (*tcl_ChannelCloseProc) (const Tcl_ChannelType *chanTypePtr); /* 401 */
+ Tcl_DriverClose2Proc * (*tcl_ChannelClose2Proc) (const Tcl_ChannelType *chanTypePtr); /* 402 */
+ Tcl_DriverInputProc * (*tcl_ChannelInputProc) (const Tcl_ChannelType *chanTypePtr); /* 403 */
+ Tcl_DriverOutputProc * (*tcl_ChannelOutputProc) (const Tcl_ChannelType *chanTypePtr); /* 404 */
+ Tcl_DriverSeekProc * (*tcl_ChannelSeekProc) (const Tcl_ChannelType *chanTypePtr); /* 405 */
+ Tcl_DriverSetOptionProc * (*tcl_ChannelSetOptionProc) (const Tcl_ChannelType *chanTypePtr); /* 406 */
+ Tcl_DriverGetOptionProc * (*tcl_ChannelGetOptionProc) (const Tcl_ChannelType *chanTypePtr); /* 407 */
+ Tcl_DriverWatchProc * (*tcl_ChannelWatchProc) (const Tcl_ChannelType *chanTypePtr); /* 408 */
+ Tcl_DriverGetHandleProc * (*tcl_ChannelGetHandleProc) (const Tcl_ChannelType *chanTypePtr); /* 409 */
+ Tcl_DriverFlushProc * (*tcl_ChannelFlushProc) (const Tcl_ChannelType *chanTypePtr); /* 410 */
+ Tcl_DriverHandlerProc * (*tcl_ChannelHandlerProc) (const Tcl_ChannelType *chanTypePtr); /* 411 */
+ int (*tcl_JoinThread) (Tcl_ThreadId threadId, int *result); /* 412 */
+ int (*tcl_IsChannelShared) (Tcl_Channel channel); /* 413 */
+ int (*tcl_IsChannelRegistered) (Tcl_Interp *interp, Tcl_Channel channel); /* 414 */
+ void (*tcl_CutChannel) (Tcl_Channel channel); /* 415 */
+ void (*tcl_SpliceChannel) (Tcl_Channel channel); /* 416 */
+ void (*tcl_ClearChannelHandlers) (Tcl_Channel channel); /* 417 */
+ int (*tcl_IsChannelExisting) (const char *channelName); /* 418 */
+ int (*tcl_UniCharNcasecmp) (const Tcl_UniChar *ucs, const Tcl_UniChar *uct, unsigned long numChars); /* 419 */
+ int (*tcl_UniCharCaseMatch) (const Tcl_UniChar *uniStr, const Tcl_UniChar *uniPattern, int nocase); /* 420 */
+ Tcl_HashEntry * (*tcl_FindHashEntry) (Tcl_HashTable *tablePtr, const void *key); /* 421 */
+ Tcl_HashEntry * (*tcl_CreateHashEntry) (Tcl_HashTable *tablePtr, const void *key, int *newPtr); /* 422 */
+ void (*tcl_InitCustomHashTable) (Tcl_HashTable *tablePtr, int keyType, const Tcl_HashKeyType *typePtr); /* 423 */
+ void (*tcl_InitObjHashTable) (Tcl_HashTable *tablePtr); /* 424 */
+ ClientData (*tcl_CommandTraceInfo) (Tcl_Interp *interp, const char *varName, int flags, Tcl_CommandTraceProc *procPtr, ClientData prevClientData); /* 425 */
+ int (*tcl_TraceCommand) (Tcl_Interp *interp, const char *varName, int flags, Tcl_CommandTraceProc *proc, ClientData clientData); /* 426 */
+ void (*tcl_UntraceCommand) (Tcl_Interp *interp, const char *varName, int flags, Tcl_CommandTraceProc *proc, ClientData clientData); /* 427 */
+ char * (*tcl_AttemptAlloc) (unsigned int size); /* 428 */
+ char * (*tcl_AttemptDbCkalloc) (unsigned int size, const char *file, int line); /* 429 */
+ char * (*tcl_AttemptRealloc) (char *ptr, unsigned int size); /* 430 */
+ char * (*tcl_AttemptDbCkrealloc) (char *ptr, unsigned int size, const char *file, int line); /* 431 */
+ int (*tcl_AttemptSetObjLength) (Tcl_Obj *objPtr, int length); /* 432 */
+ Tcl_ThreadId (*tcl_GetChannelThread) (Tcl_Channel channel); /* 433 */
+ Tcl_UniChar * (*tcl_GetUnicodeFromObj) (Tcl_Obj *objPtr, int *lengthPtr); /* 434 */
+ int (*tcl_GetMathFuncInfo) (Tcl_Interp *interp, const char *name, int *numArgsPtr, Tcl_ValueType **argTypesPtr, Tcl_MathProc **procPtr, ClientData *clientDataPtr); /* 435 */
+ Tcl_Obj * (*tcl_ListMathFuncs) (Tcl_Interp *interp, const char *pattern); /* 436 */
+ Tcl_Obj * (*tcl_SubstObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, int flags); /* 437 */
+ int (*tcl_DetachChannel) (Tcl_Interp *interp, Tcl_Channel channel); /* 438 */
+ int (*tcl_IsStandardChannel) (Tcl_Channel channel); /* 439 */
+ int (*tcl_FSCopyFile) (Tcl_Obj *srcPathPtr, Tcl_Obj *destPathPtr); /* 440 */
+ int (*tcl_FSCopyDirectory) (Tcl_Obj *srcPathPtr, Tcl_Obj *destPathPtr, Tcl_Obj **errorPtr); /* 441 */
+ int (*tcl_FSCreateDirectory) (Tcl_Obj *pathPtr); /* 442 */
+ int (*tcl_FSDeleteFile) (Tcl_Obj *pathPtr); /* 443 */
+ int (*tcl_FSLoadFile) (Tcl_Interp *interp, Tcl_Obj *pathPtr, const char *sym1, const char *sym2, Tcl_PackageInitProc **proc1Ptr, Tcl_PackageInitProc **proc2Ptr, Tcl_LoadHandle *handlePtr, Tcl_FSUnloadFileProc **unloadProcPtr); /* 444 */
+ int (*tcl_FSMatchInDirectory) (Tcl_Interp *interp, Tcl_Obj *result, Tcl_Obj *pathPtr, const char *pattern, Tcl_GlobTypeData *types); /* 445 */
+ Tcl_Obj * (*tcl_FSLink) (Tcl_Obj *pathPtr, Tcl_Obj *toPtr, int linkAction); /* 446 */
+ int (*tcl_FSRemoveDirectory) (Tcl_Obj *pathPtr, int recursive, Tcl_Obj **errorPtr); /* 447 */
+ int (*tcl_FSRenameFile) (Tcl_Obj *srcPathPtr, Tcl_Obj *destPathPtr); /* 448 */
+ int (*tcl_FSLstat) (Tcl_Obj *pathPtr, Tcl_StatBuf *buf); /* 449 */
+ int (*tcl_FSUtime) (Tcl_Obj *pathPtr, struct utimbuf *tval); /* 450 */
+ int (*tcl_FSFileAttrsGet) (Tcl_Interp *interp, int index, Tcl_Obj *pathPtr, Tcl_Obj **objPtrRef); /* 451 */
+ int (*tcl_FSFileAttrsSet) (Tcl_Interp *interp, int index, Tcl_Obj *pathPtr, Tcl_Obj *objPtr); /* 452 */
+ const char *CONST86 * (*tcl_FSFileAttrStrings) (Tcl_Obj *pathPtr, Tcl_Obj **objPtrRef); /* 453 */
+ int (*tcl_FSStat) (Tcl_Obj *pathPtr, Tcl_StatBuf *buf); /* 454 */
+ int (*tcl_FSAccess) (Tcl_Obj *pathPtr, int mode); /* 455 */
+ Tcl_Channel (*tcl_FSOpenFileChannel) (Tcl_Interp *interp, Tcl_Obj *pathPtr, const char *modeString, int permissions); /* 456 */
+ Tcl_Obj * (*tcl_FSGetCwd) (Tcl_Interp *interp); /* 457 */
+ int (*tcl_FSChdir) (Tcl_Obj *pathPtr); /* 458 */
+ int (*tcl_FSConvertToPathType) (Tcl_Interp *interp, Tcl_Obj *pathPtr); /* 459 */
+ Tcl_Obj * (*tcl_FSJoinPath) (Tcl_Obj *listObj, int elements); /* 460 */
+ Tcl_Obj * (*tcl_FSSplitPath) (Tcl_Obj *pathPtr, int *lenPtr); /* 461 */
+ int (*tcl_FSEqualPaths) (Tcl_Obj *firstPtr, Tcl_Obj *secondPtr); /* 462 */
+ Tcl_Obj * (*tcl_FSGetNormalizedPath) (Tcl_Interp *interp, Tcl_Obj *pathPtr); /* 463 */
+ Tcl_Obj * (*tcl_FSJoinToPath) (Tcl_Obj *pathPtr, int objc, Tcl_Obj *const objv[]); /* 464 */
+ ClientData (*tcl_FSGetInternalRep) (Tcl_Obj *pathPtr, const Tcl_Filesystem *fsPtr); /* 465 */
+ Tcl_Obj * (*tcl_FSGetTranslatedPath) (Tcl_Interp *interp, Tcl_Obj *pathPtr); /* 466 */
+ int (*tcl_FSEvalFile) (Tcl_Interp *interp, Tcl_Obj *fileName); /* 467 */
+ Tcl_Obj * (*tcl_FSNewNativePath) (const Tcl_Filesystem *fromFilesystem, ClientData clientData); /* 468 */
+ const void * (*tcl_FSGetNativePath) (Tcl_Obj *pathPtr); /* 469 */
+ Tcl_Obj * (*tcl_FSFileSystemInfo) (Tcl_Obj *pathPtr); /* 470 */
+ Tcl_Obj * (*tcl_FSPathSeparator) (Tcl_Obj *pathPtr); /* 471 */
+ Tcl_Obj * (*tcl_FSListVolumes) (void); /* 472 */
+ int (*tcl_FSRegister) (ClientData clientData, const Tcl_Filesystem *fsPtr); /* 473 */
+ int (*tcl_FSUnregister) (const Tcl_Filesystem *fsPtr); /* 474 */
+ ClientData (*tcl_FSData) (const Tcl_Filesystem *fsPtr); /* 475 */
+ const char * (*tcl_FSGetTranslatedStringPath) (Tcl_Interp *interp, Tcl_Obj *pathPtr); /* 476 */
+ CONST86 Tcl_Filesystem * (*tcl_FSGetFileSystemForPath) (Tcl_Obj *pathPtr); /* 477 */
+ Tcl_PathType (*tcl_FSGetPathType) (Tcl_Obj *pathPtr); /* 478 */
+ int (*tcl_OutputBuffered) (Tcl_Channel chan); /* 479 */
+ void (*tcl_FSMountsChanged) (const Tcl_Filesystem *fsPtr); /* 480 */
+ int (*tcl_EvalTokensStandard) (Tcl_Interp *interp, Tcl_Token *tokenPtr, int count); /* 481 */
+ void (*tcl_GetTime) (Tcl_Time *timeBuf); /* 482 */
+ Tcl_Trace (*tcl_CreateObjTrace) (Tcl_Interp *interp, int level, int flags, Tcl_CmdObjTraceProc *objProc, ClientData clientData, Tcl_CmdObjTraceDeleteProc *delProc); /* 483 */
+ int (*tcl_GetCommandInfoFromToken) (Tcl_Command token, Tcl_CmdInfo *infoPtr); /* 484 */
+ int (*tcl_SetCommandInfoFromToken) (Tcl_Command token, const Tcl_CmdInfo *infoPtr); /* 485 */
+ Tcl_Obj * (*tcl_DbNewWideIntObj) (Tcl_WideInt wideValue, const char *file, int line); /* 486 */
+ int (*tcl_GetWideIntFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, Tcl_WideInt *widePtr); /* 487 */
+ Tcl_Obj * (*tcl_NewWideIntObj) (Tcl_WideInt wideValue); /* 488 */
+ void (*tcl_SetWideIntObj) (Tcl_Obj *objPtr, Tcl_WideInt wideValue); /* 489 */
+ Tcl_StatBuf * (*tcl_AllocStatBuf) (void); /* 490 */
+ Tcl_WideInt (*tcl_Seek) (Tcl_Channel chan, Tcl_WideInt offset, int mode); /* 491 */
+ Tcl_WideInt (*tcl_Tell) (Tcl_Channel chan); /* 492 */
+ Tcl_DriverWideSeekProc * (*tcl_ChannelWideSeekProc) (const Tcl_ChannelType *chanTypePtr); /* 493 */
+ int (*tcl_DictObjPut) (Tcl_Interp *interp, Tcl_Obj *dictPtr, Tcl_Obj *keyPtr, Tcl_Obj *valuePtr); /* 494 */
+ int (*tcl_DictObjGet) (Tcl_Interp *interp, Tcl_Obj *dictPtr, Tcl_Obj *keyPtr, Tcl_Obj **valuePtrPtr); /* 495 */
+ int (*tcl_DictObjRemove) (Tcl_Interp *interp, Tcl_Obj *dictPtr, Tcl_Obj *keyPtr); /* 496 */
+ int (*tcl_DictObjSize) (Tcl_Interp *interp, Tcl_Obj *dictPtr, int *sizePtr); /* 497 */
+ int (*tcl_DictObjFirst) (Tcl_Interp *interp, Tcl_Obj *dictPtr, Tcl_DictSearch *searchPtr, Tcl_Obj **keyPtrPtr, Tcl_Obj **valuePtrPtr, int *donePtr); /* 498 */
+ void (*tcl_DictObjNext) (Tcl_DictSearch *searchPtr, Tcl_Obj **keyPtrPtr, Tcl_Obj **valuePtrPtr, int *donePtr); /* 499 */
+ void (*tcl_DictObjDone) (Tcl_DictSearch *searchPtr); /* 500 */
+ int (*tcl_DictObjPutKeyList) (Tcl_Interp *interp, Tcl_Obj *dictPtr, int keyc, Tcl_Obj *const *keyv, Tcl_Obj *valuePtr); /* 501 */
+ int (*tcl_DictObjRemoveKeyList) (Tcl_Interp *interp, Tcl_Obj *dictPtr, int keyc, Tcl_Obj *const *keyv); /* 502 */
+ Tcl_Obj * (*tcl_NewDictObj) (void); /* 503 */
+ Tcl_Obj * (*tcl_DbNewDictObj) (const char *file, int line); /* 504 */
+ void (*tcl_RegisterConfig) (Tcl_Interp *interp, const char *pkgName, const Tcl_Config *configuration, const char *valEncoding); /* 505 */
+ Tcl_Namespace * (*tcl_CreateNamespace) (Tcl_Interp *interp, const char *name, ClientData clientData, Tcl_NamespaceDeleteProc *deleteProc); /* 506 */
+ void (*tcl_DeleteNamespace) (Tcl_Namespace *nsPtr); /* 507 */
+ int (*tcl_AppendExportList) (Tcl_Interp *interp, Tcl_Namespace *nsPtr, Tcl_Obj *objPtr); /* 508 */
+ int (*tcl_Export) (Tcl_Interp *interp, Tcl_Namespace *nsPtr, const char *pattern, int resetListFirst); /* 509 */
+ int (*tcl_Import) (Tcl_Interp *interp, Tcl_Namespace *nsPtr, const char *pattern, int allowOverwrite); /* 510 */
+ int (*tcl_ForgetImport) (Tcl_Interp *interp, Tcl_Namespace *nsPtr, const char *pattern); /* 511 */
+ Tcl_Namespace * (*tcl_GetCurrentNamespace) (Tcl_Interp *interp); /* 512 */
+ Tcl_Namespace * (*tcl_GetGlobalNamespace) (Tcl_Interp *interp); /* 513 */
+ Tcl_Namespace * (*tcl_FindNamespace) (Tcl_Interp *interp, const char *name, Tcl_Namespace *contextNsPtr, int flags); /* 514 */
+ Tcl_Command (*tcl_FindCommand) (Tcl_Interp *interp, const char *name, Tcl_Namespace *contextNsPtr, int flags); /* 515 */
+ Tcl_Command (*tcl_GetCommandFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr); /* 516 */
+ void (*tcl_GetCommandFullName) (Tcl_Interp *interp, Tcl_Command command, Tcl_Obj *objPtr); /* 517 */
+ int (*tcl_FSEvalFileEx) (Tcl_Interp *interp, Tcl_Obj *fileName, const char *encodingName); /* 518 */
+ Tcl_ExitProc * (*tcl_SetExitProc) (Tcl_ExitProc *proc); /* 519 */
+ void (*tcl_LimitAddHandler) (Tcl_Interp *interp, int type, Tcl_LimitHandlerProc *handlerProc, ClientData clientData, Tcl_LimitHandlerDeleteProc *deleteProc); /* 520 */
+ void (*tcl_LimitRemoveHandler) (Tcl_Interp *interp, int type, Tcl_LimitHandlerProc *handlerProc, ClientData clientData); /* 521 */
+ int (*tcl_LimitReady) (Tcl_Interp *interp); /* 522 */
+ int (*tcl_LimitCheck) (Tcl_Interp *interp); /* 523 */
+ int (*tcl_LimitExceeded) (Tcl_Interp *interp); /* 524 */
+ void (*tcl_LimitSetCommands) (Tcl_Interp *interp, int commandLimit); /* 525 */
+ void (*tcl_LimitSetTime) (Tcl_Interp *interp, Tcl_Time *timeLimitPtr); /* 526 */
+ void (*tcl_LimitSetGranularity) (Tcl_Interp *interp, int type, int granularity); /* 527 */
+ int (*tcl_LimitTypeEnabled) (Tcl_Interp *interp, int type); /* 528 */
+ int (*tcl_LimitTypeExceeded) (Tcl_Interp *interp, int type); /* 529 */
+ void (*tcl_LimitTypeSet) (Tcl_Interp *interp, int type); /* 530 */
+ void (*tcl_LimitTypeReset) (Tcl_Interp *interp, int type); /* 531 */
+ int (*tcl_LimitGetCommands) (Tcl_Interp *interp); /* 532 */
+ void (*tcl_LimitGetTime) (Tcl_Interp *interp, Tcl_Time *timeLimitPtr); /* 533 */
+ int (*tcl_LimitGetGranularity) (Tcl_Interp *interp, int type); /* 534 */
+ Tcl_InterpState (*tcl_SaveInterpState) (Tcl_Interp *interp, int status); /* 535 */
+ int (*tcl_RestoreInterpState) (Tcl_Interp *interp, Tcl_InterpState state); /* 536 */
+ void (*tcl_DiscardInterpState) (Tcl_InterpState state); /* 537 */
+ int (*tcl_SetReturnOptions) (Tcl_Interp *interp, Tcl_Obj *options); /* 538 */
+ Tcl_Obj * (*tcl_GetReturnOptions) (Tcl_Interp *interp, int result); /* 539 */
+ int (*tcl_IsEnsemble) (Tcl_Command token); /* 540 */
+ Tcl_Command (*tcl_CreateEnsemble) (Tcl_Interp *interp, const char *name, Tcl_Namespace *namespacePtr, int flags); /* 541 */
+ Tcl_Command (*tcl_FindEnsemble) (Tcl_Interp *interp, Tcl_Obj *cmdNameObj, int flags); /* 542 */
+ int (*tcl_SetEnsembleSubcommandList) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj *subcmdList); /* 543 */
+ int (*tcl_SetEnsembleMappingDict) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj *mapDict); /* 544 */
+ int (*tcl_SetEnsembleUnknownHandler) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj *unknownList); /* 545 */
+ int (*tcl_SetEnsembleFlags) (Tcl_Interp *interp, Tcl_Command token, int flags); /* 546 */
+ int (*tcl_GetEnsembleSubcommandList) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj **subcmdListPtr); /* 547 */
+ int (*tcl_GetEnsembleMappingDict) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj **mapDictPtr); /* 548 */
+ int (*tcl_GetEnsembleUnknownHandler) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj **unknownListPtr); /* 549 */
+ int (*tcl_GetEnsembleFlags) (Tcl_Interp *interp, Tcl_Command token, int *flagsPtr); /* 550 */
+ int (*tcl_GetEnsembleNamespace) (Tcl_Interp *interp, Tcl_Command token, Tcl_Namespace **namespacePtrPtr); /* 551 */
+ void (*tcl_SetTimeProc) (Tcl_GetTimeProc *getProc, Tcl_ScaleTimeProc *scaleProc, ClientData clientData); /* 552 */
+ void (*tcl_QueryTimeProc) (Tcl_GetTimeProc **getProc, Tcl_ScaleTimeProc **scaleProc, ClientData *clientData); /* 553 */
+ Tcl_DriverThreadActionProc * (*tcl_ChannelThreadActionProc) (const Tcl_ChannelType *chanTypePtr); /* 554 */
+ Tcl_Obj * (*tcl_NewBignumObj) (mp_int *value); /* 555 */
+ Tcl_Obj * (*tcl_DbNewBignumObj) (mp_int *value, const char *file, int line); /* 556 */
+ void (*tcl_SetBignumObj) (Tcl_Obj *obj, mp_int *value); /* 557 */
+ int (*tcl_GetBignumFromObj) (Tcl_Interp *interp, Tcl_Obj *obj, mp_int *value); /* 558 */
+ int (*tcl_TakeBignumFromObj) (Tcl_Interp *interp, Tcl_Obj *obj, mp_int *value); /* 559 */
+ int (*tcl_TruncateChannel) (Tcl_Channel chan, Tcl_WideInt length); /* 560 */
+ Tcl_DriverTruncateProc * (*tcl_ChannelTruncateProc) (const Tcl_ChannelType *chanTypePtr); /* 561 */
+ void (*tcl_SetChannelErrorInterp) (Tcl_Interp *interp, Tcl_Obj *msg); /* 562 */
+ void (*tcl_GetChannelErrorInterp) (Tcl_Interp *interp, Tcl_Obj **msg); /* 563 */
+ void (*tcl_SetChannelError) (Tcl_Channel chan, Tcl_Obj *msg); /* 564 */
+ void (*tcl_GetChannelError) (Tcl_Channel chan, Tcl_Obj **msg); /* 565 */
+ int (*tcl_InitBignumFromDouble) (Tcl_Interp *interp, double initval, mp_int *toInit); /* 566 */
+ Tcl_Obj * (*tcl_GetNamespaceUnknownHandler) (Tcl_Interp *interp, Tcl_Namespace *nsPtr); /* 567 */
+ int (*tcl_SetNamespaceUnknownHandler) (Tcl_Interp *interp, Tcl_Namespace *nsPtr, Tcl_Obj *handlerPtr); /* 568 */
+ int (*tcl_GetEncodingFromObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, Tcl_Encoding *encodingPtr); /* 569 */
+ Tcl_Obj * (*tcl_GetEncodingSearchPath) (void); /* 570 */
+ int (*tcl_SetEncodingSearchPath) (Tcl_Obj *searchPath); /* 571 */
+ const char * (*tcl_GetEncodingNameFromEnvironment) (Tcl_DString *bufPtr); /* 572 */
+ int (*tcl_PkgRequireProc) (Tcl_Interp *interp, const char *name, int objc, Tcl_Obj *const objv[], void *clientDataPtr); /* 573 */
+ void (*tcl_AppendObjToErrorInfo) (Tcl_Interp *interp, Tcl_Obj *objPtr); /* 574 */
+ void (*tcl_AppendLimitedToObj) (Tcl_Obj *objPtr, const char *bytes, int length, int limit, const char *ellipsis); /* 575 */
+ Tcl_Obj * (*tcl_Format) (Tcl_Interp *interp, const char *format, int objc, Tcl_Obj *const objv[]); /* 576 */
+ int (*tcl_AppendFormatToObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, const char *format, int objc, Tcl_Obj *const objv[]); /* 577 */
+ Tcl_Obj * (*tcl_ObjPrintf) (const char *format, ...) TCL_FORMAT_PRINTF(1, 2); /* 578 */
+ void (*tcl_AppendPrintfToObj) (Tcl_Obj *objPtr, const char *format, ...) TCL_FORMAT_PRINTF(2, 3); /* 579 */
+ int (*tcl_CancelEval) (Tcl_Interp *interp, Tcl_Obj *resultObjPtr, ClientData clientData, int flags); /* 580 */
+ int (*tcl_Canceled) (Tcl_Interp *interp, int flags); /* 581 */
+ int (*tcl_CreatePipe) (Tcl_Interp *interp, Tcl_Channel *rchan, Tcl_Channel *wchan, int flags); /* 582 */
+ Tcl_Command (*tcl_NRCreateCommand) (Tcl_Interp *interp, const char *cmdName, Tcl_ObjCmdProc *proc, Tcl_ObjCmdProc *nreProc, ClientData clientData, Tcl_CmdDeleteProc *deleteProc); /* 583 */
+ int (*tcl_NREvalObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, int flags); /* 584 */
+ int (*tcl_NREvalObjv) (Tcl_Interp *interp, int objc, Tcl_Obj *const objv[], int flags); /* 585 */
+ int (*tcl_NRCmdSwap) (Tcl_Interp *interp, Tcl_Command cmd, int objc, Tcl_Obj *const objv[], int flags); /* 586 */
+ void (*tcl_NRAddCallback) (Tcl_Interp *interp, Tcl_NRPostProc *postProcPtr, ClientData data0, ClientData data1, ClientData data2, ClientData data3); /* 587 */
+ int (*tcl_NRCallObjProc) (Tcl_Interp *interp, Tcl_ObjCmdProc *objProc, ClientData clientData, int objc, Tcl_Obj *const objv[]); /* 588 */
+ unsigned (*tcl_GetFSDeviceFromStat) (const Tcl_StatBuf *statPtr); /* 589 */
+ unsigned (*tcl_GetFSInodeFromStat) (const Tcl_StatBuf *statPtr); /* 590 */
+ unsigned (*tcl_GetModeFromStat) (const Tcl_StatBuf *statPtr); /* 591 */
+ int (*tcl_GetLinkCountFromStat) (const Tcl_StatBuf *statPtr); /* 592 */
+ int (*tcl_GetUserIdFromStat) (const Tcl_StatBuf *statPtr); /* 593 */
+ int (*tcl_GetGroupIdFromStat) (const Tcl_StatBuf *statPtr); /* 594 */
+ int (*tcl_GetDeviceTypeFromStat) (const Tcl_StatBuf *statPtr); /* 595 */
+ Tcl_WideInt (*tcl_GetAccessTimeFromStat) (const Tcl_StatBuf *statPtr); /* 596 */
+ Tcl_WideInt (*tcl_GetModificationTimeFromStat) (const Tcl_StatBuf *statPtr); /* 597 */
+ Tcl_WideInt (*tcl_GetChangeTimeFromStat) (const Tcl_StatBuf *statPtr); /* 598 */
+ Tcl_WideUInt (*tcl_GetSizeFromStat) (const Tcl_StatBuf *statPtr); /* 599 */
+ Tcl_WideUInt (*tcl_GetBlocksFromStat) (const Tcl_StatBuf *statPtr); /* 600 */
+ unsigned (*tcl_GetBlockSizeFromStat) (const Tcl_StatBuf *statPtr); /* 601 */
+ int (*tcl_SetEnsembleParameterList) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj *paramList); /* 602 */
+ int (*tcl_GetEnsembleParameterList) (Tcl_Interp *interp, Tcl_Command token, Tcl_Obj **paramListPtr); /* 603 */
+ int (*tcl_ParseArgsObjv) (Tcl_Interp *interp, const Tcl_ArgvInfo *argTable, int *objcPtr, Tcl_Obj *const *objv, Tcl_Obj ***remObjv); /* 604 */
+ int (*tcl_GetErrorLine) (Tcl_Interp *interp); /* 605 */
+ void (*tcl_SetErrorLine) (Tcl_Interp *interp, int lineNum); /* 606 */
+ void (*tcl_TransferResult) (Tcl_Interp *sourceInterp, int result, Tcl_Interp *targetInterp); /* 607 */
+ int (*tcl_InterpActive) (Tcl_Interp *interp); /* 608 */
+ void (*tcl_BackgroundException) (Tcl_Interp *interp, int code); /* 609 */
+ int (*tcl_ZlibDeflate) (Tcl_Interp *interp, int format, Tcl_Obj *data, int level, Tcl_Obj *gzipHeaderDictObj); /* 610 */
+ int (*tcl_ZlibInflate) (Tcl_Interp *interp, int format, Tcl_Obj *data, int buffersize, Tcl_Obj *gzipHeaderDictObj); /* 611 */
+ unsigned int (*tcl_ZlibCRC32) (unsigned int crc, const unsigned char *buf, int len); /* 612 */
+ unsigned int (*tcl_ZlibAdler32) (unsigned int adler, const unsigned char *buf, int len); /* 613 */
+ int (*tcl_ZlibStreamInit) (Tcl_Interp *interp, int mode, int format, int level, Tcl_Obj *dictObj, Tcl_ZlibStream *zshandle); /* 614 */
+ Tcl_Obj * (*tcl_ZlibStreamGetCommandName) (Tcl_ZlibStream zshandle); /* 615 */
+ int (*tcl_ZlibStreamEof) (Tcl_ZlibStream zshandle); /* 616 */
+ int (*tcl_ZlibStreamChecksum) (Tcl_ZlibStream zshandle); /* 617 */
+ int (*tcl_ZlibStreamPut) (Tcl_ZlibStream zshandle, Tcl_Obj *data, int flush); /* 618 */
+ int (*tcl_ZlibStreamGet) (Tcl_ZlibStream zshandle, Tcl_Obj *data, int count); /* 619 */
+ int (*tcl_ZlibStreamClose) (Tcl_ZlibStream zshandle); /* 620 */
+ int (*tcl_ZlibStreamReset) (Tcl_ZlibStream zshandle); /* 621 */
+ void (*tcl_SetStartupScript) (Tcl_Obj *path, const char *encoding); /* 622 */
+ Tcl_Obj * (*tcl_GetStartupScript) (const char **encodingPtr); /* 623 */
+ int (*tcl_CloseEx) (Tcl_Interp *interp, Tcl_Channel chan, int flags); /* 624 */
+ int (*tcl_NRExprObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, Tcl_Obj *resultPtr); /* 625 */
+ int (*tcl_NRSubstObj) (Tcl_Interp *interp, Tcl_Obj *objPtr, int flags); /* 626 */
+ int (*tcl_LoadFile) (Tcl_Interp *interp, Tcl_Obj *pathPtr, const char *const symv[], int flags, void *procPtrs, Tcl_LoadHandle *handlePtr); /* 627 */
+ void * (*tcl_FindSymbol) (Tcl_Interp *interp, Tcl_LoadHandle handle, const char *symbol); /* 628 */
+ int (*tcl_FSUnloadFile) (Tcl_Interp *interp, Tcl_LoadHandle handlePtr); /* 629 */
+ void (*tcl_ZlibStreamSetCompressionDictionary) (Tcl_ZlibStream zhandle, Tcl_Obj *compressionDictionaryObj); /* 630 */
+} TclStubs;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern const TclStubs *tclStubsPtr;
+#ifdef __cplusplus
+}
+#endif
+
+#if defined(USE_TCL_STUBS)
+
+/*
+ * Inline function declarations:
+ */
+
+#define Tcl_PkgProvideEx \
+ (tclStubsPtr->tcl_PkgProvideEx) /* 0 */
+#define Tcl_PkgRequireEx \
+ (tclStubsPtr->tcl_PkgRequireEx) /* 1 */
+#define Tcl_Panic \
+ (tclStubsPtr->tcl_Panic) /* 2 */
+#define Tcl_Alloc \
+ (tclStubsPtr->tcl_Alloc) /* 3 */
+#define Tcl_Free \
+ (tclStubsPtr->tcl_Free) /* 4 */
+#define Tcl_Realloc \
+ (tclStubsPtr->tcl_Realloc) /* 5 */
+#define Tcl_DbCkalloc \
+ (tclStubsPtr->tcl_DbCkalloc) /* 6 */
+#define Tcl_DbCkfree \
+ (tclStubsPtr->tcl_DbCkfree) /* 7 */
+#define Tcl_DbCkrealloc \
+ (tclStubsPtr->tcl_DbCkrealloc) /* 8 */
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+#define Tcl_CreateFileHandler \
+ (tclStubsPtr->tcl_CreateFileHandler) /* 9 */
+#endif /* UNIX */
+#ifdef MAC_OSX_TCL /* MACOSX */
+#define Tcl_CreateFileHandler \
+ (tclStubsPtr->tcl_CreateFileHandler) /* 9 */
+#endif /* MACOSX */
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+#define Tcl_DeleteFileHandler \
+ (tclStubsPtr->tcl_DeleteFileHandler) /* 10 */
+#endif /* UNIX */
+#ifdef MAC_OSX_TCL /* MACOSX */
+#define Tcl_DeleteFileHandler \
+ (tclStubsPtr->tcl_DeleteFileHandler) /* 10 */
+#endif /* MACOSX */
+#define Tcl_SetTimer \
+ (tclStubsPtr->tcl_SetTimer) /* 11 */
+#define Tcl_Sleep \
+ (tclStubsPtr->tcl_Sleep) /* 12 */
+#define Tcl_WaitForEvent \
+ (tclStubsPtr->tcl_WaitForEvent) /* 13 */
+#define Tcl_AppendAllObjTypes \
+ (tclStubsPtr->tcl_AppendAllObjTypes) /* 14 */
+#define Tcl_AppendStringsToObj \
+ (tclStubsPtr->tcl_AppendStringsToObj) /* 15 */
+#define Tcl_AppendToObj \
+ (tclStubsPtr->tcl_AppendToObj) /* 16 */
+#define Tcl_ConcatObj \
+ (tclStubsPtr->tcl_ConcatObj) /* 17 */
+#define Tcl_ConvertToType \
+ (tclStubsPtr->tcl_ConvertToType) /* 18 */
+#define Tcl_DbDecrRefCount \
+ (tclStubsPtr->tcl_DbDecrRefCount) /* 19 */
+#define Tcl_DbIncrRefCount \
+ (tclStubsPtr->tcl_DbIncrRefCount) /* 20 */
+#define Tcl_DbIsShared \
+ (tclStubsPtr->tcl_DbIsShared) /* 21 */
+#define Tcl_DbNewBooleanObj \
+ (tclStubsPtr->tcl_DbNewBooleanObj) /* 22 */
+#define Tcl_DbNewByteArrayObj \
+ (tclStubsPtr->tcl_DbNewByteArrayObj) /* 23 */
+#define Tcl_DbNewDoubleObj \
+ (tclStubsPtr->tcl_DbNewDoubleObj) /* 24 */
+#define Tcl_DbNewListObj \
+ (tclStubsPtr->tcl_DbNewListObj) /* 25 */
+#define Tcl_DbNewLongObj \
+ (tclStubsPtr->tcl_DbNewLongObj) /* 26 */
+#define Tcl_DbNewObj \
+ (tclStubsPtr->tcl_DbNewObj) /* 27 */
+#define Tcl_DbNewStringObj \
+ (tclStubsPtr->tcl_DbNewStringObj) /* 28 */
+#define Tcl_DuplicateObj \
+ (tclStubsPtr->tcl_DuplicateObj) /* 29 */
+#define TclFreeObj \
+ (tclStubsPtr->tclFreeObj) /* 30 */
+#define Tcl_GetBoolean \
+ (tclStubsPtr->tcl_GetBoolean) /* 31 */
+#define Tcl_GetBooleanFromObj \
+ (tclStubsPtr->tcl_GetBooleanFromObj) /* 32 */
+#define Tcl_GetByteArrayFromObj \
+ (tclStubsPtr->tcl_GetByteArrayFromObj) /* 33 */
+#define Tcl_GetDouble \
+ (tclStubsPtr->tcl_GetDouble) /* 34 */
+#define Tcl_GetDoubleFromObj \
+ (tclStubsPtr->tcl_GetDoubleFromObj) /* 35 */
+#define Tcl_GetIndexFromObj \
+ (tclStubsPtr->tcl_GetIndexFromObj) /* 36 */
+#define Tcl_GetInt \
+ (tclStubsPtr->tcl_GetInt) /* 37 */
+#define Tcl_GetIntFromObj \
+ (tclStubsPtr->tcl_GetIntFromObj) /* 38 */
+#define Tcl_GetLongFromObj \
+ (tclStubsPtr->tcl_GetLongFromObj) /* 39 */
+#define Tcl_GetObjType \
+ (tclStubsPtr->tcl_GetObjType) /* 40 */
+#define Tcl_GetStringFromObj \
+ (tclStubsPtr->tcl_GetStringFromObj) /* 41 */
+#define Tcl_InvalidateStringRep \
+ (tclStubsPtr->tcl_InvalidateStringRep) /* 42 */
+#define Tcl_ListObjAppendList \
+ (tclStubsPtr->tcl_ListObjAppendList) /* 43 */
+#define Tcl_ListObjAppendElement \
+ (tclStubsPtr->tcl_ListObjAppendElement) /* 44 */
+#define Tcl_ListObjGetElements \
+ (tclStubsPtr->tcl_ListObjGetElements) /* 45 */
+#define Tcl_ListObjIndex \
+ (tclStubsPtr->tcl_ListObjIndex) /* 46 */
+#define Tcl_ListObjLength \
+ (tclStubsPtr->tcl_ListObjLength) /* 47 */
+#define Tcl_ListObjReplace \
+ (tclStubsPtr->tcl_ListObjReplace) /* 48 */
+#define Tcl_NewBooleanObj \
+ (tclStubsPtr->tcl_NewBooleanObj) /* 49 */
+#define Tcl_NewByteArrayObj \
+ (tclStubsPtr->tcl_NewByteArrayObj) /* 50 */
+#define Tcl_NewDoubleObj \
+ (tclStubsPtr->tcl_NewDoubleObj) /* 51 */
+#define Tcl_NewIntObj \
+ (tclStubsPtr->tcl_NewIntObj) /* 52 */
+#define Tcl_NewListObj \
+ (tclStubsPtr->tcl_NewListObj) /* 53 */
+#define Tcl_NewLongObj \
+ (tclStubsPtr->tcl_NewLongObj) /* 54 */
+#define Tcl_NewObj \
+ (tclStubsPtr->tcl_NewObj) /* 55 */
+#define Tcl_NewStringObj \
+ (tclStubsPtr->tcl_NewStringObj) /* 56 */
+#define Tcl_SetBooleanObj \
+ (tclStubsPtr->tcl_SetBooleanObj) /* 57 */
+#define Tcl_SetByteArrayLength \
+ (tclStubsPtr->tcl_SetByteArrayLength) /* 58 */
+#define Tcl_SetByteArrayObj \
+ (tclStubsPtr->tcl_SetByteArrayObj) /* 59 */
+#define Tcl_SetDoubleObj \
+ (tclStubsPtr->tcl_SetDoubleObj) /* 60 */
+#define Tcl_SetIntObj \
+ (tclStubsPtr->tcl_SetIntObj) /* 61 */
+#define Tcl_SetListObj \
+ (tclStubsPtr->tcl_SetListObj) /* 62 */
+#define Tcl_SetLongObj \
+ (tclStubsPtr->tcl_SetLongObj) /* 63 */
+#define Tcl_SetObjLength \
+ (tclStubsPtr->tcl_SetObjLength) /* 64 */
+#define Tcl_SetStringObj \
+ (tclStubsPtr->tcl_SetStringObj) /* 65 */
+#define Tcl_AddErrorInfo \
+ (tclStubsPtr->tcl_AddErrorInfo) /* 66 */
+#define Tcl_AddObjErrorInfo \
+ (tclStubsPtr->tcl_AddObjErrorInfo) /* 67 */
+#define Tcl_AllowExceptions \
+ (tclStubsPtr->tcl_AllowExceptions) /* 68 */
+#define Tcl_AppendElement \
+ (tclStubsPtr->tcl_AppendElement) /* 69 */
+#define Tcl_AppendResult \
+ (tclStubsPtr->tcl_AppendResult) /* 70 */
+#define Tcl_AsyncCreate \
+ (tclStubsPtr->tcl_AsyncCreate) /* 71 */
+#define Tcl_AsyncDelete \
+ (tclStubsPtr->tcl_AsyncDelete) /* 72 */
+#define Tcl_AsyncInvoke \
+ (tclStubsPtr->tcl_AsyncInvoke) /* 73 */
+#define Tcl_AsyncMark \
+ (tclStubsPtr->tcl_AsyncMark) /* 74 */
+#define Tcl_AsyncReady \
+ (tclStubsPtr->tcl_AsyncReady) /* 75 */
+#define Tcl_BackgroundError \
+ (tclStubsPtr->tcl_BackgroundError) /* 76 */
+#define Tcl_Backslash \
+ (tclStubsPtr->tcl_Backslash) /* 77 */
+#define Tcl_BadChannelOption \
+ (tclStubsPtr->tcl_BadChannelOption) /* 78 */
+#define Tcl_CallWhenDeleted \
+ (tclStubsPtr->tcl_CallWhenDeleted) /* 79 */
+#define Tcl_CancelIdleCall \
+ (tclStubsPtr->tcl_CancelIdleCall) /* 80 */
+#define Tcl_Close \
+ (tclStubsPtr->tcl_Close) /* 81 */
+#define Tcl_CommandComplete \
+ (tclStubsPtr->tcl_CommandComplete) /* 82 */
+#define Tcl_Concat \
+ (tclStubsPtr->tcl_Concat) /* 83 */
+#define Tcl_ConvertElement \
+ (tclStubsPtr->tcl_ConvertElement) /* 84 */
+#define Tcl_ConvertCountedElement \
+ (tclStubsPtr->tcl_ConvertCountedElement) /* 85 */
+#define Tcl_CreateAlias \
+ (tclStubsPtr->tcl_CreateAlias) /* 86 */
+#define Tcl_CreateAliasObj \
+ (tclStubsPtr->tcl_CreateAliasObj) /* 87 */
+#define Tcl_CreateChannel \
+ (tclStubsPtr->tcl_CreateChannel) /* 88 */
+#define Tcl_CreateChannelHandler \
+ (tclStubsPtr->tcl_CreateChannelHandler) /* 89 */
+#define Tcl_CreateCloseHandler \
+ (tclStubsPtr->tcl_CreateCloseHandler) /* 90 */
+#define Tcl_CreateCommand \
+ (tclStubsPtr->tcl_CreateCommand) /* 91 */
+#define Tcl_CreateEventSource \
+ (tclStubsPtr->tcl_CreateEventSource) /* 92 */
+#define Tcl_CreateExitHandler \
+ (tclStubsPtr->tcl_CreateExitHandler) /* 93 */
+#define Tcl_CreateInterp \
+ (tclStubsPtr->tcl_CreateInterp) /* 94 */
+#define Tcl_CreateMathFunc \
+ (tclStubsPtr->tcl_CreateMathFunc) /* 95 */
+#define Tcl_CreateObjCommand \
+ (tclStubsPtr->tcl_CreateObjCommand) /* 96 */
+#define Tcl_CreateSlave \
+ (tclStubsPtr->tcl_CreateSlave) /* 97 */
+#define Tcl_CreateTimerHandler \
+ (tclStubsPtr->tcl_CreateTimerHandler) /* 98 */
+#define Tcl_CreateTrace \
+ (tclStubsPtr->tcl_CreateTrace) /* 99 */
+#define Tcl_DeleteAssocData \
+ (tclStubsPtr->tcl_DeleteAssocData) /* 100 */
+#define Tcl_DeleteChannelHandler \
+ (tclStubsPtr->tcl_DeleteChannelHandler) /* 101 */
+#define Tcl_DeleteCloseHandler \
+ (tclStubsPtr->tcl_DeleteCloseHandler) /* 102 */
+#define Tcl_DeleteCommand \
+ (tclStubsPtr->tcl_DeleteCommand) /* 103 */
+#define Tcl_DeleteCommandFromToken \
+ (tclStubsPtr->tcl_DeleteCommandFromToken) /* 104 */
+#define Tcl_DeleteEvents \
+ (tclStubsPtr->tcl_DeleteEvents) /* 105 */
+#define Tcl_DeleteEventSource \
+ (tclStubsPtr->tcl_DeleteEventSource) /* 106 */
+#define Tcl_DeleteExitHandler \
+ (tclStubsPtr->tcl_DeleteExitHandler) /* 107 */
+#define Tcl_DeleteHashEntry \
+ (tclStubsPtr->tcl_DeleteHashEntry) /* 108 */
+#define Tcl_DeleteHashTable \
+ (tclStubsPtr->tcl_DeleteHashTable) /* 109 */
+#define Tcl_DeleteInterp \
+ (tclStubsPtr->tcl_DeleteInterp) /* 110 */
+#define Tcl_DetachPids \
+ (tclStubsPtr->tcl_DetachPids) /* 111 */
+#define Tcl_DeleteTimerHandler \
+ (tclStubsPtr->tcl_DeleteTimerHandler) /* 112 */
+#define Tcl_DeleteTrace \
+ (tclStubsPtr->tcl_DeleteTrace) /* 113 */
+#define Tcl_DontCallWhenDeleted \
+ (tclStubsPtr->tcl_DontCallWhenDeleted) /* 114 */
+#define Tcl_DoOneEvent \
+ (tclStubsPtr->tcl_DoOneEvent) /* 115 */
+#define Tcl_DoWhenIdle \
+ (tclStubsPtr->tcl_DoWhenIdle) /* 116 */
+#define Tcl_DStringAppend \
+ (tclStubsPtr->tcl_DStringAppend) /* 117 */
+#define Tcl_DStringAppendElement \
+ (tclStubsPtr->tcl_DStringAppendElement) /* 118 */
+#define Tcl_DStringEndSublist \
+ (tclStubsPtr->tcl_DStringEndSublist) /* 119 */
+#define Tcl_DStringFree \
+ (tclStubsPtr->tcl_DStringFree) /* 120 */
+#define Tcl_DStringGetResult \
+ (tclStubsPtr->tcl_DStringGetResult) /* 121 */
+#define Tcl_DStringInit \
+ (tclStubsPtr->tcl_DStringInit) /* 122 */
+#define Tcl_DStringResult \
+ (tclStubsPtr->tcl_DStringResult) /* 123 */
+#define Tcl_DStringSetLength \
+ (tclStubsPtr->tcl_DStringSetLength) /* 124 */
+#define Tcl_DStringStartSublist \
+ (tclStubsPtr->tcl_DStringStartSublist) /* 125 */
+#define Tcl_Eof \
+ (tclStubsPtr->tcl_Eof) /* 126 */
+#define Tcl_ErrnoId \
+ (tclStubsPtr->tcl_ErrnoId) /* 127 */
+#define Tcl_ErrnoMsg \
+ (tclStubsPtr->tcl_ErrnoMsg) /* 128 */
+#define Tcl_Eval \
+ (tclStubsPtr->tcl_Eval) /* 129 */
+#define Tcl_EvalFile \
+ (tclStubsPtr->tcl_EvalFile) /* 130 */
+#define Tcl_EvalObj \
+ (tclStubsPtr->tcl_EvalObj) /* 131 */
+#define Tcl_EventuallyFree \
+ (tclStubsPtr->tcl_EventuallyFree) /* 132 */
+#define Tcl_Exit \
+ (tclStubsPtr->tcl_Exit) /* 133 */
+#define Tcl_ExposeCommand \
+ (tclStubsPtr->tcl_ExposeCommand) /* 134 */
+#define Tcl_ExprBoolean \
+ (tclStubsPtr->tcl_ExprBoolean) /* 135 */
+#define Tcl_ExprBooleanObj \
+ (tclStubsPtr->tcl_ExprBooleanObj) /* 136 */
+#define Tcl_ExprDouble \
+ (tclStubsPtr->tcl_ExprDouble) /* 137 */
+#define Tcl_ExprDoubleObj \
+ (tclStubsPtr->tcl_ExprDoubleObj) /* 138 */
+#define Tcl_ExprLong \
+ (tclStubsPtr->tcl_ExprLong) /* 139 */
+#define Tcl_ExprLongObj \
+ (tclStubsPtr->tcl_ExprLongObj) /* 140 */
+#define Tcl_ExprObj \
+ (tclStubsPtr->tcl_ExprObj) /* 141 */
+#define Tcl_ExprString \
+ (tclStubsPtr->tcl_ExprString) /* 142 */
+#define Tcl_Finalize \
+ (tclStubsPtr->tcl_Finalize) /* 143 */
+#define Tcl_FindExecutable \
+ (tclStubsPtr->tcl_FindExecutable) /* 144 */
+#define Tcl_FirstHashEntry \
+ (tclStubsPtr->tcl_FirstHashEntry) /* 145 */
+#define Tcl_Flush \
+ (tclStubsPtr->tcl_Flush) /* 146 */
+#define Tcl_FreeResult \
+ (tclStubsPtr->tcl_FreeResult) /* 147 */
+#define Tcl_GetAlias \
+ (tclStubsPtr->tcl_GetAlias) /* 148 */
+#define Tcl_GetAliasObj \
+ (tclStubsPtr->tcl_GetAliasObj) /* 149 */
+#define Tcl_GetAssocData \
+ (tclStubsPtr->tcl_GetAssocData) /* 150 */
+#define Tcl_GetChannel \
+ (tclStubsPtr->tcl_GetChannel) /* 151 */
+#define Tcl_GetChannelBufferSize \
+ (tclStubsPtr->tcl_GetChannelBufferSize) /* 152 */
+#define Tcl_GetChannelHandle \
+ (tclStubsPtr->tcl_GetChannelHandle) /* 153 */
+#define Tcl_GetChannelInstanceData \
+ (tclStubsPtr->tcl_GetChannelInstanceData) /* 154 */
+#define Tcl_GetChannelMode \
+ (tclStubsPtr->tcl_GetChannelMode) /* 155 */
+#define Tcl_GetChannelName \
+ (tclStubsPtr->tcl_GetChannelName) /* 156 */
+#define Tcl_GetChannelOption \
+ (tclStubsPtr->tcl_GetChannelOption) /* 157 */
+#define Tcl_GetChannelType \
+ (tclStubsPtr->tcl_GetChannelType) /* 158 */
+#define Tcl_GetCommandInfo \
+ (tclStubsPtr->tcl_GetCommandInfo) /* 159 */
+#define Tcl_GetCommandName \
+ (tclStubsPtr->tcl_GetCommandName) /* 160 */
+#define Tcl_GetErrno \
+ (tclStubsPtr->tcl_GetErrno) /* 161 */
+#define Tcl_GetHostName \
+ (tclStubsPtr->tcl_GetHostName) /* 162 */
+#define Tcl_GetInterpPath \
+ (tclStubsPtr->tcl_GetInterpPath) /* 163 */
+#define Tcl_GetMaster \
+ (tclStubsPtr->tcl_GetMaster) /* 164 */
+#define Tcl_GetNameOfExecutable \
+ (tclStubsPtr->tcl_GetNameOfExecutable) /* 165 */
+#define Tcl_GetObjResult \
+ (tclStubsPtr->tcl_GetObjResult) /* 166 */
+#if !defined(__WIN32__) && !defined(MAC_OSX_TCL) /* UNIX */
+#define Tcl_GetOpenFile \
+ (tclStubsPtr->tcl_GetOpenFile) /* 167 */
+#endif /* UNIX */
+#ifdef MAC_OSX_TCL /* MACOSX */
+#define Tcl_GetOpenFile \
+ (tclStubsPtr->tcl_GetOpenFile) /* 167 */
+#endif /* MACOSX */
+#define Tcl_GetPathType \
+ (tclStubsPtr->tcl_GetPathType) /* 168 */
+#define Tcl_Gets \
+ (tclStubsPtr->tcl_Gets) /* 169 */
+#define Tcl_GetsObj \
+ (tclStubsPtr->tcl_GetsObj) /* 170 */
+#define Tcl_GetServiceMode \
+ (tclStubsPtr->tcl_GetServiceMode) /* 171 */
+#define Tcl_GetSlave \
+ (tclStubsPtr->tcl_GetSlave) /* 172 */
+#define Tcl_GetStdChannel \
+ (tclStubsPtr->tcl_GetStdChannel) /* 173 */
+#define Tcl_GetStringResult \
+ (tclStubsPtr->tcl_GetStringResult) /* 174 */
+#define Tcl_GetVar \
+ (tclStubsPtr->tcl_GetVar) /* 175 */
+#define Tcl_GetVar2 \
+ (tclStubsPtr->tcl_GetVar2) /* 176 */
+#define Tcl_GlobalEval \
+ (tclStubsPtr->tcl_GlobalEval) /* 177 */
+#define Tcl_GlobalEvalObj \
+ (tclStubsPtr->tcl_GlobalEvalObj) /* 178 */
+#define Tcl_HideCommand \
+ (tclStubsPtr->tcl_HideCommand) /* 179 */
+#define Tcl_Init \
+ (tclStubsPtr->tcl_Init) /* 180 */
+#define Tcl_InitHashTable \
+ (tclStubsPtr->tcl_InitHashTable) /* 181 */
+#define Tcl_InputBlocked \
+ (tclStubsPtr->tcl_InputBlocked) /* 182 */
+#define Tcl_InputBuffered \
+ (tclStubsPtr->tcl_InputBuffered) /* 183 */
+#define Tcl_InterpDeleted \
+ (tclStubsPtr->tcl_InterpDeleted) /* 184 */
+#define Tcl_IsSafe \
+ (tclStubsPtr->tcl_IsSafe) /* 185 */
+#define Tcl_JoinPath \
+ (tclStubsPtr->tcl_JoinPath) /* 186 */
+#define Tcl_LinkVar \
+ (tclStubsPtr->tcl_LinkVar) /* 187 */
+/* Slot 188 is reserved */
+#define Tcl_MakeFileChannel \
+ (tclStubsPtr->tcl_MakeFileChannel) /* 189 */
+#define Tcl_MakeSafe \
+ (tclStubsPtr->tcl_MakeSafe) /* 190 */
+#define Tcl_MakeTcpClientChannel \
+ (tclStubsPtr->tcl_MakeTcpClientChannel) /* 191 */
+#define Tcl_Merge \
+ (tclStubsPtr->tcl_Merge) /* 192 */
+#define Tcl_NextHashEntry \
+ (tclStubsPtr->tcl_NextHashEntry) /* 193 */
+#define Tcl_NotifyChannel \
+ (tclStubsPtr->tcl_NotifyChannel) /* 194 */
+#define Tcl_ObjGetVar2 \
+ (tclStubsPtr->tcl_ObjGetVar2) /* 195 */
+#define Tcl_ObjSetVar2 \
+ (tclStubsPtr->tcl_ObjSetVar2) /* 196 */
+#define Tcl_OpenCommandChannel \
+ (tclStubsPtr->tcl_OpenCommandChannel) /* 197 */
+#define Tcl_OpenFileChannel \
+ (tclStubsPtr->tcl_OpenFileChannel) /* 198 */
+#define Tcl_OpenTcpClient \
+ (tclStubsPtr->tcl_OpenTcpClient) /* 199 */
+#define Tcl_OpenTcpServer \
+ (tclStubsPtr->tcl_OpenTcpServer) /* 200 */
+#define Tcl_Preserve \
+ (tclStubsPtr->tcl_Preserve) /* 201 */
+#define Tcl_PrintDouble \
+ (tclStubsPtr->tcl_PrintDouble) /* 202 */
+#define Tcl_PutEnv \
+ (tclStubsPtr->tcl_PutEnv) /* 203 */
+#define Tcl_PosixError \
+ (tclStubsPtr->tcl_PosixError) /* 204 */
+#define Tcl_QueueEvent \
+ (tclStubsPtr->tcl_QueueEvent) /* 205 */
+#define Tcl_Read \
+ (tclStubsPtr->tcl_Read) /* 206 */
+#define Tcl_ReapDetachedProcs \
+ (tclStubsPtr->tcl_ReapDetachedProcs) /* 207 */
+#define Tcl_RecordAndEval \
+ (tclStubsPtr->tcl_RecordAndEval) /* 208 */
+#define Tcl_RecordAndEvalObj \
+ (tclStubsPtr->tcl_RecordAndEvalObj) /* 209 */
+#define Tcl_RegisterChannel \
+ (tclStubsPtr->tcl_RegisterChannel) /* 210 */
+#define Tcl_RegisterObjType \
+ (tclStubsPtr->tcl_RegisterObjType) /* 211 */
+#define Tcl_RegExpCompile \
+ (tclStubsPtr->tcl_RegExpCompile) /* 212 */
+#define Tcl_RegExpExec \
+ (tclStubsPtr->tcl_RegExpExec) /* 213 */
+#define Tcl_RegExpMatch \
+ (tclStubsPtr->tcl_RegExpMatch) /* 214 */
+#define Tcl_RegExpRange \
+ (tclStubsPtr->tcl_RegExpRange) /* 215 */
+#define Tcl_Release \
+ (tclStubsPtr->tcl_Release) /* 216 */
+#define Tcl_ResetResult \
+ (tclStubsPtr->tcl_ResetResult) /* 217 */
+#define Tcl_ScanElement \
+ (tclStubsPtr->tcl_ScanElement) /* 218 */
+#define Tcl_ScanCountedElement \
+ (tclStubsPtr->tcl_ScanCountedElement) /* 219 */
+#define Tcl_SeekOld \
+ (tclStubsPtr->tcl_SeekOld) /* 220 */
+#define Tcl_ServiceAll \
+ (tclStubsPtr->tcl_ServiceAll) /* 221 */
+#define Tcl_ServiceEvent \
+ (tclStubsPtr->tcl_ServiceEvent) /* 222 */
+#define Tcl_SetAssocData \
+ (tclStubsPtr->tcl_SetAssocData) /* 223 */
+#define Tcl_SetChannelBufferSize \
+ (tclStubsPtr->tcl_SetChannelBufferSize) /* 224 */
+#define Tcl_SetChannelOption \
+ (tclStubsPtr->tcl_SetChannelOption) /* 225 */
+#define Tcl_SetCommandInfo \
+ (tclStubsPtr->tcl_SetCommandInfo) /* 226 */
+#define Tcl_SetErrno \
+ (tclStubsPtr->tcl_SetErrno) /* 227 */
+#define Tcl_SetErrorCode \
+ (tclStubsPtr->tcl_SetErrorCode) /* 228 */
+#define Tcl_SetMaxBlockTime \
+ (tclStubsPtr->tcl_SetMaxBlockTime) /* 229 */
+#define Tcl_SetPanicProc \
+ (tclStubsPtr->tcl_SetPanicProc) /* 230 */
+#define Tcl_SetRecursionLimit \
+ (tclStubsPtr->tcl_SetRecursionLimit) /* 231 */
+#define Tcl_SetResult \
+ (tclStubsPtr->tcl_SetResult) /* 232 */
+#define Tcl_SetServiceMode \
+ (tclStubsPtr->tcl_SetServiceMode) /* 233 */
+#define Tcl_SetObjErrorCode \
+ (tclStubsPtr->tcl_SetObjErrorCode) /* 234 */
+#define Tcl_SetObjResult \
+ (tclStubsPtr->tcl_SetObjResult) /* 235 */
+#define Tcl_SetStdChannel \
+ (tclStubsPtr->tcl_SetStdChannel) /* 236 */
+#define Tcl_SetVar \
+ (tclStubsPtr->tcl_SetVar) /* 237 */
+#define Tcl_SetVar2 \
+ (tclStubsPtr->tcl_SetVar2) /* 238 */
+#define Tcl_SignalId \
+ (tclStubsPtr->tcl_SignalId) /* 239 */
+#define Tcl_SignalMsg \
+ (tclStubsPtr->tcl_SignalMsg) /* 240 */
+#define Tcl_SourceRCFile \
+ (tclStubsPtr->tcl_SourceRCFile) /* 241 */
+#define Tcl_SplitList \
+ (tclStubsPtr->tcl_SplitList) /* 242 */
+#define Tcl_SplitPath \
+ (tclStubsPtr->tcl_SplitPath) /* 243 */
+#define Tcl_StaticPackage \
+ (tclStubsPtr->tcl_StaticPackage) /* 244 */
+#define Tcl_StringMatch \
+ (tclStubsPtr->tcl_StringMatch) /* 245 */
+#define Tcl_TellOld \
+ (tclStubsPtr->tcl_TellOld) /* 246 */
+#define Tcl_TraceVar \
+ (tclStubsPtr->tcl_TraceVar) /* 247 */
+#define Tcl_TraceVar2 \
+ (tclStubsPtr->tcl_TraceVar2) /* 248 */
+#define Tcl_TranslateFileName \
+ (tclStubsPtr->tcl_TranslateFileName) /* 249 */
+#define Tcl_Ungets \
+ (tclStubsPtr->tcl_Ungets) /* 250 */
+#define Tcl_UnlinkVar \
+ (tclStubsPtr->tcl_UnlinkVar) /* 251 */
+#define Tcl_UnregisterChannel \
+ (tclStubsPtr->tcl_UnregisterChannel) /* 252 */
+#define Tcl_UnsetVar \
+ (tclStubsPtr->tcl_UnsetVar) /* 253 */
+#define Tcl_UnsetVar2 \
+ (tclStubsPtr->tcl_UnsetVar2) /* 254 */
+#define Tcl_UntraceVar \
+ (tclStubsPtr->tcl_UntraceVar) /* 255 */
+#define Tcl_UntraceVar2 \
+ (tclStubsPtr->tcl_UntraceVar2) /* 256 */
+#define Tcl_UpdateLinkedVar \
+ (tclStubsPtr->tcl_UpdateLinkedVar) /* 257 */
+#define Tcl_UpVar \
+ (tclStubsPtr->tcl_UpVar) /* 258 */
+#define Tcl_UpVar2 \
+ (tclStubsPtr->tcl_UpVar2) /* 259 */
+#define Tcl_VarEval \
+ (tclStubsPtr->tcl_VarEval) /* 260 */
+#define Tcl_VarTraceInfo \
+ (tclStubsPtr->tcl_VarTraceInfo) /* 261 */
+#define Tcl_VarTraceInfo2 \
+ (tclStubsPtr->tcl_VarTraceInfo2) /* 262 */
+#define Tcl_Write \
+ (tclStubsPtr->tcl_Write) /* 263 */
+#define Tcl_WrongNumArgs \
+ (tclStubsPtr->tcl_WrongNumArgs) /* 264 */
+#define Tcl_DumpActiveMemory \
+ (tclStubsPtr->tcl_DumpActiveMemory) /* 265 */
+#define Tcl_ValidateAllMemory \
+ (tclStubsPtr->tcl_ValidateAllMemory) /* 266 */
+#define Tcl_AppendResultVA \
+ (tclStubsPtr->tcl_AppendResultVA) /* 267 */
+#define Tcl_AppendStringsToObjVA \
+ (tclStubsPtr->tcl_AppendStringsToObjVA) /* 268 */
+#define Tcl_HashStats \
+ (tclStubsPtr->tcl_HashStats) /* 269 */
+#define Tcl_ParseVar \
+ (tclStubsPtr->tcl_ParseVar) /* 270 */
+#define Tcl_PkgPresent \
+ (tclStubsPtr->tcl_PkgPresent) /* 271 */
+#define Tcl_PkgPresentEx \
+ (tclStubsPtr->tcl_PkgPresentEx) /* 272 */
+#define Tcl_PkgProvide \
+ (tclStubsPtr->tcl_PkgProvide) /* 273 */
+#define Tcl_PkgRequire \
+ (tclStubsPtr->tcl_PkgRequire) /* 274 */
+#define Tcl_SetErrorCodeVA \
+ (tclStubsPtr->tcl_SetErrorCodeVA) /* 275 */
+#define Tcl_VarEvalVA \
+ (tclStubsPtr->tcl_VarEvalVA) /* 276 */
+#define Tcl_WaitPid \
+ (tclStubsPtr->tcl_WaitPid) /* 277 */
+#define Tcl_PanicVA \
+ (tclStubsPtr->tcl_PanicVA) /* 278 */
+#define Tcl_GetVersion \
+ (tclStubsPtr->tcl_GetVersion) /* 279 */
+#define Tcl_InitMemory \
+ (tclStubsPtr->tcl_InitMemory) /* 280 */
+#define Tcl_StackChannel \
+ (tclStubsPtr->tcl_StackChannel) /* 281 */
+#define Tcl_UnstackChannel \
+ (tclStubsPtr->tcl_UnstackChannel) /* 282 */
+#define Tcl_GetStackedChannel \
+ (tclStubsPtr->tcl_GetStackedChannel) /* 283 */
+#define Tcl_SetMainLoop \
+ (tclStubsPtr->tcl_SetMainLoop) /* 284 */
+/* Slot 285 is reserved */
+#define Tcl_AppendObjToObj \
+ (tclStubsPtr->tcl_AppendObjToObj) /* 286 */
+#define Tcl_CreateEncoding \
+ (tclStubsPtr->tcl_CreateEncoding) /* 287 */
+#define Tcl_CreateThreadExitHandler \
+ (tclStubsPtr->tcl_CreateThreadExitHandler) /* 288 */
+#define Tcl_DeleteThreadExitHandler \
+ (tclStubsPtr->tcl_DeleteThreadExitHandler) /* 289 */
+#define Tcl_DiscardResult \
+ (tclStubsPtr->tcl_DiscardResult) /* 290 */
+#define Tcl_EvalEx \
+ (tclStubsPtr->tcl_EvalEx) /* 291 */
+#define Tcl_EvalObjv \
+ (tclStubsPtr->tcl_EvalObjv) /* 292 */
+#define Tcl_EvalObjEx \
+ (tclStubsPtr->tcl_EvalObjEx) /* 293 */
+#define Tcl_ExitThread \
+ (tclStubsPtr->tcl_ExitThread) /* 294 */
+#define Tcl_ExternalToUtf \
+ (tclStubsPtr->tcl_ExternalToUtf) /* 295 */
+#define Tcl_ExternalToUtfDString \
+ (tclStubsPtr->tcl_ExternalToUtfDString) /* 296 */
+#define Tcl_FinalizeThread \
+ (tclStubsPtr->tcl_FinalizeThread) /* 297 */
+#define Tcl_FinalizeNotifier \
+ (tclStubsPtr->tcl_FinalizeNotifier) /* 298 */
+#define Tcl_FreeEncoding \
+ (tclStubsPtr->tcl_FreeEncoding) /* 299 */
+#define Tcl_GetCurrentThread \
+ (tclStubsPtr->tcl_GetCurrentThread) /* 300 */
+#define Tcl_GetEncoding \
+ (tclStubsPtr->tcl_GetEncoding) /* 301 */
+#define Tcl_GetEncodingName \
+ (tclStubsPtr->tcl_GetEncodingName) /* 302 */
+#define Tcl_GetEncodingNames \
+ (tclStubsPtr->tcl_GetEncodingNames) /* 303 */
+#define Tcl_GetIndexFromObjStruct \
+ (tclStubsPtr->tcl_GetIndexFromObjStruct) /* 304 */
+#define Tcl_GetThreadData \
+ (tclStubsPtr->tcl_GetThreadData) /* 305 */
+#define Tcl_GetVar2Ex \
+ (tclStubsPtr->tcl_GetVar2Ex) /* 306 */
+#define Tcl_InitNotifier \
+ (tclStubsPtr->tcl_InitNotifier) /* 307 */
+#define Tcl_MutexLock \
+ (tclStubsPtr->tcl_MutexLock) /* 308 */
+#define Tcl_MutexUnlock \
+ (tclStubsPtr->tcl_MutexUnlock) /* 309 */
+#define Tcl_ConditionNotify \
+ (tclStubsPtr->tcl_ConditionNotify) /* 310 */
+#define Tcl_ConditionWait \
+ (tclStubsPtr->tcl_ConditionWait) /* 311 */
+#define Tcl_NumUtfChars \
+ (tclStubsPtr->tcl_NumUtfChars) /* 312 */
+#define Tcl_ReadChars \
+ (tclStubsPtr->tcl_ReadChars) /* 313 */
+#define Tcl_RestoreResult \
+ (tclStubsPtr->tcl_RestoreResult) /* 314 */
+#define Tcl_SaveResult \
+ (tclStubsPtr->tcl_SaveResult) /* 315 */
+#define Tcl_SetSystemEncoding \
+ (tclStubsPtr->tcl_SetSystemEncoding) /* 316 */
+#define Tcl_SetVar2Ex \
+ (tclStubsPtr->tcl_SetVar2Ex) /* 317 */
+#define Tcl_ThreadAlert \
+ (tclStubsPtr->tcl_ThreadAlert) /* 318 */
+#define Tcl_ThreadQueueEvent \
+ (tclStubsPtr->tcl_ThreadQueueEvent) /* 319 */
+#define Tcl_UniCharAtIndex \
+ (tclStubsPtr->tcl_UniCharAtIndex) /* 320 */
+#define Tcl_UniCharToLower \
+ (tclStubsPtr->tcl_UniCharToLower) /* 321 */
+#define Tcl_UniCharToTitle \
+ (tclStubsPtr->tcl_UniCharToTitle) /* 322 */
+#define Tcl_UniCharToUpper \
+ (tclStubsPtr->tcl_UniCharToUpper) /* 323 */
+#define Tcl_UniCharToUtf \
+ (tclStubsPtr->tcl_UniCharToUtf) /* 324 */
+#define Tcl_UtfAtIndex \
+ (tclStubsPtr->tcl_UtfAtIndex) /* 325 */
+#define Tcl_UtfCharComplete \
+ (tclStubsPtr->tcl_UtfCharComplete) /* 326 */
+#define Tcl_UtfBackslash \
+ (tclStubsPtr->tcl_UtfBackslash) /* 327 */
+#define Tcl_UtfFindFirst \
+ (tclStubsPtr->tcl_UtfFindFirst) /* 328 */
+#define Tcl_UtfFindLast \
+ (tclStubsPtr->tcl_UtfFindLast) /* 329 */
+#define Tcl_UtfNext \
+ (tclStubsPtr->tcl_UtfNext) /* 330 */
+#define Tcl_UtfPrev \
+ (tclStubsPtr->tcl_UtfPrev) /* 331 */
+#define Tcl_UtfToExternal \
+ (tclStubsPtr->tcl_UtfToExternal) /* 332 */
+#define Tcl_UtfToExternalDString \
+ (tclStubsPtr->tcl_UtfToExternalDString) /* 333 */
+#define Tcl_UtfToLower \
+ (tclStubsPtr->tcl_UtfToLower) /* 334 */
+#define Tcl_UtfToTitle \
+ (tclStubsPtr->tcl_UtfToTitle) /* 335 */
+#define Tcl_UtfToUniChar \
+ (tclStubsPtr->tcl_UtfToUniChar) /* 336 */
+#define Tcl_UtfToUpper \
+ (tclStubsPtr->tcl_UtfToUpper) /* 337 */
+#define Tcl_WriteChars \
+ (tclStubsPtr->tcl_WriteChars) /* 338 */
+#define Tcl_WriteObj \
+ (tclStubsPtr->tcl_WriteObj) /* 339 */
+#define Tcl_GetString \
+ (tclStubsPtr->tcl_GetString) /* 340 */
+#define Tcl_GetDefaultEncodingDir \
+ (tclStubsPtr->tcl_GetDefaultEncodingDir) /* 341 */
+#define Tcl_SetDefaultEncodingDir \
+ (tclStubsPtr->tcl_SetDefaultEncodingDir) /* 342 */
+#define Tcl_AlertNotifier \
+ (tclStubsPtr->tcl_AlertNotifier) /* 343 */
+#define Tcl_ServiceModeHook \
+ (tclStubsPtr->tcl_ServiceModeHook) /* 344 */
+#define Tcl_UniCharIsAlnum \
+ (tclStubsPtr->tcl_UniCharIsAlnum) /* 345 */
+#define Tcl_UniCharIsAlpha \
+ (tclStubsPtr->tcl_UniCharIsAlpha) /* 346 */
+#define Tcl_UniCharIsDigit \
+ (tclStubsPtr->tcl_UniCharIsDigit) /* 347 */
+#define Tcl_UniCharIsLower \
+ (tclStubsPtr->tcl_UniCharIsLower) /* 348 */
+#define Tcl_UniCharIsSpace \
+ (tclStubsPtr->tcl_UniCharIsSpace) /* 349 */
+#define Tcl_UniCharIsUpper \
+ (tclStubsPtr->tcl_UniCharIsUpper) /* 350 */
+#define Tcl_UniCharIsWordChar \
+ (tclStubsPtr->tcl_UniCharIsWordChar) /* 351 */
+#define Tcl_UniCharLen \
+ (tclStubsPtr->tcl_UniCharLen) /* 352 */
+#define Tcl_UniCharNcmp \
+ (tclStubsPtr->tcl_UniCharNcmp) /* 353 */
+#define Tcl_UniCharToUtfDString \
+ (tclStubsPtr->tcl_UniCharToUtfDString) /* 354 */
+#define Tcl_UtfToUniCharDString \
+ (tclStubsPtr->tcl_UtfToUniCharDString) /* 355 */
+#define Tcl_GetRegExpFromObj \
+ (tclStubsPtr->tcl_GetRegExpFromObj) /* 356 */
+#define Tcl_EvalTokens \
+ (tclStubsPtr->tcl_EvalTokens) /* 357 */
+#define Tcl_FreeParse \
+ (tclStubsPtr->tcl_FreeParse) /* 358 */
+#define Tcl_LogCommandInfo \
+ (tclStubsPtr->tcl_LogCommandInfo) /* 359 */
+#define Tcl_ParseBraces \
+ (tclStubsPtr->tcl_ParseBraces) /* 360 */
+#define Tcl_ParseCommand \
+ (tclStubsPtr->tcl_ParseCommand) /* 361 */
+#define Tcl_ParseExpr \
+ (tclStubsPtr->tcl_ParseExpr) /* 362 */
+#define Tcl_ParseQuotedString \
+ (tclStubsPtr->tcl_ParseQuotedString) /* 363 */
+#define Tcl_ParseVarName \
+ (tclStubsPtr->tcl_ParseVarName) /* 364 */
+#define Tcl_GetCwd \
+ (tclStubsPtr->tcl_GetCwd) /* 365 */
+#define Tcl_Chdir \
+ (tclStubsPtr->tcl_Chdir) /* 366 */
+#define Tcl_Access \
+ (tclStubsPtr->tcl_Access) /* 367 */
+#define Tcl_Stat \
+ (tclStubsPtr->tcl_Stat) /* 368 */
+#define Tcl_UtfNcmp \
+ (tclStubsPtr->tcl_UtfNcmp) /* 369 */
+#define Tcl_UtfNcasecmp \
+ (tclStubsPtr->tcl_UtfNcasecmp) /* 370 */
+#define Tcl_StringCaseMatch \
+ (tclStubsPtr->tcl_StringCaseMatch) /* 371 */
+#define Tcl_UniCharIsControl \
+ (tclStubsPtr->tcl_UniCharIsControl) /* 372 */
+#define Tcl_UniCharIsGraph \
+ (tclStubsPtr->tcl_UniCharIsGraph) /* 373 */
+#define Tcl_UniCharIsPrint \
+ (tclStubsPtr->tcl_UniCharIsPrint) /* 374 */
+#define Tcl_UniCharIsPunct \
+ (tclStubsPtr->tcl_UniCharIsPunct) /* 375 */
+#define Tcl_RegExpExecObj \
+ (tclStubsPtr->tcl_RegExpExecObj) /* 376 */
+#define Tcl_RegExpGetInfo \
+ (tclStubsPtr->tcl_RegExpGetInfo) /* 377 */
+#define Tcl_NewUnicodeObj \
+ (tclStubsPtr->tcl_NewUnicodeObj) /* 378 */
+#define Tcl_SetUnicodeObj \
+ (tclStubsPtr->tcl_SetUnicodeObj) /* 379 */
+#define Tcl_GetCharLength \
+ (tclStubsPtr->tcl_GetCharLength) /* 380 */
+#define Tcl_GetUniChar \
+ (tclStubsPtr->tcl_GetUniChar) /* 381 */
+#define Tcl_GetUnicode \
+ (tclStubsPtr->tcl_GetUnicode) /* 382 */
+#define Tcl_GetRange \
+ (tclStubsPtr->tcl_GetRange) /* 383 */
+#define Tcl_AppendUnicodeToObj \
+ (tclStubsPtr->tcl_AppendUnicodeToObj) /* 384 */
+#define Tcl_RegExpMatchObj \
+ (tclStubsPtr->tcl_RegExpMatchObj) /* 385 */
+#define Tcl_SetNotifier \
+ (tclStubsPtr->tcl_SetNotifier) /* 386 */
+#define Tcl_GetAllocMutex \
+ (tclStubsPtr->tcl_GetAllocMutex) /* 387 */
+#define Tcl_GetChannelNames \
+ (tclStubsPtr->tcl_GetChannelNames) /* 388 */
+#define Tcl_GetChannelNamesEx \
+ (tclStubsPtr->tcl_GetChannelNamesEx) /* 389 */
+#define Tcl_ProcObjCmd \
+ (tclStubsPtr->tcl_ProcObjCmd) /* 390 */
+#define Tcl_ConditionFinalize \
+ (tclStubsPtr->tcl_ConditionFinalize) /* 391 */
+#define Tcl_MutexFinalize \
+ (tclStubsPtr->tcl_MutexFinalize) /* 392 */
+#define Tcl_CreateThread \
+ (tclStubsPtr->tcl_CreateThread) /* 393 */
+#define Tcl_ReadRaw \
+ (tclStubsPtr->tcl_ReadRaw) /* 394 */
+#define Tcl_WriteRaw \
+ (tclStubsPtr->tcl_WriteRaw) /* 395 */
+#define Tcl_GetTopChannel \
+ (tclStubsPtr->tcl_GetTopChannel) /* 396 */
+#define Tcl_ChannelBuffered \
+ (tclStubsPtr->tcl_ChannelBuffered) /* 397 */
+#define Tcl_ChannelName \
+ (tclStubsPtr->tcl_ChannelName) /* 398 */
+#define Tcl_ChannelVersion \
+ (tclStubsPtr->tcl_ChannelVersion) /* 399 */
+#define Tcl_ChannelBlockModeProc \
+ (tclStubsPtr->tcl_ChannelBlockModeProc) /* 400 */
+#define Tcl_ChannelCloseProc \
+ (tclStubsPtr->tcl_ChannelCloseProc) /* 401 */
+#define Tcl_ChannelClose2Proc \
+ (tclStubsPtr->tcl_ChannelClose2Proc) /* 402 */
+#define Tcl_ChannelInputProc \
+ (tclStubsPtr->tcl_ChannelInputProc) /* 403 */
+#define Tcl_ChannelOutputProc \
+ (tclStubsPtr->tcl_ChannelOutputProc) /* 404 */
+#define Tcl_ChannelSeekProc \
+ (tclStubsPtr->tcl_ChannelSeekProc) /* 405 */
+#define Tcl_ChannelSetOptionProc \
+ (tclStubsPtr->tcl_ChannelSetOptionProc) /* 406 */
+#define Tcl_ChannelGetOptionProc \
+ (tclStubsPtr->tcl_ChannelGetOptionProc) /* 407 */
+#define Tcl_ChannelWatchProc \
+ (tclStubsPtr->tcl_ChannelWatchProc) /* 408 */
+#define Tcl_ChannelGetHandleProc \
+ (tclStubsPtr->tcl_ChannelGetHandleProc) /* 409 */
+#define Tcl_ChannelFlushProc \
+ (tclStubsPtr->tcl_ChannelFlushProc) /* 410 */
+#define Tcl_ChannelHandlerProc \
+ (tclStubsPtr->tcl_ChannelHandlerProc) /* 411 */
+#define Tcl_JoinThread \
+ (tclStubsPtr->tcl_JoinThread) /* 412 */
+#define Tcl_IsChannelShared \
+ (tclStubsPtr->tcl_IsChannelShared) /* 413 */
+#define Tcl_IsChannelRegistered \
+ (tclStubsPtr->tcl_IsChannelRegistered) /* 414 */
+#define Tcl_CutChannel \
+ (tclStubsPtr->tcl_CutChannel) /* 415 */
+#define Tcl_SpliceChannel \
+ (tclStubsPtr->tcl_SpliceChannel) /* 416 */
+#define Tcl_ClearChannelHandlers \
+ (tclStubsPtr->tcl_ClearChannelHandlers) /* 417 */
+#define Tcl_IsChannelExisting \
+ (tclStubsPtr->tcl_IsChannelExisting) /* 418 */
+#define Tcl_UniCharNcasecmp \
+ (tclStubsPtr->tcl_UniCharNcasecmp) /* 419 */
+#define Tcl_UniCharCaseMatch \
+ (tclStubsPtr->tcl_UniCharCaseMatch) /* 420 */
+#define Tcl_FindHashEntry \
+ (tclStubsPtr->tcl_FindHashEntry) /* 421 */
+#define Tcl_CreateHashEntry \
+ (tclStubsPtr->tcl_CreateHashEntry) /* 422 */
+#define Tcl_InitCustomHashTable \
+ (tclStubsPtr->tcl_InitCustomHashTable) /* 423 */
+#define Tcl_InitObjHashTable \
+ (tclStubsPtr->tcl_InitObjHashTable) /* 424 */
+#define Tcl_CommandTraceInfo \
+ (tclStubsPtr->tcl_CommandTraceInfo) /* 425 */
+#define Tcl_TraceCommand \
+ (tclStubsPtr->tcl_TraceCommand) /* 426 */
+#define Tcl_UntraceCommand \
+ (tclStubsPtr->tcl_UntraceCommand) /* 427 */
+#define Tcl_AttemptAlloc \
+ (tclStubsPtr->tcl_AttemptAlloc) /* 428 */
+#define Tcl_AttemptDbCkalloc \
+ (tclStubsPtr->tcl_AttemptDbCkalloc) /* 429 */
+#define Tcl_AttemptRealloc \
+ (tclStubsPtr->tcl_AttemptRealloc) /* 430 */
+#define Tcl_AttemptDbCkrealloc \
+ (tclStubsPtr->tcl_AttemptDbCkrealloc) /* 431 */
+#define Tcl_AttemptSetObjLength \
+ (tclStubsPtr->tcl_AttemptSetObjLength) /* 432 */
+#define Tcl_GetChannelThread \
+ (tclStubsPtr->tcl_GetChannelThread) /* 433 */
+#define Tcl_GetUnicodeFromObj \
+ (tclStubsPtr->tcl_GetUnicodeFromObj) /* 434 */
+#define Tcl_GetMathFuncInfo \
+ (tclStubsPtr->tcl_GetMathFuncInfo) /* 435 */
+#define Tcl_ListMathFuncs \
+ (tclStubsPtr->tcl_ListMathFuncs) /* 436 */
+#define Tcl_SubstObj \
+ (tclStubsPtr->tcl_SubstObj) /* 437 */
+#define Tcl_DetachChannel \
+ (tclStubsPtr->tcl_DetachChannel) /* 438 */
+#define Tcl_IsStandardChannel \
+ (tclStubsPtr->tcl_IsStandardChannel) /* 439 */
+#define Tcl_FSCopyFile \
+ (tclStubsPtr->tcl_FSCopyFile) /* 440 */
+#define Tcl_FSCopyDirectory \
+ (tclStubsPtr->tcl_FSCopyDirectory) /* 441 */
+#define Tcl_FSCreateDirectory \
+ (tclStubsPtr->tcl_FSCreateDirectory) /* 442 */
+#define Tcl_FSDeleteFile \
+ (tclStubsPtr->tcl_FSDeleteFile) /* 443 */
+#define Tcl_FSLoadFile \
+ (tclStubsPtr->tcl_FSLoadFile) /* 444 */
+#define Tcl_FSMatchInDirectory \
+ (tclStubsPtr->tcl_FSMatchInDirectory) /* 445 */
+#define Tcl_FSLink \
+ (tclStubsPtr->tcl_FSLink) /* 446 */
+#define Tcl_FSRemoveDirectory \
+ (tclStubsPtr->tcl_FSRemoveDirectory) /* 447 */
+#define Tcl_FSRenameFile \
+ (tclStubsPtr->tcl_FSRenameFile) /* 448 */
+#define Tcl_FSLstat \
+ (tclStubsPtr->tcl_FSLstat) /* 449 */
+#define Tcl_FSUtime \
+ (tclStubsPtr->tcl_FSUtime) /* 450 */
+#define Tcl_FSFileAttrsGet \
+ (tclStubsPtr->tcl_FSFileAttrsGet) /* 451 */
+#define Tcl_FSFileAttrsSet \
+ (tclStubsPtr->tcl_FSFileAttrsSet) /* 452 */
+#define Tcl_FSFileAttrStrings \
+ (tclStubsPtr->tcl_FSFileAttrStrings) /* 453 */
+#define Tcl_FSStat \
+ (tclStubsPtr->tcl_FSStat) /* 454 */
+#define Tcl_FSAccess \
+ (tclStubsPtr->tcl_FSAccess) /* 455 */
+#define Tcl_FSOpenFileChannel \
+ (tclStubsPtr->tcl_FSOpenFileChannel) /* 456 */
+#define Tcl_FSGetCwd \
+ (tclStubsPtr->tcl_FSGetCwd) /* 457 */
+#define Tcl_FSChdir \
+ (tclStubsPtr->tcl_FSChdir) /* 458 */
+#define Tcl_FSConvertToPathType \
+ (tclStubsPtr->tcl_FSConvertToPathType) /* 459 */
+#define Tcl_FSJoinPath \
+ (tclStubsPtr->tcl_FSJoinPath) /* 460 */
+#define Tcl_FSSplitPath \
+ (tclStubsPtr->tcl_FSSplitPath) /* 461 */
+#define Tcl_FSEqualPaths \
+ (tclStubsPtr->tcl_FSEqualPaths) /* 462 */
+#define Tcl_FSGetNormalizedPath \
+ (tclStubsPtr->tcl_FSGetNormalizedPath) /* 463 */
+#define Tcl_FSJoinToPath \
+ (tclStubsPtr->tcl_FSJoinToPath) /* 464 */
+#define Tcl_FSGetInternalRep \
+ (tclStubsPtr->tcl_FSGetInternalRep) /* 465 */
+#define Tcl_FSGetTranslatedPath \
+ (tclStubsPtr->tcl_FSGetTranslatedPath) /* 466 */
+#define Tcl_FSEvalFile \
+ (tclStubsPtr->tcl_FSEvalFile) /* 467 */
+#define Tcl_FSNewNativePath \
+ (tclStubsPtr->tcl_FSNewNativePath) /* 468 */
+#define Tcl_FSGetNativePath \
+ (tclStubsPtr->tcl_FSGetNativePath) /* 469 */
+#define Tcl_FSFileSystemInfo \
+ (tclStubsPtr->tcl_FSFileSystemInfo) /* 470 */
+#define Tcl_FSPathSeparator \
+ (tclStubsPtr->tcl_FSPathSeparator) /* 471 */
+#define Tcl_FSListVolumes \
+ (tclStubsPtr->tcl_FSListVolumes) /* 472 */
+#define Tcl_FSRegister \
+ (tclStubsPtr->tcl_FSRegister) /* 473 */
+#define Tcl_FSUnregister \
+ (tclStubsPtr->tcl_FSUnregister) /* 474 */
+#define Tcl_FSData \
+ (tclStubsPtr->tcl_FSData) /* 475 */
+#define Tcl_FSGetTranslatedStringPath \
+ (tclStubsPtr->tcl_FSGetTranslatedStringPath) /* 476 */
+#define Tcl_FSGetFileSystemForPath \
+ (tclStubsPtr->tcl_FSGetFileSystemForPath) /* 477 */
+#define Tcl_FSGetPathType \
+ (tclStubsPtr->tcl_FSGetPathType) /* 478 */
+#define Tcl_OutputBuffered \
+ (tclStubsPtr->tcl_OutputBuffered) /* 479 */
+#define Tcl_FSMountsChanged \
+ (tclStubsPtr->tcl_FSMountsChanged) /* 480 */
+#define Tcl_EvalTokensStandard \
+ (tclStubsPtr->tcl_EvalTokensStandard) /* 481 */
+#define Tcl_GetTime \
+ (tclStubsPtr->tcl_GetTime) /* 482 */
+#define Tcl_CreateObjTrace \
+ (tclStubsPtr->tcl_CreateObjTrace) /* 483 */
+#define Tcl_GetCommandInfoFromToken \
+ (tclStubsPtr->tcl_GetCommandInfoFromToken) /* 484 */
+#define Tcl_SetCommandInfoFromToken \
+ (tclStubsPtr->tcl_SetCommandInfoFromToken) /* 485 */
+#define Tcl_DbNewWideIntObj \
+ (tclStubsPtr->tcl_DbNewWideIntObj) /* 486 */
+#define Tcl_GetWideIntFromObj \
+ (tclStubsPtr->tcl_GetWideIntFromObj) /* 487 */
+#define Tcl_NewWideIntObj \
+ (tclStubsPtr->tcl_NewWideIntObj) /* 488 */
+#define Tcl_SetWideIntObj \
+ (tclStubsPtr->tcl_SetWideIntObj) /* 489 */
+#define Tcl_AllocStatBuf \
+ (tclStubsPtr->tcl_AllocStatBuf) /* 490 */
+#define Tcl_Seek \
+ (tclStubsPtr->tcl_Seek) /* 491 */
+#define Tcl_Tell \
+ (tclStubsPtr->tcl_Tell) /* 492 */
+#define Tcl_ChannelWideSeekProc \
+ (tclStubsPtr->tcl_ChannelWideSeekProc) /* 493 */
+#define Tcl_DictObjPut \
+ (tclStubsPtr->tcl_DictObjPut) /* 494 */
+#define Tcl_DictObjGet \
+ (tclStubsPtr->tcl_DictObjGet) /* 495 */
+#define Tcl_DictObjRemove \
+ (tclStubsPtr->tcl_DictObjRemove) /* 496 */
+#define Tcl_DictObjSize \
+ (tclStubsPtr->tcl_DictObjSize) /* 497 */
+#define Tcl_DictObjFirst \
+ (tclStubsPtr->tcl_DictObjFirst) /* 498 */
+#define Tcl_DictObjNext \
+ (tclStubsPtr->tcl_DictObjNext) /* 499 */
+#define Tcl_DictObjDone \
+ (tclStubsPtr->tcl_DictObjDone) /* 500 */
+#define Tcl_DictObjPutKeyList \
+ (tclStubsPtr->tcl_DictObjPutKeyList) /* 501 */
+#define Tcl_DictObjRemoveKeyList \
+ (tclStubsPtr->tcl_DictObjRemoveKeyList) /* 502 */
+#define Tcl_NewDictObj \
+ (tclStubsPtr->tcl_NewDictObj) /* 503 */
+#define Tcl_DbNewDictObj \
+ (tclStubsPtr->tcl_DbNewDictObj) /* 504 */
+#define Tcl_RegisterConfig \
+ (tclStubsPtr->tcl_RegisterConfig) /* 505 */
+#define Tcl_CreateNamespace \
+ (tclStubsPtr->tcl_CreateNamespace) /* 506 */
+#define Tcl_DeleteNamespace \
+ (tclStubsPtr->tcl_DeleteNamespace) /* 507 */
+#define Tcl_AppendExportList \
+ (tclStubsPtr->tcl_AppendExportList) /* 508 */
+#define Tcl_Export \
+ (tclStubsPtr->tcl_Export) /* 509 */
+#define Tcl_Import \
+ (tclStubsPtr->tcl_Import) /* 510 */
+#define Tcl_ForgetImport \
+ (tclStubsPtr->tcl_ForgetImport) /* 511 */
+#define Tcl_GetCurrentNamespace \
+ (tclStubsPtr->tcl_GetCurrentNamespace) /* 512 */
+#define Tcl_GetGlobalNamespace \
+ (tclStubsPtr->tcl_GetGlobalNamespace) /* 513 */
+#define Tcl_FindNamespace \
+ (tclStubsPtr->tcl_FindNamespace) /* 514 */
+#define Tcl_FindCommand \
+ (tclStubsPtr->tcl_FindCommand) /* 515 */
+#define Tcl_GetCommandFromObj \
+ (tclStubsPtr->tcl_GetCommandFromObj) /* 516 */
+#define Tcl_GetCommandFullName \
+ (tclStubsPtr->tcl_GetCommandFullName) /* 517 */
+#define Tcl_FSEvalFileEx \
+ (tclStubsPtr->tcl_FSEvalFileEx) /* 518 */
+#define Tcl_SetExitProc \
+ (tclStubsPtr->tcl_SetExitProc) /* 519 */
+#define Tcl_LimitAddHandler \
+ (tclStubsPtr->tcl_LimitAddHandler) /* 520 */
+#define Tcl_LimitRemoveHandler \
+ (tclStubsPtr->tcl_LimitRemoveHandler) /* 521 */
+#define Tcl_LimitReady \
+ (tclStubsPtr->tcl_LimitReady) /* 522 */
+#define Tcl_LimitCheck \
+ (tclStubsPtr->tcl_LimitCheck) /* 523 */
+#define Tcl_LimitExceeded \
+ (tclStubsPtr->tcl_LimitExceeded) /* 524 */
+#define Tcl_LimitSetCommands \
+ (tclStubsPtr->tcl_LimitSetCommands) /* 525 */
+#define Tcl_LimitSetTime \
+ (tclStubsPtr->tcl_LimitSetTime) /* 526 */
+#define Tcl_LimitSetGranularity \
+ (tclStubsPtr->tcl_LimitSetGranularity) /* 527 */
+#define Tcl_LimitTypeEnabled \
+ (tclStubsPtr->tcl_LimitTypeEnabled) /* 528 */
+#define Tcl_LimitTypeExceeded \
+ (tclStubsPtr->tcl_LimitTypeExceeded) /* 529 */
+#define Tcl_LimitTypeSet \
+ (tclStubsPtr->tcl_LimitTypeSet) /* 530 */
+#define Tcl_LimitTypeReset \
+ (tclStubsPtr->tcl_LimitTypeReset) /* 531 */
+#define Tcl_LimitGetCommands \
+ (tclStubsPtr->tcl_LimitGetCommands) /* 532 */
+#define Tcl_LimitGetTime \
+ (tclStubsPtr->tcl_LimitGetTime) /* 533 */
+#define Tcl_LimitGetGranularity \
+ (tclStubsPtr->tcl_LimitGetGranularity) /* 534 */
+#define Tcl_SaveInterpState \
+ (tclStubsPtr->tcl_SaveInterpState) /* 535 */
+#define Tcl_RestoreInterpState \
+ (tclStubsPtr->tcl_RestoreInterpState) /* 536 */
+#define Tcl_DiscardInterpState \
+ (tclStubsPtr->tcl_DiscardInterpState) /* 537 */
+#define Tcl_SetReturnOptions \
+ (tclStubsPtr->tcl_SetReturnOptions) /* 538 */
+#define Tcl_GetReturnOptions \
+ (tclStubsPtr->tcl_GetReturnOptions) /* 539 */
+#define Tcl_IsEnsemble \
+ (tclStubsPtr->tcl_IsEnsemble) /* 540 */
+#define Tcl_CreateEnsemble \
+ (tclStubsPtr->tcl_CreateEnsemble) /* 541 */
+#define Tcl_FindEnsemble \
+ (tclStubsPtr->tcl_FindEnsemble) /* 542 */
+#define Tcl_SetEnsembleSubcommandList \
+ (tclStubsPtr->tcl_SetEnsembleSubcommandList) /* 543 */
+#define Tcl_SetEnsembleMappingDict \
+ (tclStubsPtr->tcl_SetEnsembleMappingDict) /* 544 */
+#define Tcl_SetEnsembleUnknownHandler \
+ (tclStubsPtr->tcl_SetEnsembleUnknownHandler) /* 545 */
+#define Tcl_SetEnsembleFlags \
+ (tclStubsPtr->tcl_SetEnsembleFlags) /* 546 */
+#define Tcl_GetEnsembleSubcommandList \
+ (tclStubsPtr->tcl_GetEnsembleSubcommandList) /* 547 */
+#define Tcl_GetEnsembleMappingDict \
+ (tclStubsPtr->tcl_GetEnsembleMappingDict) /* 548 */
+#define Tcl_GetEnsembleUnknownHandler \
+ (tclStubsPtr->tcl_GetEnsembleUnknownHandler) /* 549 */
+#define Tcl_GetEnsembleFlags \
+ (tclStubsPtr->tcl_GetEnsembleFlags) /* 550 */
+#define Tcl_GetEnsembleNamespace \
+ (tclStubsPtr->tcl_GetEnsembleNamespace) /* 551 */
+#define Tcl_SetTimeProc \
+ (tclStubsPtr->tcl_SetTimeProc) /* 552 */
+#define Tcl_QueryTimeProc \
+ (tclStubsPtr->tcl_QueryTimeProc) /* 553 */
+#define Tcl_ChannelThreadActionProc \
+ (tclStubsPtr->tcl_ChannelThreadActionProc) /* 554 */
+#define Tcl_NewBignumObj \
+ (tclStubsPtr->tcl_NewBignumObj) /* 555 */
+#define Tcl_DbNewBignumObj \
+ (tclStubsPtr->tcl_DbNewBignumObj) /* 556 */
+#define Tcl_SetBignumObj \
+ (tclStubsPtr->tcl_SetBignumObj) /* 557 */
+#define Tcl_GetBignumFromObj \
+ (tclStubsPtr->tcl_GetBignumFromObj) /* 558 */
+#define Tcl_TakeBignumFromObj \
+ (tclStubsPtr->tcl_TakeBignumFromObj) /* 559 */
+#define Tcl_TruncateChannel \
+ (tclStubsPtr->tcl_TruncateChannel) /* 560 */
+#define Tcl_ChannelTruncateProc \
+ (tclStubsPtr->tcl_ChannelTruncateProc) /* 561 */
+#define Tcl_SetChannelErrorInterp \
+ (tclStubsPtr->tcl_SetChannelErrorInterp) /* 562 */
+#define Tcl_GetChannelErrorInterp \
+ (tclStubsPtr->tcl_GetChannelErrorInterp) /* 563 */
+#define Tcl_SetChannelError \
+ (tclStubsPtr->tcl_SetChannelError) /* 564 */
+#define Tcl_GetChannelError \
+ (tclStubsPtr->tcl_GetChannelError) /* 565 */
+#define Tcl_InitBignumFromDouble \
+ (tclStubsPtr->tcl_InitBignumFromDouble) /* 566 */
+#define Tcl_GetNamespaceUnknownHandler \
+ (tclStubsPtr->tcl_GetNamespaceUnknownHandler) /* 567 */
+#define Tcl_SetNamespaceUnknownHandler \
+ (tclStubsPtr->tcl_SetNamespaceUnknownHandler) /* 568 */
+#define Tcl_GetEncodingFromObj \
+ (tclStubsPtr->tcl_GetEncodingFromObj) /* 569 */
+#define Tcl_GetEncodingSearchPath \
+ (tclStubsPtr->tcl_GetEncodingSearchPath) /* 570 */
+#define Tcl_SetEncodingSearchPath \
+ (tclStubsPtr->tcl_SetEncodingSearchPath) /* 571 */
+#define Tcl_GetEncodingNameFromEnvironment \
+ (tclStubsPtr->tcl_GetEncodingNameFromEnvironment) /* 572 */
+#define Tcl_PkgRequireProc \
+ (tclStubsPtr->tcl_PkgRequireProc) /* 573 */
+#define Tcl_AppendObjToErrorInfo \
+ (tclStubsPtr->tcl_AppendObjToErrorInfo) /* 574 */
+#define Tcl_AppendLimitedToObj \
+ (tclStubsPtr->tcl_AppendLimitedToObj) /* 575 */
+#define Tcl_Format \
+ (tclStubsPtr->tcl_Format) /* 576 */
+#define Tcl_AppendFormatToObj \
+ (tclStubsPtr->tcl_AppendFormatToObj) /* 577 */
+#define Tcl_ObjPrintf \
+ (tclStubsPtr->tcl_ObjPrintf) /* 578 */
+#define Tcl_AppendPrintfToObj \
+ (tclStubsPtr->tcl_AppendPrintfToObj) /* 579 */
+#define Tcl_CancelEval \
+ (tclStubsPtr->tcl_CancelEval) /* 580 */
+#define Tcl_Canceled \
+ (tclStubsPtr->tcl_Canceled) /* 581 */
+#define Tcl_CreatePipe \
+ (tclStubsPtr->tcl_CreatePipe) /* 582 */
+#define Tcl_NRCreateCommand \
+ (tclStubsPtr->tcl_NRCreateCommand) /* 583 */
+#define Tcl_NREvalObj \
+ (tclStubsPtr->tcl_NREvalObj) /* 584 */
+#define Tcl_NREvalObjv \
+ (tclStubsPtr->tcl_NREvalObjv) /* 585 */
+#define Tcl_NRCmdSwap \
+ (tclStubsPtr->tcl_NRCmdSwap) /* 586 */
+#define Tcl_NRAddCallback \
+ (tclStubsPtr->tcl_NRAddCallback) /* 587 */
+#define Tcl_NRCallObjProc \
+ (tclStubsPtr->tcl_NRCallObjProc) /* 588 */
+#define Tcl_GetFSDeviceFromStat \
+ (tclStubsPtr->tcl_GetFSDeviceFromStat) /* 589 */
+#define Tcl_GetFSInodeFromStat \
+ (tclStubsPtr->tcl_GetFSInodeFromStat) /* 590 */
+#define Tcl_GetModeFromStat \
+ (tclStubsPtr->tcl_GetModeFromStat) /* 591 */
+#define Tcl_GetLinkCountFromStat \
+ (tclStubsPtr->tcl_GetLinkCountFromStat) /* 592 */
+#define Tcl_GetUserIdFromStat \
+ (tclStubsPtr->tcl_GetUserIdFromStat) /* 593 */
+#define Tcl_GetGroupIdFromStat \
+ (tclStubsPtr->tcl_GetGroupIdFromStat) /* 594 */
+#define Tcl_GetDeviceTypeFromStat \
+ (tclStubsPtr->tcl_GetDeviceTypeFromStat) /* 595 */
+#define Tcl_GetAccessTimeFromStat \
+ (tclStubsPtr->tcl_GetAccessTimeFromStat) /* 596 */
+#define Tcl_GetModificationTimeFromStat \
+ (tclStubsPtr->tcl_GetModificationTimeFromStat) /* 597 */
+#define Tcl_GetChangeTimeFromStat \
+ (tclStubsPtr->tcl_GetChangeTimeFromStat) /* 598 */
+#define Tcl_GetSizeFromStat \
+ (tclStubsPtr->tcl_GetSizeFromStat) /* 599 */
+#define Tcl_GetBlocksFromStat \
+ (tclStubsPtr->tcl_GetBlocksFromStat) /* 600 */
+#define Tcl_GetBlockSizeFromStat \
+ (tclStubsPtr->tcl_GetBlockSizeFromStat) /* 601 */
+#define Tcl_SetEnsembleParameterList \
+ (tclStubsPtr->tcl_SetEnsembleParameterList) /* 602 */
+#define Tcl_GetEnsembleParameterList \
+ (tclStubsPtr->tcl_GetEnsembleParameterList) /* 603 */
+#define Tcl_ParseArgsObjv \
+ (tclStubsPtr->tcl_ParseArgsObjv) /* 604 */
+#define Tcl_GetErrorLine \
+ (tclStubsPtr->tcl_GetErrorLine) /* 605 */
+#define Tcl_SetErrorLine \
+ (tclStubsPtr->tcl_SetErrorLine) /* 606 */
+#define Tcl_TransferResult \
+ (tclStubsPtr->tcl_TransferResult) /* 607 */
+#define Tcl_InterpActive \
+ (tclStubsPtr->tcl_InterpActive) /* 608 */
+#define Tcl_BackgroundException \
+ (tclStubsPtr->tcl_BackgroundException) /* 609 */
+#define Tcl_ZlibDeflate \
+ (tclStubsPtr->tcl_ZlibDeflate) /* 610 */
+#define Tcl_ZlibInflate \
+ (tclStubsPtr->tcl_ZlibInflate) /* 611 */
+#define Tcl_ZlibCRC32 \
+ (tclStubsPtr->tcl_ZlibCRC32) /* 612 */
+#define Tcl_ZlibAdler32 \
+ (tclStubsPtr->tcl_ZlibAdler32) /* 613 */
+#define Tcl_ZlibStreamInit \
+ (tclStubsPtr->tcl_ZlibStreamInit) /* 614 */
+#define Tcl_ZlibStreamGetCommandName \
+ (tclStubsPtr->tcl_ZlibStreamGetCommandName) /* 615 */
+#define Tcl_ZlibStreamEof \
+ (tclStubsPtr->tcl_ZlibStreamEof) /* 616 */
+#define Tcl_ZlibStreamChecksum \
+ (tclStubsPtr->tcl_ZlibStreamChecksum) /* 617 */
+#define Tcl_ZlibStreamPut \
+ (tclStubsPtr->tcl_ZlibStreamPut) /* 618 */
+#define Tcl_ZlibStreamGet \
+ (tclStubsPtr->tcl_ZlibStreamGet) /* 619 */
+#define Tcl_ZlibStreamClose \
+ (tclStubsPtr->tcl_ZlibStreamClose) /* 620 */
+#define Tcl_ZlibStreamReset \
+ (tclStubsPtr->tcl_ZlibStreamReset) /* 621 */
+#define Tcl_SetStartupScript \
+ (tclStubsPtr->tcl_SetStartupScript) /* 622 */
+#define Tcl_GetStartupScript \
+ (tclStubsPtr->tcl_GetStartupScript) /* 623 */
+#define Tcl_CloseEx \
+ (tclStubsPtr->tcl_CloseEx) /* 624 */
+#define Tcl_NRExprObj \
+ (tclStubsPtr->tcl_NRExprObj) /* 625 */
+#define Tcl_NRSubstObj \
+ (tclStubsPtr->tcl_NRSubstObj) /* 626 */
+#define Tcl_LoadFile \
+ (tclStubsPtr->tcl_LoadFile) /* 627 */
+#define Tcl_FindSymbol \
+ (tclStubsPtr->tcl_FindSymbol) /* 628 */
+#define Tcl_FSUnloadFile \
+ (tclStubsPtr->tcl_FSUnloadFile) /* 629 */
+#define Tcl_ZlibStreamSetCompressionDictionary \
+ (tclStubsPtr->tcl_ZlibStreamSetCompressionDictionary) /* 630 */
+
+#endif /* defined(USE_TCL_STUBS) */
+
+/* !END!: Do not edit above this line. */
+
+#if defined(USE_TCL_STUBS)
+# undef Tcl_CreateInterp
+# undef Tcl_FindExecutable
+# undef Tcl_GetStringResult
+# undef Tcl_Init
+# undef Tcl_SetPanicProc
+# undef Tcl_SetVar
+# undef Tcl_StaticPackage
+# undef TclFSGetNativePath
+# define Tcl_CreateInterp() (tclStubsPtr->tcl_CreateInterp())
+# define Tcl_GetStringResult(interp) (tclStubsPtr->tcl_GetStringResult(interp))
+# define Tcl_Init(interp) (tclStubsPtr->tcl_Init(interp))
+# define Tcl_SetPanicProc(proc) (tclStubsPtr->tcl_SetPanicProc(proc))
+# define Tcl_SetVar(interp, varName, newValue, flags) \
+ (tclStubsPtr->tcl_SetVar(interp, varName, newValue, flags))
+#endif
+
+#if defined(_WIN32) && defined(UNICODE)
+# define Tcl_FindExecutable(arg) ((Tcl_FindExecutable)((const char *)(arg)))
+# define Tcl_MainEx Tcl_MainExW
+ EXTERN void Tcl_MainExW(int argc, wchar_t **argv,
+ Tcl_AppInitProc *appInitProc, Tcl_Interp *interp);
+#endif
+
+#undef TCL_STORAGE_CLASS
+#define TCL_STORAGE_CLASS DLLIMPORT
+
+#endif /* _TCLDECLS */
ADDED compat/tcl-8.6/generic/tclPlatDecls.h
Index: compat/tcl-8.6/generic/tclPlatDecls.h
==================================================================
--- compat/tcl-8.6/generic/tclPlatDecls.h
+++ compat/tcl-8.6/generic/tclPlatDecls.h
@@ -0,0 +1,120 @@
+/*
+ * tclPlatDecls.h --
+ *
+ * Declarations of platform specific Tcl APIs.
+ *
+ * Copyright (c) 1998-1999 by Scriptics Corporation.
+ * All rights reserved.
+ */
+
+#ifndef _TCLPLATDECLS
+#define _TCLPLATDECLS
+
+#undef TCL_STORAGE_CLASS
+#ifdef BUILD_tcl
+# define TCL_STORAGE_CLASS DLLEXPORT
+#else
+# ifdef USE_TCL_STUBS
+# define TCL_STORAGE_CLASS
+# else
+# define TCL_STORAGE_CLASS DLLIMPORT
+# endif
+#endif
+
+/*
+ * WARNING: This file is automatically generated by the tools/genStubs.tcl
+ * script. Any modifications to the function declarations below should be made
+ * in the generic/tcl.decls script.
+ */
+
+/*
+ * TCHAR is needed here for win32, so if it is not defined yet do it here.
+ * This way, we don't need to include just for one define.
+ */
+#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(_TCHAR_DEFINED)
+# if defined(_UNICODE)
+ typedef wchar_t TCHAR;
+# else
+ typedef char TCHAR;
+# endif
+# define _TCHAR_DEFINED
+#endif
+
+/* !BEGIN!: Do not edit below this line. */
+
+/*
+ * Exported function declarations:
+ */
+
+#if defined(__WIN32__) || defined(__CYGWIN__) /* WIN */
+/* 0 */
+EXTERN TCHAR * Tcl_WinUtfToTChar(const char *str, int len,
+ Tcl_DString *dsPtr);
+/* 1 */
+EXTERN char * Tcl_WinTCharToUtf(const TCHAR *str, int len,
+ Tcl_DString *dsPtr);
+#endif /* WIN */
+#ifdef MAC_OSX_TCL /* MACOSX */
+/* 0 */
+EXTERN int Tcl_MacOSXOpenBundleResources(Tcl_Interp *interp,
+ const char *bundleName, int hasResourceFile,
+ int maxPathLen, char *libraryPath);
+/* 1 */
+EXTERN int Tcl_MacOSXOpenVersionedBundleResources(
+ Tcl_Interp *interp, const char *bundleName,
+ const char *bundleVersion,
+ int hasResourceFile, int maxPathLen,
+ char *libraryPath);
+#endif /* MACOSX */
+
+typedef struct TclPlatStubs {
+ int magic;
+ void *hooks;
+
+#if defined(__WIN32__) || defined(__CYGWIN__) /* WIN */
+ TCHAR * (*tcl_WinUtfToTChar) (const char *str, int len, Tcl_DString *dsPtr); /* 0 */
+ char * (*tcl_WinTCharToUtf) (const TCHAR *str, int len, Tcl_DString *dsPtr); /* 1 */
+#endif /* WIN */
+#ifdef MAC_OSX_TCL /* MACOSX */
+ int (*tcl_MacOSXOpenBundleResources) (Tcl_Interp *interp, const char *bundleName, int hasResourceFile, int maxPathLen, char *libraryPath); /* 0 */
+ int (*tcl_MacOSXOpenVersionedBundleResources) (Tcl_Interp *interp, const char *bundleName, const char *bundleVersion, int hasResourceFile, int maxPathLen, char *libraryPath); /* 1 */
+#endif /* MACOSX */
+} TclPlatStubs;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern const TclPlatStubs *tclPlatStubsPtr;
+#ifdef __cplusplus
+}
+#endif
+
+#if defined(USE_TCL_STUBS)
+
+/*
+ * Inline function declarations:
+ */
+
+#if defined(__WIN32__) || defined(__CYGWIN__) /* WIN */
+#define Tcl_WinUtfToTChar \
+ (tclPlatStubsPtr->tcl_WinUtfToTChar) /* 0 */
+#define Tcl_WinTCharToUtf \
+ (tclPlatStubsPtr->tcl_WinTCharToUtf) /* 1 */
+#endif /* WIN */
+#ifdef MAC_OSX_TCL /* MACOSX */
+#define Tcl_MacOSXOpenBundleResources \
+ (tclPlatStubsPtr->tcl_MacOSXOpenBundleResources) /* 0 */
+#define Tcl_MacOSXOpenVersionedBundleResources \
+ (tclPlatStubsPtr->tcl_MacOSXOpenVersionedBundleResources) /* 1 */
+#endif /* MACOSX */
+
+#endif /* defined(USE_TCL_STUBS) */
+
+/* !END!: Do not edit above this line. */
+
+#undef TCL_STORAGE_CLASS
+#define TCL_STORAGE_CLASS DLLIMPORT
+
+#endif /* _TCLPLATDECLS */
+
+
ADDED compat/zlib/CMakeLists.txt
Index: compat/zlib/CMakeLists.txt
==================================================================
--- compat/zlib/CMakeLists.txt
+++ compat/zlib/CMakeLists.txt
@@ -0,0 +1,213 @@
+cmake_minimum_required(VERSION 2.4.4)
+set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON)
+
+project(zlib C)
+
+set(VERSION "1.2.13")
+
+set(INSTALL_BIN_DIR "${CMAKE_INSTALL_PREFIX}/bin" CACHE PATH "Installation directory for executables")
+set(INSTALL_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib" CACHE PATH "Installation directory for libraries")
+set(INSTALL_INC_DIR "${CMAKE_INSTALL_PREFIX}/include" CACHE PATH "Installation directory for headers")
+set(INSTALL_MAN_DIR "${CMAKE_INSTALL_PREFIX}/share/man" CACHE PATH "Installation directory for manual pages")
+set(INSTALL_PKGCONFIG_DIR "${CMAKE_INSTALL_PREFIX}/share/pkgconfig" CACHE PATH "Installation directory for pkgconfig (.pc) files")
+
+include(CheckTypeSize)
+include(CheckFunctionExists)
+include(CheckIncludeFile)
+include(CheckCSourceCompiles)
+enable_testing()
+
+check_include_file(sys/types.h HAVE_SYS_TYPES_H)
+check_include_file(stdint.h HAVE_STDINT_H)
+check_include_file(stddef.h HAVE_STDDEF_H)
+
+#
+# Check to see if we have large file support
+#
+set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE=1)
+# We add these other definitions here because CheckTypeSize.cmake
+# in CMake 2.4.x does not automatically do so and we want
+# compatibility with CMake 2.4.x.
+if(HAVE_SYS_TYPES_H)
+ list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_SYS_TYPES_H)
+endif()
+if(HAVE_STDINT_H)
+ list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDINT_H)
+endif()
+if(HAVE_STDDEF_H)
+ list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDDEF_H)
+endif()
+check_type_size(off64_t OFF64_T)
+if(HAVE_OFF64_T)
+ add_definitions(-D_LARGEFILE64_SOURCE=1)
+endif()
+set(CMAKE_REQUIRED_DEFINITIONS) # clear variable
+
+#
+# Check for fseeko
+#
+check_function_exists(fseeko HAVE_FSEEKO)
+if(NOT HAVE_FSEEKO)
+ add_definitions(-DNO_FSEEKO)
+endif()
+
+#
+# Check for unistd.h
+#
+check_include_file(unistd.h Z_HAVE_UNISTD_H)
+
+if(MSVC)
+ set(CMAKE_DEBUG_POSTFIX "d")
+ add_definitions(-D_CRT_SECURE_NO_DEPRECATE)
+ add_definitions(-D_CRT_NONSTDC_NO_DEPRECATE)
+ include_directories(${CMAKE_CURRENT_SOURCE_DIR})
+endif()
+
+if(NOT CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)
+ # If we're doing an out of source build and the user has a zconf.h
+ # in their source tree...
+ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h)
+ message(STATUS "Renaming")
+ message(STATUS " ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h")
+ message(STATUS "to 'zconf.h.included' because this file is included with zlib")
+ message(STATUS "but CMake generates it automatically in the build directory.")
+ file(RENAME ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.included)
+ endif()
+endif()
+
+set(ZLIB_PC ${CMAKE_CURRENT_BINARY_DIR}/zlib.pc)
+configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zlib.pc.cmakein
+ ${ZLIB_PC} @ONLY)
+configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/zconf.h.cmakein
+ ${CMAKE_CURRENT_BINARY_DIR}/zconf.h @ONLY)
+include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR})
+
+
+#============================================================================
+# zlib
+#============================================================================
+
+set(ZLIB_PUBLIC_HDRS
+ ${CMAKE_CURRENT_BINARY_DIR}/zconf.h
+ zlib.h
+)
+set(ZLIB_PRIVATE_HDRS
+ crc32.h
+ deflate.h
+ gzguts.h
+ inffast.h
+ inffixed.h
+ inflate.h
+ inftrees.h
+ trees.h
+ zutil.h
+)
+set(ZLIB_SRCS
+ adler32.c
+ compress.c
+ crc32.c
+ deflate.c
+ gzclose.c
+ gzlib.c
+ gzread.c
+ gzwrite.c
+ inflate.c
+ infback.c
+ inftrees.c
+ inffast.c
+ trees.c
+ uncompr.c
+ zutil.c
+)
+
+if(NOT MINGW)
+ set(ZLIB_DLL_SRCS
+ win32/zlib1.rc # If present will override custom build rule below.
+ )
+endif()
+
+# parse the full version number from zlib.h and include in ZLIB_FULL_VERSION
+file(READ ${CMAKE_CURRENT_SOURCE_DIR}/zlib.h _zlib_h_contents)
+string(REGEX REPLACE ".*#define[ \t]+ZLIB_VERSION[ \t]+\"([-0-9A-Za-z.]+)\".*"
+ "\\1" ZLIB_FULL_VERSION ${_zlib_h_contents})
+
+if(MINGW)
+ # This gets us DLL resource information when compiling on MinGW.
+ if(NOT CMAKE_RC_COMPILER)
+ set(CMAKE_RC_COMPILER windres.exe)
+ endif()
+
+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj
+ COMMAND ${CMAKE_RC_COMPILER}
+ -D GCC_WINDRES
+ -I ${CMAKE_CURRENT_SOURCE_DIR}
+ -I ${CMAKE_CURRENT_BINARY_DIR}
+ -o ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj
+ -i ${CMAKE_CURRENT_SOURCE_DIR}/win32/zlib1.rc)
+ set(ZLIB_DLL_SRCS ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj)
+endif(MINGW)
+
+add_library(zlib SHARED ${ZLIB_SRCS} ${ZLIB_DLL_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS})
+add_library(zlibstatic STATIC ${ZLIB_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS})
+set_target_properties(zlib PROPERTIES DEFINE_SYMBOL ZLIB_DLL)
+set_target_properties(zlib PROPERTIES SOVERSION 1)
+
+if(NOT CYGWIN)
+ # This property causes shared libraries on Linux to have the full version
+ # encoded into their final filename. We disable this on Cygwin because
+ # it causes cygz-${ZLIB_FULL_VERSION}.dll to be created when cygz.dll
+ # seems to be the default.
+ #
+ # This has no effect with MSVC, on that platform the version info for
+ # the DLL comes from the resource file win32/zlib1.rc
+ set_target_properties(zlib PROPERTIES VERSION ${ZLIB_FULL_VERSION})
+endif()
+
+if(UNIX)
+ # On unix-like platforms the library is almost always called libz
+ set_target_properties(zlib zlibstatic PROPERTIES OUTPUT_NAME z)
+ if(NOT APPLE)
+ set_target_properties(zlib PROPERTIES LINK_FLAGS "-Wl,--version-script,\"${CMAKE_CURRENT_SOURCE_DIR}/zlib.map\"")
+ endif()
+elseif(BUILD_SHARED_LIBS AND WIN32)
+ # Creates zlib1.dll when building shared library version
+ set_target_properties(zlib PROPERTIES SUFFIX "1.dll")
+endif()
+
+if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL )
+ install(TARGETS zlib zlibstatic
+ RUNTIME DESTINATION "${INSTALL_BIN_DIR}"
+ ARCHIVE DESTINATION "${INSTALL_LIB_DIR}"
+ LIBRARY DESTINATION "${INSTALL_LIB_DIR}" )
+endif()
+if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL )
+ install(FILES ${ZLIB_PUBLIC_HDRS} DESTINATION "${INSTALL_INC_DIR}")
+endif()
+if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL )
+ install(FILES zlib.3 DESTINATION "${INSTALL_MAN_DIR}/man3")
+endif()
+if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL )
+ install(FILES ${ZLIB_PC} DESTINATION "${INSTALL_PKGCONFIG_DIR}")
+endif()
+
+#============================================================================
+# Example binaries
+#============================================================================
+
+add_executable(example test/example.c)
+target_link_libraries(example zlib)
+add_test(example example)
+
+add_executable(minigzip test/minigzip.c)
+target_link_libraries(minigzip zlib)
+
+if(HAVE_OFF64_T)
+ add_executable(example64 test/example.c)
+ target_link_libraries(example64 zlib)
+ set_target_properties(example64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64")
+ add_test(example64 example64)
+
+ add_executable(minigzip64 test/minigzip.c)
+ target_link_libraries(minigzip64 zlib)
+ set_target_properties(minigzip64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64")
+endif()
ADDED compat/zlib/ChangeLog
Index: compat/zlib/ChangeLog
==================================================================
--- compat/zlib/ChangeLog
+++ compat/zlib/ChangeLog
@@ -0,0 +1,1590 @@
+
+ ChangeLog file for zlib
+
+Changes in 1.2.13 (13 Oct 2022)
+- Fix configure issue that discarded provided CC definition
+- Correct incorrect inputs provided to the CRC functions
+- Repair prototypes and exporting of new CRC functions
+- Fix inflateBack to detect invalid input with distances too far
+- Have infback() deliver all of the available output up to any error
+- Fix a bug when getting a gzip header extra field with inflate()
+- Fix bug in block type selection when Z_FIXED used
+- Tighten deflateBound bounds
+- Remove deleted assembler code references
+- Various portability and appearance improvements
+
+Changes in 1.2.12 (27 Mar 2022)
+- Cygwin does not have _wopen(), so do not create gzopen_w() there
+- Permit a deflateParams() parameter change as soon as possible
+- Limit hash table inserts after switch from stored deflate
+- Fix bug when window full in deflate_stored()
+- Fix CLEAR_HASH macro to be usable as a single statement
+- Avoid a conversion error in gzseek when off_t type too small
+- Have Makefile return non-zero error code on test failure
+- Avoid some conversion warnings in gzread.c and gzwrite.c
+- Update use of errno for newer Windows CE versions
+- Small speedup to inflate [psumbera]
+- Return an error if the gzputs string length can't fit in an int
+- Add address checking in clang to -w option of configure
+- Don't compute check value for raw inflate if asked to validate
+- Handle case where inflateSync used when header never processed
+- Avoid the use of ptrdiff_t
+- Avoid an undefined behavior of memcpy() in gzappend()
+- Avoid undefined behaviors of memcpy() in gz*printf()
+- Avoid an undefined behavior of memcpy() in _tr_stored_block()
+- Make the names in functions declarations identical to definitions
+- Remove old assembler code in which bugs have manifested
+- Fix deflateEnd() to not report an error at start of raw deflate
+- Add legal disclaimer to README
+- Emphasize the need to continue decompressing gzip members
+- Correct the initialization requirements for deflateInit2()
+- Fix a bug that can crash deflate on some input when using Z_FIXED
+- Assure that the number of bits for deflatePrime() is valid
+- Use a structure to make globals in enough.c evident
+- Use a macro for the printf format of big_t in enough.c
+- Clean up code style in enough.c, update version
+- Use inline function instead of macro for index in enough.c
+- Clarify that prefix codes are counted in enough.c
+- Show all the codes for the maximum tables size in enough.c
+- Add gznorm.c example, which normalizes gzip files
+- Fix the zran.c example to work on a multiple-member gzip file
+- Add tables for crc32_combine(), to speed it up by a factor of 200
+- Add crc32_combine_gen() and crc32_combine_op() for fast combines
+- Speed up software CRC-32 computation by a factor of 1.5 to 3
+- Use atomic test and set, if available, for dynamic CRC tables
+- Don't bother computing check value after successful inflateSync()
+- Correct comment in crc32.c
+- Add use of the ARMv8 crc32 instructions when requested
+- Use ARM crc32 instructions if the ARM architecture has them
+- Explicitly note that the 32-bit check values are 32 bits
+- Avoid adding empty gzip member after gzflush with Z_FINISH
+- Fix memory leak on error in gzlog.c
+- Fix error in comment on the polynomial representation of a byte
+- Clarify gz* function interfaces, referring to parameter names
+- Change macro name in inflate.c to avoid collision in VxWorks
+- Correct typo in blast.c
+- Improve portability of contrib/minizip
+- Fix indentation in minizip's zip.c
+- Replace black/white with allow/block. (theresa-m)
+- minizip warning fix if MAXU32 already defined. (gvollant)
+- Fix unztell64() in minizip to work past 4GB. (Daniël Hörchner)
+- Clean up minizip to reduce warnings for testing
+- Add fallthrough comments for gcc
+- Eliminate use of ULL constants
+- Separate out address sanitizing from warnings in configure
+- Remove destructive aspects of make distclean
+- Check for cc masquerading as gcc or clang in configure
+- Fix crc32.c to compile local functions only if used
+
+Changes in 1.2.11 (15 Jan 2017)
+- Fix deflate stored bug when pulling last block from window
+- Permit immediate deflateParams changes before any deflate input
+
+Changes in 1.2.10 (2 Jan 2017)
+- Avoid warnings on snprintf() return value
+- Fix bug in deflate_stored() for zero-length input
+- Fix bug in gzwrite.c that produced corrupt gzip files
+- Remove files to be installed before copying them in Makefile.in
+- Add warnings when compiling with assembler code
+
+Changes in 1.2.9 (31 Dec 2016)
+- Fix contrib/minizip to permit unzipping with desktop API [Zouzou]
+- Improve contrib/blast to return unused bytes
+- Assure that gzoffset() is correct when appending
+- Improve compress() and uncompress() to support large lengths
+- Fix bug in test/example.c where error code not saved
+- Remedy Coverity warning [Randers-Pehrson]
+- Improve speed of gzprintf() in transparent mode
+- Fix inflateInit2() bug when windowBits is 16 or 32
+- Change DEBUG macro to ZLIB_DEBUG
+- Avoid uninitialized access by gzclose_w()
+- Allow building zlib outside of the source directory
+- Fix bug that accepted invalid zlib header when windowBits is zero
+- Fix gzseek() problem on MinGW due to buggy _lseeki64 there
+- Loop on write() calls in gzwrite.c in case of non-blocking I/O
+- Add --warn (-w) option to ./configure for more compiler warnings
+- Reject a window size of 256 bytes if not using the zlib wrapper
+- Fix bug when level 0 used with Z_HUFFMAN or Z_RLE
+- Add --debug (-d) option to ./configure to define ZLIB_DEBUG
+- Fix bugs in creating a very large gzip header
+- Add uncompress2() function, which returns the input size used
+- Assure that deflateParams() will not switch functions mid-block
+- Dramatically speed up deflation for level 0 (storing)
+- Add gzfread(), duplicating the interface of fread()
+- Add gzfwrite(), duplicating the interface of fwrite()
+- Add deflateGetDictionary() function
+- Use snprintf() for later versions of Microsoft C
+- Fix *Init macros to use z_ prefix when requested
+- Replace as400 with os400 for OS/400 support [Monnerat]
+- Add crc32_z() and adler32_z() functions with size_t lengths
+- Update Visual Studio project files [AraHaan]
+
+Changes in 1.2.8 (28 Apr 2013)
+- Update contrib/minizip/iowin32.c for Windows RT [Vollant]
+- Do not force Z_CONST for C++
+- Clean up contrib/vstudio [Roß]
+- Correct spelling error in zlib.h
+- Fix mixed line endings in contrib/vstudio
+
+Changes in 1.2.7.3 (13 Apr 2013)
+- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc
+
+Changes in 1.2.7.2 (13 Apr 2013)
+- Change check for a four-byte type back to hexadecimal
+- Fix typo in win32/Makefile.msc
+- Add casts in gzwrite.c for pointer differences
+
+Changes in 1.2.7.1 (24 Mar 2013)
+- Replace use of unsafe string functions with snprintf if available
+- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink]
+- Fix gzgetc undefine when Z_PREFIX set [Turk]
+- Eliminate use of mktemp in Makefile (not always available)
+- Fix bug in 'F' mode for gzopen()
+- Add inflateGetDictionary() function
+- Correct comment in deflate.h
+- Use _snprintf for snprintf in Microsoft C
+- On Darwin, only use /usr/bin/libtool if libtool is not Apple
+- Delete "--version" file if created by "ar --version" [Richard G.]
+- Fix configure check for veracity of compiler error return codes
+- Fix CMake compilation of static lib for MSVC2010 x64
+- Remove unused variable in infback9.c
+- Fix argument checks in gzlog_compress() and gzlog_write()
+- Clean up the usage of z_const and respect const usage within zlib
+- Clean up examples/gzlog.[ch] comparisons of different types
+- Avoid shift equal to bits in type (caused endless loop)
+- Fix uninitialized value bug in gzputc() introduced by const patches
+- Fix memory allocation error in examples/zran.c [Nor]
+- Fix bug where gzopen(), gzclose() would write an empty file
+- Fix bug in gzclose() when gzwrite() runs out of memory
+- Check for input buffer malloc failure in examples/gzappend.c
+- Add note to contrib/blast to use binary mode in stdio
+- Fix comparisons of differently signed integers in contrib/blast
+- Check for invalid code length codes in contrib/puff
+- Fix serious but very rare decompression bug in inftrees.c
+- Update inflateBack() comments, since inflate() can be faster
+- Use underscored I/O function names for WINAPI_FAMILY
+- Add _tr_flush_bits to the external symbols prefixed by --zprefix
+- Add contrib/vstudio/vc10 pre-build step for static only
+- Quote --version-script argument in CMakeLists.txt
+- Don't specify --version-script on Apple platforms in CMakeLists.txt
+- Fix casting error in contrib/testzlib/testzlib.c
+- Fix types in contrib/minizip to match result of get_crc_table()
+- Simplify contrib/vstudio/vc10 with 'd' suffix
+- Add TOP support to win32/Makefile.msc
+- Support i686 and amd64 assembler builds in CMakeLists.txt
+- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h
+- Add vc11 and vc12 build files to contrib/vstudio
+- Add gzvprintf() as an undocumented function in zlib
+- Fix configure for Sun shell
+- Remove runtime check in configure for four-byte integer type
+- Add casts and consts to ease user conversion to C++
+- Add man pages for minizip and miniunzip
+- In Makefile uninstall, don't rm if preceding cd fails
+- Do not return Z_BUF_ERROR if deflateParam() has nothing to write
+
+Changes in 1.2.7 (2 May 2012)
+- Replace use of memmove() with a simple copy for portability
+- Test for existence of strerror
+- Restore gzgetc_ for backward compatibility with 1.2.6
+- Fix build with non-GNU make on Solaris
+- Require gcc 4.0 or later on Mac OS X to use the hidden attribute
+- Include unistd.h for Watcom C
+- Use __WATCOMC__ instead of __WATCOM__
+- Do not use the visibility attribute if NO_VIZ defined
+- Improve the detection of no hidden visibility attribute
+- Avoid using __int64 for gcc or solo compilation
+- Cast to char * in gzprintf to avoid warnings [Zinser]
+- Fix make_vms.com for VAX [Zinser]
+- Don't use library or built-in byte swaps
+- Simplify test and use of gcc hidden attribute
+- Fix bug in gzclose_w() when gzwrite() fails to allocate memory
+- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen()
+- Fix bug in test/minigzip.c for configure --solo
+- Fix contrib/vstudio project link errors [Mohanathas]
+- Add ability to choose the builder in make_vms.com [Schweda]
+- Add DESTDIR support to mingw32 win32/Makefile.gcc
+- Fix comments in win32/Makefile.gcc for proper usage
+- Allow overriding the default install locations for cmake
+- Generate and install the pkg-config file with cmake
+- Build both a static and a shared version of zlib with cmake
+- Include version symbols for cmake builds
+- If using cmake with MSVC, add the source directory to the includes
+- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta]
+- Move obsolete emx makefile to old [Truta]
+- Allow the use of -Wundef when compiling or using zlib
+- Avoid the use of the -u option with mktemp
+- Improve inflate() documentation on the use of Z_FINISH
+- Recognize clang as gcc
+- Add gzopen_w() in Windows for wide character path names
+- Rename zconf.h in CMakeLists.txt to move it out of the way
+- Add source directory in CMakeLists.txt for building examples
+- Look in build directory for zlib.pc in CMakeLists.txt
+- Remove gzflags from zlibvc.def in vc9 and vc10
+- Fix contrib/minizip compilation in the MinGW environment
+- Update ./configure for Solaris, support --64 [Mooney]
+- Remove -R. from Solaris shared build (possible security issue)
+- Avoid race condition for parallel make (-j) running example
+- Fix type mismatch between get_crc_table() and crc_table
+- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler]
+- Fix the path to zlib.map in CMakeLists.txt
+- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe]
+- Add instructions to win32/Makefile.gcc for shared install [Torri]
+
+Changes in 1.2.6.1 (12 Feb 2012)
+- Avoid the use of the Objective-C reserved name "id"
+- Include io.h in gzguts.h for Microsoft compilers
+- Fix problem with ./configure --prefix and gzgetc macro
+- Include gz_header definition when compiling zlib solo
+- Put gzflags() functionality back in zutil.c
+- Avoid library header include in crc32.c for Z_SOLO
+- Use name in GCC_CLASSIC as C compiler for coverage testing, if set
+- Minor cleanup in contrib/minizip/zip.c [Vollant]
+- Update make_vms.com [Zinser]
+- Remove unnecessary gzgetc_ function
+- Use optimized byte swap operations for Microsoft and GNU [Snyder]
+- Fix minor typo in zlib.h comments [Rzesniowiecki]
+
+Changes in 1.2.6 (29 Jan 2012)
+- Update the Pascal interface in contrib/pascal
+- Fix function numbers for gzgetc_ in zlibvc.def files
+- Fix configure.ac for contrib/minizip [Schiffer]
+- Fix large-entry detection in minizip on 64-bit systems [Schiffer]
+- Have ./configure use the compiler return code for error indication
+- Fix CMakeLists.txt for cross compilation [McClure]
+- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes]
+- Fix compilation of contrib/minizip on FreeBSD [Marquez]
+- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath]
+- Include io.h for Turbo C / Borland C on all platforms [Truta]
+- Make version explicit in contrib/minizip/configure.ac [Bosmans]
+- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant]
+- Minor cleanup up contrib/minizip/unzip.c [Vollant]
+- Fix bug when compiling minizip with C++ [Vollant]
+- Protect for long name and extra fields in contrib/minizip [Vollant]
+- Avoid some warnings in contrib/minizip [Vollant]
+- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip
+- Add missing libs to minizip linker command
+- Add support for VPATH builds in contrib/minizip
+- Add an --enable-demos option to contrib/minizip/configure
+- Add the generation of configure.log by ./configure
+- Exit when required parameters not provided to win32/Makefile.gcc
+- Have gzputc return the character written instead of the argument
+- Use the -m option on ldconfig for BSD systems [Tobias]
+- Correct in zlib.map when deflateResetKeep was added
+
+Changes in 1.2.5.3 (15 Jan 2012)
+- Restore gzgetc function for binary compatibility
+- Do not use _lseeki64 under Borland C++ [Truta]
+- Update win32/Makefile.msc to build test/*.c [Truta]
+- Remove old/visualc6 given CMakefile and other alternatives
+- Update AS400 build files and documentation [Monnerat]
+- Update win32/Makefile.gcc to build test/*.c [Truta]
+- Permit stronger flushes after Z_BLOCK flushes
+- Avoid extraneous empty blocks when doing empty flushes
+- Permit Z_NULL arguments to deflatePending
+- Allow deflatePrime() to insert bits in the middle of a stream
+- Remove second empty static block for Z_PARTIAL_FLUSH
+- Write out all of the available bits when using Z_BLOCK
+- Insert the first two strings in the hash table after a flush
+
+Changes in 1.2.5.2 (17 Dec 2011)
+- fix ld error: unable to find version dependency 'ZLIB_1.2.5'
+- use relative symlinks for shared libs
+- Avoid searching past window for Z_RLE strategy
+- Assure that high-water mark initialization is always applied in deflate
+- Add assertions to fill_window() in deflate.c to match comments
+- Update python link in README
+- Correct spelling error in gzread.c
+- Fix bug in gzgets() for a concatenated empty gzip stream
+- Correct error in comment for gz_make()
+- Change gzread() and related to ignore junk after gzip streams
+- Allow gzread() and related to continue after gzclearerr()
+- Allow gzrewind() and gzseek() after a premature end-of-file
+- Simplify gzseek() now that raw after gzip is ignored
+- Change gzgetc() to a macro for speed (~40% speedup in testing)
+- Fix gzclose() to return the actual error last encountered
+- Always add large file support for windows
+- Include zconf.h for windows large file support
+- Include zconf.h.cmakein for windows large file support
+- Update zconf.h.cmakein on make distclean
+- Merge vestigial vsnprintf determination from zutil.h to gzguts.h
+- Clarify how gzopen() appends in zlib.h comments
+- Correct documentation of gzdirect() since junk at end now ignored
+- Add a transparent write mode to gzopen() when 'T' is in the mode
+- Update python link in zlib man page
+- Get inffixed.h and MAKEFIXED result to match
+- Add a ./config --solo option to make zlib subset with no library use
+- Add undocumented inflateResetKeep() function for CAB file decoding
+- Add --cover option to ./configure for gcc coverage testing
+- Add #define ZLIB_CONST option to use const in the z_stream interface
+- Add comment to gzdopen() in zlib.h to use dup() when using fileno()
+- Note behavior of uncompress() to provide as much data as it can
+- Add files in contrib/minizip to aid in building libminizip
+- Split off AR options in Makefile.in and configure
+- Change ON macro to Z_ARG to avoid application conflicts
+- Facilitate compilation with Borland C++ for pragmas and vsnprintf
+- Include io.h for Turbo C / Borland C++
+- Move example.c and minigzip.c to test/
+- Simplify incomplete code table filling in inflate_table()
+- Remove code from inflate.c and infback.c that is impossible to execute
+- Test the inflate code with full coverage
+- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw)
+- Add deflateResetKeep and fix inflateResetKeep to retain dictionary
+- Fix gzwrite.c to accommodate reduced memory zlib compilation
+- Have inflate() with Z_FINISH avoid the allocation of a window
+- Do not set strm->adler when doing raw inflate
+- Fix gzeof() to behave just like feof() when read is not past end of file
+- Fix bug in gzread.c when end-of-file is reached
+- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF
+- Document gzread() capability to read concurrently written files
+- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo]
+
+Changes in 1.2.5.1 (10 Sep 2011)
+- Update FAQ entry on shared builds (#13)
+- Avoid symbolic argument to chmod in Makefile.in
+- Fix bug and add consts in contrib/puff [Oberhumer]
+- Update contrib/puff/zeros.raw test file to have all block types
+- Add full coverage test for puff in contrib/puff/Makefile
+- Fix static-only-build install in Makefile.in
+- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno]
+- Add libz.a dependency to shared in Makefile.in for parallel builds
+- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out
+- Replace $(...) with `...` in configure for non-bash sh [Bowler]
+- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen]
+- Add solaris* to Linux* in configure to allow gcc use [Groffen]
+- Add *bsd* to Linux* case in configure [Bar-Lev]
+- Add inffast.obj to dependencies in win32/Makefile.msc
+- Correct spelling error in deflate.h [Kohler]
+- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc
+- Add test to configure for GNU C looking for gcc in output of $cc -v
+- Add zlib.pc generation to win32/Makefile.gcc [Weigelt]
+- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not
+- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense
+- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser)
+- Make stronger test in zconf.h to include unistd.h for LFS
+- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack]
+- Fix zlib.h LFS support when Z_PREFIX used
+- Add updated as400 support (removed from old) [Monnerat]
+- Avoid deflate sensitivity to volatile input data
+- Avoid division in adler32_combine for NO_DIVIDE
+- Clarify the use of Z_FINISH with deflateBound() amount of space
+- Set binary for output file in puff.c
+- Use u4 type for crc_table to avoid conversion warnings
+- Apply casts in zlib.h to avoid conversion warnings
+- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller]
+- Improve inflateSync() documentation to note indeterminacy
+- Add deflatePending() function to return the amount of pending output
+- Correct the spelling of "specification" in FAQ [Randers-Pehrson]
+- Add a check in configure for stdarg.h, use for gzprintf()
+- Check that pointers fit in ints when gzprint() compiled old style
+- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler]
+- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt]
+- Add debug records in assembler code [Londer]
+- Update RFC references to use http://tools.ietf.org/html/... [Li]
+- Add --archs option, use of libtool to configure for Mac OS X [Borstel]
+
+Changes in 1.2.5 (19 Apr 2010)
+- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev]
+- Default to libdir as sharedlibdir in configure [Nieder]
+- Update copyright dates on modified source files
+- Update trees.c to be able to generate modified trees.h
+- Exit configure for MinGW, suggesting win32/Makefile.gcc
+- Check for NULL path in gz_open [Homurlu]
+
+Changes in 1.2.4.5 (18 Apr 2010)
+- Set sharedlibdir in configure [Torok]
+- Set LDFLAGS in Makefile.in [Bar-Lev]
+- Avoid mkdir objs race condition in Makefile.in [Bowler]
+- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays
+- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C
+- Don't use hidden attribute when it is a warning generator (e.g. Solaris)
+
+Changes in 1.2.4.4 (18 Apr 2010)
+- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok]
+- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty
+- Try to use bash or ksh regardless of functionality of /bin/sh
+- Fix configure incompatibility with NetBSD sh
+- Remove attempt to run under bash or ksh since have better NetBSD fix
+- Fix win32/Makefile.gcc for MinGW [Bar-Lev]
+- Add diagnostic messages when using CROSS_PREFIX in configure
+- Added --sharedlibdir option to configure [Weigelt]
+- Use hidden visibility attribute when available [Frysinger]
+
+Changes in 1.2.4.3 (10 Apr 2010)
+- Only use CROSS_PREFIX in configure for ar and ranlib if they exist
+- Use CROSS_PREFIX for nm [Bar-Lev]
+- Assume _LARGEFILE64_SOURCE defined is equivalent to true
+- Avoid use of undefined symbols in #if with && and ||
+- Make *64 prototypes in gzguts.h consistent with functions
+- Add -shared load option for MinGW in configure [Bowler]
+- Move z_off64_t to public interface, use instead of off64_t
+- Remove ! from shell test in configure (not portable to Solaris)
+- Change +0 macro tests to -0 for possibly increased portability
+
+Changes in 1.2.4.2 (9 Apr 2010)
+- Add consistent carriage returns to readme.txt's in masmx86 and masmx64
+- Really provide prototypes for *64 functions when building without LFS
+- Only define unlink() in minigzip.c if unistd.h not included
+- Update README to point to contrib/vstudio project files
+- Move projects/vc6 to old/ and remove projects/
+- Include stdlib.h in minigzip.c for setmode() definition under WinCE
+- Clean up assembler builds in win32/Makefile.msc [Rowe]
+- Include sys/types.h for Microsoft for off_t definition
+- Fix memory leak on error in gz_open()
+- Symbolize nm as $NM in configure [Weigelt]
+- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt]
+- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined
+- Fix bug in gzeof() to take into account unused input data
+- Avoid initialization of structures with variables in puff.c
+- Updated win32/README-WIN32.txt [Rowe]
+
+Changes in 1.2.4.1 (28 Mar 2010)
+- Remove the use of [a-z] constructs for sed in configure [gentoo 310225]
+- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech]
+- Restore "for debugging" comment on sprintf() in gzlib.c
+- Remove fdopen for MVS from gzguts.h
+- Put new README-WIN32.txt in win32 [Rowe]
+- Add check for shell to configure and invoke another shell if needed
+- Fix big fat stinking bug in gzseek() on uncompressed files
+- Remove vestigial F_OPEN64 define in zutil.h
+- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE
+- Avoid errors on non-LFS systems when applications define LFS macros
+- Set EXE to ".exe" in configure for MINGW [Kahle]
+- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill]
+- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev]
+- Add DLL install in win32/makefile.gcc [Bar-Lev]
+- Allow Linux* or linux* from uname in configure [Bar-Lev]
+- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev]
+- Add cross-compilation prefixes to configure [Bar-Lev]
+- Match type exactly in gz_load() invocation in gzread.c
+- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func
+- Provide prototypes for *64 functions when building zlib without LFS
+- Don't use -lc when linking shared library on MinGW
+- Remove errno.h check in configure and vestigial errno code in zutil.h
+
+Changes in 1.2.4 (14 Mar 2010)
+- Fix VER3 extraction in configure for no fourth subversion
+- Update zlib.3, add docs to Makefile.in to make .pdf out of it
+- Add zlib.3.pdf to distribution
+- Don't set error code in gzerror() if passed pointer is NULL
+- Apply destination directory fixes to CMakeLists.txt [Lowman]
+- Move #cmakedefine's to a new zconf.in.cmakein
+- Restore zconf.h for builds that don't use configure or cmake
+- Add distclean to dummy Makefile for convenience
+- Update and improve INDEX, README, and FAQ
+- Update CMakeLists.txt for the return of zconf.h [Lowman]
+- Update contrib/vstudio/vc9 and vc10 [Vollant]
+- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc
+- Apply license and readme changes to contrib/asm686 [Raiter]
+- Check file name lengths and add -c option in minigzip.c [Li]
+- Update contrib/amd64 and contrib/masmx86/ [Vollant]
+- Avoid use of "eof" parameter in trees.c to not shadow library variable
+- Update make_vms.com for removal of zlibdefs.h [Zinser]
+- Update assembler code and vstudio projects in contrib [Vollant]
+- Remove outdated assembler code contrib/masm686 and contrib/asm586
+- Remove old vc7 and vc8 from contrib/vstudio
+- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe]
+- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open()
+- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant]
+- Remove *64 functions from win32/zlib.def (they're not 64-bit yet)
+- Fix bug in void-returning vsprintf() case in gzwrite.c
+- Fix name change from inflate.h in contrib/inflate86/inffas86.c
+- Check if temporary file exists before removing in make_vms.com [Zinser]
+- Fix make install and uninstall for --static option
+- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta]
+- Update readme.txt in contrib/masmx64 and masmx86 to assemble
+
+Changes in 1.2.3.9 (21 Feb 2010)
+- Expunge gzio.c
+- Move as400 build information to old
+- Fix updates in contrib/minizip and contrib/vstudio
+- Add const to vsnprintf test in configure to avoid warnings [Weigelt]
+- Delete zconf.h (made by configure) [Weigelt]
+- Change zconf.in.h to zconf.h.in per convention [Weigelt]
+- Check for NULL buf in gzgets()
+- Return empty string for gzgets() with len == 1 (like fgets())
+- Fix description of gzgets() in zlib.h for end-of-file, NULL return
+- Update minizip to 1.1 [Vollant]
+- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c
+- Note in zlib.h that gzerror() should be used to distinguish from EOF
+- Remove use of snprintf() from gzlib.c
+- Fix bug in gzseek()
+- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant]
+- Fix zconf.h generation in CMakeLists.txt [Lowman]
+- Improve comments in zconf.h where modified by configure
+
+Changes in 1.2.3.8 (13 Feb 2010)
+- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer]
+- Use z_off64_t in gz_zero() and gz_skip() to match state->skip
+- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t)
+- Revert to Makefile.in from 1.2.3.6 (live with the clutter)
+- Fix missing error return in gzflush(), add zlib.h note
+- Add *64 functions to zlib.map [Levin]
+- Fix signed/unsigned comparison in gz_comp()
+- Use SFLAGS when testing shared linking in configure
+- Add --64 option to ./configure to use -m64 with gcc
+- Fix ./configure --help to correctly name options
+- Have make fail if a test fails [Levin]
+- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson]
+- Remove assembler object files from contrib
+
+Changes in 1.2.3.7 (24 Jan 2010)
+- Always gzopen() with O_LARGEFILE if available
+- Fix gzdirect() to work immediately after gzopen() or gzdopen()
+- Make gzdirect() more precise when the state changes while reading
+- Improve zlib.h documentation in many places
+- Catch memory allocation failure in gz_open()
+- Complete close operation if seek forward in gzclose_w() fails
+- Return Z_ERRNO from gzclose_r() if close() fails
+- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL
+- Return zero for gzwrite() errors to match zlib.h description
+- Return -1 on gzputs() error to match zlib.h description
+- Add zconf.in.h to allow recovery from configure modification [Weigelt]
+- Fix static library permissions in Makefile.in [Weigelt]
+- Avoid warnings in configure tests that hide functionality [Weigelt]
+- Add *BSD and DragonFly to Linux case in configure [gentoo 123571]
+- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212]
+- Avoid access of uninitialized data for first inflateReset2 call [Gomes]
+- Keep object files in subdirectories to reduce the clutter somewhat
+- Remove default Makefile and zlibdefs.h, add dummy Makefile
+- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_
+- Remove zlibdefs.h completely -- modify zconf.h instead
+
+Changes in 1.2.3.6 (17 Jan 2010)
+- Avoid void * arithmetic in gzread.c and gzwrite.c
+- Make compilers happier with const char * for gz_error message
+- Avoid unused parameter warning in inflate.c
+- Avoid signed-unsigned comparison warning in inflate.c
+- Indent #pragma's for traditional C
+- Fix usage of strwinerror() in glib.c, change to gz_strwinerror()
+- Correct email address in configure for system options
+- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser]
+- Update zlib.map [Brown]
+- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok]
+- Apply various fixes to CMakeLists.txt [Lowman]
+- Add checks on len in gzread() and gzwrite()
+- Add error message for no more room for gzungetc()
+- Remove zlib version check in gzwrite()
+- Defer compression of gzprintf() result until need to
+- Use snprintf() in gzdopen() if available
+- Remove USE_MMAP configuration determination (only used by minigzip)
+- Remove examples/pigz.c (available separately)
+- Update examples/gun.c to 1.6
+
+Changes in 1.2.3.5 (8 Jan 2010)
+- Add space after #if in zutil.h for some compilers
+- Fix relatively harmless bug in deflate_fast() [Exarevsky]
+- Fix same problem in deflate_slow()
+- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown]
+- Add deflate_rle() for faster Z_RLE strategy run-length encoding
+- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding
+- Change name of "write" variable in inffast.c to avoid library collisions
+- Fix premature EOF from gzread() in gzio.c [Brown]
+- Use zlib header window size if windowBits is 0 in inflateInit2()
+- Remove compressBound() call in deflate.c to avoid linking compress.o
+- Replace use of errno in gz* with functions, support WinCE [Alves]
+- Provide alternative to perror() in minigzip.c for WinCE [Alves]
+- Don't use _vsnprintf on later versions of MSVC [Lowman]
+- Add CMake build script and input file [Lowman]
+- Update contrib/minizip to 1.1 [Svensson, Vollant]
+- Moved nintendods directory from contrib to root
+- Replace gzio.c with a new set of routines with the same functionality
+- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above
+- Update contrib/minizip to 1.1b
+- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h
+
+Changes in 1.2.3.4 (21 Dec 2009)
+- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility
+- Update comments in configure and Makefile.in for default --shared
+- Fix test -z's in configure [Marquess]
+- Build examplesh and minigzipsh when not testing
+- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h
+- Import LDFLAGS from the environment in configure
+- Fix configure to populate SFLAGS with discovered CFLAGS options
+- Adapt make_vms.com to the new Makefile.in [Zinser]
+- Add zlib2ansi script for C++ compilation [Marquess]
+- Add _FILE_OFFSET_BITS=64 test to make test (when applicable)
+- Add AMD64 assembler code for longest match to contrib [Teterin]
+- Include options from $SFLAGS when doing $LDSHARED
+- Simplify 64-bit file support by introducing z_off64_t type
+- Make shared object files in objs directory to work around old Sun cc
+- Use only three-part version number for Darwin shared compiles
+- Add rc option to ar in Makefile.in for when ./configure not run
+- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4*
+- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile
+- Protect against _FILE_OFFSET_BITS being defined when compiling zlib
+- Rename Makefile.in targets allstatic to static and allshared to shared
+- Fix static and shared Makefile.in targets to be independent
+- Correct error return bug in gz_open() by setting state [Brown]
+- Put spaces before ;;'s in configure for better sh compatibility
+- Add pigz.c (parallel implementation of gzip) to examples/
+- Correct constant in crc32.c to UL [Leventhal]
+- Reject negative lengths in crc32_combine()
+- Add inflateReset2() function to work like inflateEnd()/inflateInit2()
+- Include sys/types.h for _LARGEFILE64_SOURCE [Brown]
+- Correct typo in doc/algorithm.txt [Janik]
+- Fix bug in adler32_combine() [Zhu]
+- Catch missing-end-of-block-code error in all inflates and in puff
+ Assures that random input to inflate eventually results in an error
+- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/
+- Update ENOUGH and its usage to reflect discovered bounds
+- Fix gzerror() error report on empty input file [Brown]
+- Add ush casts in trees.c to avoid pedantic runtime errors
+- Fix typo in zlib.h uncompress() description [Reiss]
+- Correct inflate() comments with regard to automatic header detection
+- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays)
+- Put new version of gzlog (2.0) in examples with interruption recovery
+- Add puff compile option to permit invalid distance-too-far streams
+- Add puff TEST command options, ability to read piped input
+- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but
+ _LARGEFILE64_SOURCE not defined
+- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart
+- Fix deflateSetDictionary() to use all 32K for output consistency
+- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h)
+- Clear bytes after deflate lookahead to avoid use of uninitialized data
+- Change a limit in inftrees.c to be more transparent to Coverity Prevent
+- Update win32/zlib.def with exported symbols from zlib.h
+- Correct spelling errors in zlib.h [Willem, Sobrado]
+- Allow Z_BLOCK for deflate() to force a new block
+- Allow negative bits in inflatePrime() to delete existing bit buffer
+- Add Z_TREES flush option to inflate() to return at end of trees
+- Add inflateMark() to return current state information for random access
+- Add Makefile for NintendoDS to contrib [Costa]
+- Add -w in configure compile tests to avoid spurious warnings [Beucler]
+- Fix typos in zlib.h comments for deflateSetDictionary()
+- Fix EOF detection in transparent gzread() [Maier]
+
+Changes in 1.2.3.3 (2 October 2006)
+- Make --shared the default for configure, add a --static option
+- Add compile option to permit invalid distance-too-far streams
+- Add inflateUndermine() function which is required to enable above
+- Remove use of "this" variable name for C++ compatibility [Marquess]
+- Add testing of shared library in make test, if shared library built
+- Use ftello() and fseeko() if available instead of ftell() and fseek()
+- Provide two versions of all functions that use the z_off_t type for
+ binary compatibility -- a normal version and a 64-bit offset version,
+ per the Large File Support Extension when _LARGEFILE64_SOURCE is
+ defined; use the 64-bit versions by default when _FILE_OFFSET_BITS
+ is defined to be 64
+- Add a --uname= option to configure to perhaps help with cross-compiling
+
+Changes in 1.2.3.2 (3 September 2006)
+- Turn off silly Borland warnings [Hay]
+- Use off64_t and define _LARGEFILE64_SOURCE when present
+- Fix missing dependency on inffixed.h in Makefile.in
+- Rig configure --shared to build both shared and static [Teredesai, Truta]
+- Remove zconf.in.h and instead create a new zlibdefs.h file
+- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant]
+- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt]
+
+Changes in 1.2.3.1 (16 August 2006)
+- Add watcom directory with OpenWatcom make files [Daniel]
+- Remove #undef of FAR in zconf.in.h for MVS [Fedtke]
+- Update make_vms.com [Zinser]
+- Use -fPIC for shared build in configure [Teredesai, Nicholson]
+- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen]
+- Use fdopen() (not _fdopen()) for Interix in zutil.h [Bäck]
+- Add some FAQ entries about the contrib directory
+- Update the MVS question in the FAQ
+- Avoid extraneous reads after EOF in gzio.c [Brown]
+- Correct spelling of "successfully" in gzio.c [Randers-Pehrson]
+- Add comments to zlib.h about gzerror() usage [Brown]
+- Set extra flags in gzip header in gzopen() like deflate() does
+- Make configure options more compatible with double-dash conventions
+ [Weigelt]
+- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen]
+- Fix uninstall target in Makefile.in [Truta]
+- Add pkgconfig support [Weigelt]
+- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt]
+- Replace set_data_type() with a more accurate detect_data_type() in
+ trees.c, according to the txtvsbin.txt document [Truta]
+- Swap the order of #include and #include "zlib.h" in
+ gzio.c, example.c and minigzip.c [Truta]
+- Shut up annoying VS2005 warnings about standard C deprecation [Rowe,
+ Truta] (where?)
+- Fix target "clean" from win32/Makefile.bor [Truta]
+- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe]
+- Update zlib www home address in win32/DLL_FAQ.txt [Truta]
+- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove]
+- Enable browse info in the "Debug" and "ASM Debug" configurations in
+ the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta]
+- Add pkgconfig support [Weigelt]
+- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h,
+ for use in win32/zlib1.rc [Polushin, Rowe, Truta]
+- Add a document that explains the new text detection scheme to
+ doc/txtvsbin.txt [Truta]
+- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta]
+- Move algorithm.txt into doc/ [Truta]
+- Synchronize FAQ with website
+- Fix compressBound(), was low for some pathological cases [Fearnley]
+- Take into account wrapper variations in deflateBound()
+- Set examples/zpipe.c input and output to binary mode for Windows
+- Update examples/zlib_how.html with new zpipe.c (also web site)
+- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems
+ that gcc became pickier in 4.0)
+- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain
+ un-versioned, the patch adds versioning only for symbols introduced in
+ zlib-1.2.0 or later. It also declares as local those symbols which are
+ not designed to be exported." [Levin]
+- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure
+- Do not initialize global static by default in trees.c, add a response
+ NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess]
+- Don't use strerror() in gzio.c under WinCE [Yakimov]
+- Don't use errno.h in zutil.h under WinCE [Yakimov]
+- Move arguments for AR to its usage to allow replacing ar [Marot]
+- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson]
+- Improve inflateInit() and inflateInit2() documentation
+- Fix structure size comment in inflate.h
+- Change configure help option from --h* to --help [Santos]
+
+Changes in 1.2.3 (18 July 2005)
+- Apply security vulnerability fixes to contrib/infback9 as well
+- Clean up some text files (carriage returns, trailing space)
+- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
+
+Changes in 1.2.2.4 (11 July 2005)
+- Add inflatePrime() function for starting inflation at bit boundary
+- Avoid some Visual C warnings in deflate.c
+- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
+ compile
+- Fix some spelling errors in comments [Betts]
+- Correct inflateInit2() error return documentation in zlib.h
+- Add zran.c example of compressed data random access to examples
+ directory, shows use of inflatePrime()
+- Fix cast for assignments to strm->state in inflate.c and infback.c
+- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
+- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
+- Add cast in trees.c t avoid a warning [Oberhumer]
+- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
+- Update make_vms.com [Zinser]
+- Initialize state->write in inflateReset() since copied in inflate_fast()
+- Be more strict on incomplete code sets in inflate_table() and increase
+ ENOUGH and MAXD -- this repairs a possible security vulnerability for
+ invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for
+ discovering the vulnerability and providing test cases
+- Add ia64 support to configure for HP-UX [Smith]
+- Add error return to gzread() for format or i/o error [Levin]
+- Use malloc.h for OS/2 [Necasek]
+
+Changes in 1.2.2.3 (27 May 2005)
+- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
+- Typecast fread() return values in gzio.c [Vollant]
+- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
+- Fix crc check bug in gzread() after gzungetc() [Heiner]
+- Add the deflateTune() function to adjust internal compression parameters
+- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
+- Remove an incorrect assertion in examples/zpipe.c
+- Add C++ wrapper in infback9.h [Donais]
+- Fix bug in inflateCopy() when decoding fixed codes
+- Note in zlib.h how much deflateSetDictionary() actually uses
+- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
+- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
+- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
+- Add gzdirect() function to indicate transparent reads
+- Update contrib/minizip [Vollant]
+- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
+- Add casts in crc32.c to avoid warnings [Oberhumer]
+- Add contrib/masmx64 [Vollant]
+- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
+
+Changes in 1.2.2.2 (30 December 2004)
+- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
+ avoid implicit memcpy calls (portability for no-library compilation)
+- Increase sprintf() buffer size in gzdopen() to allow for large numbers
+- Add INFLATE_STRICT to check distances against zlib header
+- Improve WinCE errno handling and comments [Chang]
+- Remove comment about no gzip header processing in FAQ
+- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
+- Add updated make_vms.com [Coghlan], update README
+- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
+ fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html
+- Add FAQ entry and comments in deflate.c on uninitialized memory access
+- Add Solaris 9 make options in configure [Gilbert]
+- Allow strerror() usage in gzio.c for STDC
+- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
+- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
+- Use z_off_t for adler32_combine() and crc32_combine() lengths
+- Make adler32() much faster for small len
+- Use OS_CODE in deflate() default gzip header
+
+Changes in 1.2.2.1 (31 October 2004)
+- Allow inflateSetDictionary() call for raw inflate
+- Fix inflate header crc check bug for file names and comments
+- Add deflateSetHeader() and gz_header structure for custom gzip headers
+- Add inflateGetheader() to retrieve gzip headers
+- Add crc32_combine() and adler32_combine() functions
+- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
+- Use zstreamp consistently in zlib.h (inflate_back functions)
+- Remove GUNZIP condition from definition of inflate_mode in inflate.h
+ and in contrib/inflate86/inffast.S [Truta, Anderson]
+- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
+- Update projects/README.projects and projects/visualc6 [Truta]
+- Update win32/DLL_FAQ.txt [Truta]
+- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
+- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
+- Use a new algorithm for setting strm->data_type in trees.c [Truta]
+- Do not define an exit() prototype in zutil.c unless DEBUG defined
+- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
+- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
+- Fix Darwin build version identification [Peterson]
+
+Changes in 1.2.2 (3 October 2004)
+- Update zlib.h comments on gzip in-memory processing
+- Set adler to 1 in inflateReset() to support Java test suite [Walles]
+- Add contrib/dotzlib [Ravn]
+- Update win32/DLL_FAQ.txt [Truta]
+- Update contrib/minizip [Vollant]
+- Move contrib/visual-basic.txt to old/ [Truta]
+- Fix assembler builds in projects/visualc6/ [Truta]
+
+Changes in 1.2.1.2 (9 September 2004)
+- Update INDEX file
+- Fix trees.c to update strm->data_type (no one ever noticed!)
+- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
+- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
+- Add limited multitasking protection to DYNAMIC_CRC_TABLE
+- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
+- Don't declare strerror() under VMS [Mozilla]
+- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
+- Update contrib/ada [Anisimkov]
+- Update contrib/minizip [Vollant]
+- Fix configure to not hardcode directories for Darwin [Peterson]
+- Fix gzio.c to not return error on empty files [Brown]
+- Fix indentation; update version in contrib/delphi/ZLib.pas and
+ contrib/pascal/zlibpas.pas [Truta]
+- Update mkasm.bat in contrib/masmx86 [Truta]
+- Update contrib/untgz [Truta]
+- Add projects/README.projects [Truta]
+- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
+- Update win32/DLL_FAQ.txt [Truta]
+- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
+- Remove an unnecessary assignment to curr in inftrees.c [Truta]
+- Add OS/2 to exe builds in configure [Poltorak]
+- Remove err dummy parameter in zlib.h [Kientzle]
+
+Changes in 1.2.1.1 (9 January 2004)
+- Update email address in README
+- Several FAQ updates
+- Fix a big fat bug in inftrees.c that prevented decoding valid
+ dynamic blocks with only literals and no distance codes --
+ Thanks to "Hot Emu" for the bug report and sample file
+- Add a note to puff.c on no distance codes case
+
+Changes in 1.2.1 (17 November 2003)
+- Remove a tab in contrib/gzappend/gzappend.c
+- Update some interfaces in contrib for new zlib functions
+- Update zlib version number in some contrib entries
+- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
+- Support shared libraries on Hurd and KFreeBSD [Brown]
+- Fix error in NO_DIVIDE option of adler32.c
+
+Changes in 1.2.0.8 (4 November 2003)
+- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
+- Add experimental NO_DIVIDE #define in adler32.c
+ - Possibly faster on some processors (let me know if it is)
+- Correct Z_BLOCK to not return on first inflate call if no wrap
+- Fix strm->data_type on inflate() return to correctly indicate EOB
+- Add deflatePrime() function for appending in the middle of a byte
+- Add contrib/gzappend for an example of appending to a stream
+- Update win32/DLL_FAQ.txt [Truta]
+- Delete Turbo C comment in README [Truta]
+- Improve some indentation in zconf.h [Truta]
+- Fix infinite loop on bad input in configure script [Church]
+- Fix gzeof() for concatenated gzip files [Johnson]
+- Add example to contrib/visual-basic.txt [Michael B.]
+- Add -p to mkdir's in Makefile.in [vda]
+- Fix configure to properly detect presence or lack of printf functions
+- Add AS400 support [Monnerat]
+- Add a little Cygwin support [Wilson]
+
+Changes in 1.2.0.7 (21 September 2003)
+- Correct some debug formats in contrib/infback9
+- Cast a type in a debug statement in trees.c
+- Change search and replace delimiter in configure from % to # [Beebe]
+- Update contrib/untgz to 0.2 with various fixes [Truta]
+- Add build support for Amiga [Nikl]
+- Remove some directories in old that have been updated to 1.2
+- Add dylib building for Mac OS X in configure and Makefile.in
+- Remove old distribution stuff from Makefile
+- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
+- Update links in README
+
+Changes in 1.2.0.6 (13 September 2003)
+- Minor FAQ updates
+- Update contrib/minizip to 1.00 [Vollant]
+- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
+- Update POSTINC comment for 68060 [Nikl]
+- Add contrib/infback9 with deflate64 decoding (unsupported)
+- For MVS define NO_vsnprintf and undefine FAR [van Burik]
+- Add pragma for fdopen on MVS [van Burik]
+
+Changes in 1.2.0.5 (8 September 2003)
+- Add OF to inflateBackEnd() declaration in zlib.h
+- Remember start when using gzdopen in the middle of a file
+- Use internal off_t counters in gz* functions to properly handle seeks
+- Perform more rigorous check for distance-too-far in inffast.c
+- Add Z_BLOCK flush option to return from inflate at block boundary
+- Set strm->data_type on return from inflate
+ - Indicate bits unused, if at block boundary, and if in last block
+- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
+- Add condition so old NO_DEFLATE define still works for compatibility
+- FAQ update regarding the Windows DLL [Truta]
+- INDEX update: add qnx entry, remove aix entry [Truta]
+- Install zlib.3 into mandir [Wilson]
+- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
+- Adapt the zlib interface to the new DLL convention guidelines [Truta]
+- Introduce ZLIB_WINAPI macro to allow the export of functions using
+ the WINAPI calling convention, for Visual Basic [Vollant, Truta]
+- Update msdos and win32 scripts and makefiles [Truta]
+- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
+- Add contrib/ada [Anisimkov]
+- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
+- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
+- Add contrib/masm686 [Truta]
+- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
+ [Truta, Vollant]
+- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
+- Remove contrib/delphi2; add a new contrib/delphi [Truta]
+- Avoid inclusion of the nonstandard in contrib/iostream,
+ and fix some method prototypes [Truta]
+- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
+ [Truta]
+- Avoid the use of backslash (\) in contrib/minizip [Vollant]
+- Fix file time handling in contrib/untgz; update makefiles [Truta]
+- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
+ [Vollant]
+- Remove contrib/vstudio/vc15_16 [Vollant]
+- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
+- Update README.contrib [Truta]
+- Invert the assignment order of match_head and s->prev[...] in
+ INSERT_STRING [Truta]
+- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
+ [Truta]
+- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
+- Fix prototype of syncsearch in inflate.c [Truta]
+- Introduce ASMINF macro to be enabled when using an ASM implementation
+ of inflate_fast [Truta]
+- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
+- Modify test_gzio in example.c to take a single file name as a
+ parameter [Truta]
+- Exit the example.c program if gzopen fails [Truta]
+- Add type casts around strlen in example.c [Truta]
+- Remove casting to sizeof in minigzip.c; give a proper type
+ to the variable compared with SUFFIX_LEN [Truta]
+- Update definitions of STDC and STDC99 in zconf.h [Truta]
+- Synchronize zconf.h with the new Windows DLL interface [Truta]
+- Use SYS16BIT instead of __32BIT__ to distinguish between
+ 16- and 32-bit platforms [Truta]
+- Use far memory allocators in small 16-bit memory models for
+ Turbo C [Truta]
+- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
+ zlibCompileFlags [Truta]
+- Cygwin has vsnprintf [Wilson]
+- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
+- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
+
+Changes in 1.2.0.4 (10 August 2003)
+- Minor FAQ updates
+- Be more strict when checking inflateInit2's windowBits parameter
+- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
+- Add gzip wrapper option to deflateInit2 using windowBits
+- Add updated QNX rule in configure and qnx directory [Bonnefoy]
+- Make inflate distance-too-far checks more rigorous
+- Clean up FAR usage in inflate
+- Add casting to sizeof() in gzio.c and minigzip.c
+
+Changes in 1.2.0.3 (19 July 2003)
+- Fix silly error in gzungetc() implementation [Vollant]
+- Update contrib/minizip and contrib/vstudio [Vollant]
+- Fix printf format in example.c
+- Correct cdecl support in zconf.in.h [Anisimkov]
+- Minor FAQ updates
+
+Changes in 1.2.0.2 (13 July 2003)
+- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
+- Attempt to avoid warnings in crc32.c for pointer-int conversion
+- Add AIX to configure, remove aix directory [Bakker]
+- Add some casts to minigzip.c
+- Improve checking after insecure sprintf() or vsprintf() calls
+- Remove #elif's from crc32.c
+- Change leave label to inf_leave in inflate.c and infback.c to avoid
+ library conflicts
+- Remove inflate gzip decoding by default--only enable gzip decoding by
+ special request for stricter backward compatibility
+- Add zlibCompileFlags() function to return compilation information
+- More typecasting in deflate.c to avoid warnings
+- Remove leading underscore from _Capital #defines [Truta]
+- Fix configure to link shared library when testing
+- Add some Windows CE target adjustments [Mai]
+- Remove #define ZLIB_DLL in zconf.h [Vollant]
+- Add zlib.3 [Rodgers]
+- Update RFC URL in deflate.c and algorithm.txt [Mai]
+- Add zlib_dll_FAQ.txt to contrib [Truta]
+- Add UL to some constants [Truta]
+- Update minizip and vstudio [Vollant]
+- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
+- Expand use of NO_DUMMY_DECL to avoid all dummy structures
+- Added iostream3 to contrib [Schwardt]
+- Replace rewind() with fseek() for WinCE [Truta]
+- Improve setting of zlib format compression level flags
+ - Report 0 for huffman and rle strategies and for level == 0 or 1
+ - Report 2 only for level == 6
+- Only deal with 64K limit when necessary at compile time [Truta]
+- Allow TOO_FAR check to be turned off at compile time [Truta]
+- Add gzclearerr() function [Souza]
+- Add gzungetc() function
+
+Changes in 1.2.0.1 (17 March 2003)
+- Add Z_RLE strategy for run-length encoding [Truta]
+ - When Z_RLE requested, restrict matches to distance one
+ - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
+- Correct FASTEST compilation to allow level == 0
+- Clean up what gets compiled for FASTEST
+- Incorporate changes to zconf.in.h [Vollant]
+ - Refine detection of Turbo C need for dummy returns
+ - Refine ZLIB_DLL compilation
+ - Include additional header file on VMS for off_t typedef
+- Try to use _vsnprintf where it supplants vsprintf [Vollant]
+- Add some casts in inffast.c
+- Enhance comments in zlib.h on what happens if gzprintf() tries to
+ write more than 4095 bytes before compression
+- Remove unused state from inflateBackEnd()
+- Remove exit(0) from minigzip.c, example.c
+- Get rid of all those darn tabs
+- Add "check" target to Makefile.in that does the same thing as "test"
+- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
+- Update contrib/inflate86 [Anderson]
+- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
+- Add msdos and win32 directories with makefiles [Truta]
+- More additions and improvements to the FAQ
+
+Changes in 1.2.0 (9 March 2003)
+- New and improved inflate code
+ - About 20% faster
+ - Does not allocate 32K window unless and until needed
+ - Automatically detects and decompresses gzip streams
+ - Raw inflate no longer needs an extra dummy byte at end
+ - Added inflateBack functions using a callback interface--even faster
+ than inflate, useful for file utilities (gzip, zip)
+ - Added inflateCopy() function to record state for random access on
+ externally generated deflate streams (e.g. in gzip files)
+ - More readable code (I hope)
+- New and improved crc32()
+ - About 50% faster, thanks to suggestions from Rodney Brown
+- Add deflateBound() and compressBound() functions
+- Fix memory leak in deflateInit2()
+- Permit setting dictionary for raw deflate (for parallel deflate)
+- Fix const declaration for gzwrite()
+- Check for some malloc() failures in gzio.c
+- Fix bug in gzopen() on single-byte file 0x1f
+- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
+ and next buffer doesn't start with 0x8b
+- Fix uncompress() to return Z_DATA_ERROR on truncated input
+- Free memory at end of example.c
+- Remove MAX #define in trees.c (conflicted with some libraries)
+- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
+- Declare malloc() and free() in gzio.c if STDC not defined
+- Use malloc() instead of calloc() in zutil.c if int big enough
+- Define STDC for AIX
+- Add aix/ with approach for compiling shared library on AIX
+- Add HP-UX support for shared libraries in configure
+- Add OpenUNIX support for shared libraries in configure
+- Use $cc instead of gcc to build shared library
+- Make prefix directory if needed when installing
+- Correct Macintosh avoidance of typedef Byte in zconf.h
+- Correct Turbo C memory allocation when under Linux
+- Use libz.a instead of -lz in Makefile (assure use of compiled library)
+- Update configure to check for snprintf or vsnprintf functions and their
+ return value, warn during make if using an insecure function
+- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
+ is lost when library is used--resolution is to build new zconf.h
+- Documentation improvements (in zlib.h):
+ - Document raw deflate and inflate
+ - Update RFCs URL
+ - Point out that zlib and gzip formats are different
+ - Note that Z_BUF_ERROR is not fatal
+ - Document string limit for gzprintf() and possible buffer overflow
+ - Note requirement on avail_out when flushing
+ - Note permitted values of flush parameter of inflate()
+- Add some FAQs (and even answers) to the FAQ
+- Add contrib/inflate86/ for x86 faster inflate
+- Add contrib/blast/ for PKWare Data Compression Library decompression
+- Add contrib/puff/ simple inflate for deflate format description
+
+Changes in 1.1.4 (11 March 2002)
+- ZFREE was repeated on same allocation on some error conditions
+ This creates a security problem described in
+ http://www.zlib.org/advisory-2002-03-11.txt
+- Returned incorrect error (Z_MEM_ERROR) on some invalid data
+- Avoid accesses before window for invalid distances with inflate window
+ less than 32K
+- force windowBits > 8 to avoid a bug in the encoder for a window size
+ of 256 bytes. (A complete fix will be available in 1.1.5)
+
+Changes in 1.1.3 (9 July 1998)
+- fix "an inflate input buffer bug that shows up on rare but persistent
+ occasions" (Mark)
+- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
+- fix gzseek(..., SEEK_SET) in write mode
+- fix crc check after a gzeek (Frank Faubert)
+- fix miniunzip when the last entry in a zip file is itself a zip file
+ (J Lillge)
+- add contrib/asm586 and contrib/asm686 (Brian Raiter)
+ See http://www.muppetlabs.com/~breadbox/software/assembly.html
+- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
+- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
+- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
+- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
+- added a FAQ file
+
+- Support gzdopen on Mac with Metrowerks (Jason Linhart)
+- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
+- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
+- avoid some warnings with Borland C (Tom Tanner)
+- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
+- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant)
+- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
+- use libdir and includedir in Makefile.in (Tim Mooney)
+- support shared libraries on OSF1 V4 (Tim Mooney)
+- remove so_locations in "make clean" (Tim Mooney)
+- fix maketree.c compilation error (Glenn, Mark)
+- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
+- new Makefile.riscos (Rich Walker)
+- initialize static descriptors in trees.c for embedded targets (Nick Smith)
+- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
+- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
+- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
+- fix maketree.c to allow clean compilation of inffixed.h (Mark)
+- fix parameter check in deflateCopy (Gunther Nikl)
+- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
+- Many portability patches by Christian Spieler:
+ . zutil.c, zutil.h: added "const" for zmem*
+ . Make_vms.com: fixed some typos
+ . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
+ . msdos/Makefile.msc: remove "default rtl link library" info from obj files
+ . msdos/Makefile.*: use model-dependent name for the built zlib library
+ . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
+ new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
+- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
+- replace __far with _far for better portability (Christian Spieler, Tom Lane)
+- fix test for errno.h in configure (Tim Newsham)
+
+Changes in 1.1.2 (19 March 98)
+- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
+ See http://www.winimage.com/zLibDll/unzip.html
+- preinitialize the inflate tables for fixed codes, to make the code
+ completely thread safe (Mark)
+- some simplifications and slight speed-up to the inflate code (Mark)
+- fix gzeof on non-compressed files (Allan Schrum)
+- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
+- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
+- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
+- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
+- do not wrap extern "C" around system includes (Tom Lane)
+- mention zlib binding for TCL in README (Andreas Kupries)
+- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
+- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
+- allow "configure --prefix $HOME" (Tim Mooney)
+- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
+- move Makefile.sas to amiga/Makefile.sas
+
+Changes in 1.1.1 (27 Feb 98)
+- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson)
+- remove block truncation heuristic which had very marginal effect for zlib
+ (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
+ compression ratio on some files. This also allows inlining _tr_tally for
+ matches in deflate_slow
+- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
+
+Changes in 1.1.0 (24 Feb 98)
+- do not return STREAM_END prematurely in inflate (John Bowler)
+- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
+- compile with -DFASTEST to get compression code optimized for speed only
+- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
+- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
+ on Sun but significant on HP)
+
+- add a pointer to experimental unzip library in README (Gilles Vollant)
+- initialize variable gcc in configure (Chris Herborth)
+
+Changes in 1.0.9 (17 Feb 1998)
+- added gzputs and gzgets functions
+- do not clear eof flag in gzseek (Mark Diekhans)
+- fix gzseek for files in transparent mode (Mark Diekhans)
+- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
+- replace EXPORT with ZEXPORT to avoid conflict with other programs
+- added compress2 in zconf.h, zlib.def, zlib.dnt
+- new asm code from Gilles Vollant in contrib/asm386
+- simplify the inflate code (Mark):
+ . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
+ . ZALLOC the length list in inflate_trees_fixed() instead of using stack
+ . ZALLOC the value area for huft_build() instead of using stack
+ . Simplify Z_FINISH check in inflate()
+
+- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
+- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
+- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
+ the declaration of FAR (Gilles Vollant)
+- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
+- read_buf buf parameter of type Bytef* instead of charf*
+- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
+- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
+- fix check for presence of directories in "make install" (Ian Willis)
+
+Changes in 1.0.8 (27 Jan 1998)
+- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
+- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
+- added compress2() to allow setting the compression level
+- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
+- use constant arrays for the static trees in trees.c instead of computing
+ them at run time (thanks to Ken Raeburn for this suggestion). To create
+ trees.h, compile with GEN_TREES_H and run "make test"
+- check return code of example in "make test" and display result
+- pass minigzip command line options to file_compress
+- simplifying code of inflateSync to avoid gcc 2.8 bug
+
+- support CC="gcc -Wall" in configure -s (QingLong)
+- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
+- fix test for shared library support to avoid compiler warnings
+- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
+- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
+- do not use fdopen for Metrowerks on Mac (Brad Pettit))
+- add checks for gzputc and gzputc in example.c
+- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
+- use const for the CRC table (Ken Raeburn)
+- fixed "make uninstall" for shared libraries
+- use Tracev instead of Trace in infblock.c
+- in example.c use correct compressed length for test_sync
+- suppress +vnocompatwarnings in configure for HPUX (not always supported)
+
+Changes in 1.0.7 (20 Jan 1998)
+- fix gzseek which was broken in write mode
+- return error for gzseek to negative absolute position
+- fix configure for Linux (Chun-Chung Chen)
+- increase stack space for MSC (Tim Wegner)
+- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
+- define EXPORTVA for gzprintf (Gilles Vollant)
+- added man page zlib.3 (Rick Rodgers)
+- for contrib/untgz, fix makedir() and improve Makefile
+
+- check gzseek in write mode in example.c
+- allocate extra buffer for seeks only if gzseek is actually called
+- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
+- add inflateSyncPoint in zconf.h
+- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
+
+Changes in 1.0.6 (19 Jan 1998)
+- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
+ gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
+- Fix a deflate bug occurring only with compression level 0 (thanks to
+ Andy Buckler for finding this one)
+- In minigzip, pass transparently also the first byte for .Z files
+- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
+- check Z_FINISH in inflate (thanks to Marc Schluper)
+- Implement deflateCopy (thanks to Adam Costello)
+- make static libraries by default in configure, add --shared option
+- move MSDOS or Windows specific files to directory msdos
+- suppress the notion of partial flush to simplify the interface
+ (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
+- suppress history buffer provided by application to simplify the interface
+ (this feature was not implemented anyway in 1.0.4)
+- next_in and avail_in must be initialized before calling inflateInit or
+ inflateInit2
+- add EXPORT in all exported functions (for Windows DLL)
+- added Makefile.nt (thanks to Stephen Williams)
+- added the unsupported "contrib" directory:
+ contrib/asm386/ by Gilles Vollant
+ 386 asm code replacing longest_match()
+ contrib/iostream/ by Kevin Ruland
+ A C++ I/O streams interface to the zlib gz* functions
+ contrib/iostream2/ by Tyge Løvset
+ Another C++ I/O streams interface
+ contrib/untgz/ by "Pedro A. Aranda Guti\irrez"
+ A very simple tar.gz file extractor using zlib
+ contrib/visual-basic.txt by Carlos Rios
+ How to use compress(), uncompress() and the gz* functions from VB
+- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
+ level) in minigzip (thanks to Tom Lane)
+
+- use const for rommable constants in deflate
+- added test for gzseek and gztell in example.c
+- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
+- add undocumented function zError to convert error code to string
+ (for Tim Smithers)
+- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code
+- Use default memcpy for Symantec MSDOS compiler
+- Add EXPORT keyword for check_func (needed for Windows DLL)
+- add current directory to LD_LIBRARY_PATH for "make test"
+- create also a link for libz.so.1
+- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
+- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
+- added -soname for Linux in configure (Chun-Chung Chen,
+- assign numbers to the exported functions in zlib.def (for Windows DLL)
+- add advice in zlib.h for best usage of deflateSetDictionary
+- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
+- allow compilation with ANSI keywords only enabled for TurboC in large model
+- avoid "versionString"[0] (Borland bug)
+- add NEED_DUMMY_RETURN for Borland
+- use variable z_verbose for tracing in debug mode (L. Peter Deutsch)
+- allow compilation with CC
+- defined STDC for OS/2 (David Charlap)
+- limit external names to 8 chars for MVS (Thomas Lund)
+- in minigzip.c, use static buffers only for 16-bit systems
+- fix suffix check for "minigzip -d foo.gz"
+- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
+- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
+- added makelcc.bat for lcc-win32 (Tom St Denis)
+- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
+- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion
+- check for unistd.h in configure (for off_t)
+- remove useless check parameter in inflate_blocks_free
+- avoid useless assignment of s->check to itself in inflate_blocks_new
+- do not flush twice in gzclose (thanks to Ken Raeburn)
+- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
+- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
+- work around buggy fclose on pipes for HP/UX
+- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
+- fix configure if CC is already equal to gcc
+
+Changes in 1.0.5 (3 Jan 98)
+- Fix inflate to terminate gracefully when fed corrupted or invalid data
+- Use const for rommable constants in inflate
+- Eliminate memory leaks on error conditions in inflate
+- Removed some vestigial code in inflate
+- Update web address in README
+
+Changes in 1.0.4 (24 Jul 96)
+- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
+ bit, so the decompressor could decompress all the correct data but went
+ on to attempt decompressing extra garbage data. This affected minigzip too
+- zlibVersion and gzerror return const char* (needed for DLL)
+- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
+- use z_error only for DEBUG (avoid problem with DLLs)
+
+Changes in 1.0.3 (2 Jul 96)
+- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
+ small and medium models; this makes the library incompatible with previous
+ versions for these models. (No effect in large model or on other systems.)
+- return OK instead of BUF_ERROR if previous deflate call returned with
+ avail_out as zero but there is nothing to do
+- added memcmp for non STDC compilers
+- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
+- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
+- better check for 16-bit mode MSC (avoids problem with Symantec)
+
+Changes in 1.0.2 (23 May 96)
+- added Windows DLL support
+- added a function zlibVersion (for the DLL support)
+- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
+- Bytef is define's instead of typedef'd only for Borland C
+- avoid reading uninitialized memory in example.c
+- mention in README that the zlib format is now RFC1950
+- updated Makefile.dj2
+- added algorithm.doc
+
+Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
+- fix array overlay in deflate.c which sometimes caused bad compressed data
+- fix inflate bug with empty stored block
+- fix MSDOS medium model which was broken in 0.99
+- fix deflateParams() which could generate bad compressed data
+- Bytef is define'd instead of typedef'ed (work around Borland bug)
+- added an INDEX file
+- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
+ Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
+- speed up adler32 for modern machines without auto-increment
+- added -ansi for IRIX in configure
+- static_init_done in trees.c is an int
+- define unlink as delete for VMS
+- fix configure for QNX
+- add configure branch for SCO and HPUX
+- avoid many warnings (unused variables, dead assignments, etc...)
+- no fdopen for BeOS
+- fix the Watcom fix for 32 bit mode (define FAR as empty)
+- removed redefinition of Byte for MKWERKS
+- work around an MWKERKS bug (incorrect merge of all .h files)
+
+Changes in 0.99 (27 Jan 96)
+- allow preset dictionary shared between compressor and decompressor
+- allow compression level 0 (no compression)
+- add deflateParams in zlib.h: allow dynamic change of compression level
+ and compression strategy
+- test large buffers and deflateParams in example.c
+- add optional "configure" to build zlib as a shared library
+- suppress Makefile.qnx, use configure instead
+- fixed deflate for 64-bit systems (detected on Cray)
+- fixed inflate_blocks for 64-bit systems (detected on Alpha)
+- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
+- always return Z_BUF_ERROR when deflate() has nothing to do
+- deflateInit and inflateInit are now macros to allow version checking
+- prefix all global functions and types with z_ with -DZ_PREFIX
+- make falloc completely reentrant (inftrees.c)
+- fixed very unlikely race condition in ct_static_init
+- free in reverse order of allocation to help memory manager
+- use zlib-1.0/* instead of zlib/* inside the tar.gz
+- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
+ -Wconversion -Wstrict-prototypes -Wmissing-prototypes"
+- allow gzread on concatenated .gz files
+- deflateEnd now returns Z_DATA_ERROR if it was premature
+- deflate is finally (?) fully deterministic (no matches beyond end of input)
+- Document Z_SYNC_FLUSH
+- add uninstall in Makefile
+- Check for __cpluplus in zlib.h
+- Better test in ct_align for partial flush
+- avoid harmless warnings for Borland C++
+- initialize hash_head in deflate.c
+- avoid warning on fdopen (gzio.c) for HP cc -Aa
+- include stdlib.h for STDC compilers
+- include errno.h for Cray
+- ignore error if ranlib doesn't exist
+- call ranlib twice for NeXTSTEP
+- use exec_prefix instead of prefix for libz.a
+- renamed ct_* as _tr_* to avoid conflict with applications
+- clear z->msg in inflateInit2 before any error return
+- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
+- fixed typo in zconf.h (_GNUC__ => __GNUC__)
+- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
+- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
+- in fcalloc, normalize pointer if size > 65520 bytes
+- don't use special fcalloc for 32 bit Borland C++
+- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
+- use Z_BINARY instead of BINARY
+- document that gzclose after gzdopen will close the file
+- allow "a" as mode in gzopen
+- fix error checking in gzread
+- allow skipping .gz extra-field on pipes
+- added reference to Perl interface in README
+- put the crc table in FAR data (I dislike more and more the medium model :)
+- added get_crc_table
+- added a dimension to all arrays (Borland C can't count)
+- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
+- guard against multiple inclusion of *.h (for precompiled header on Mac)
+- Watcom C pretends to be Microsoft C small model even in 32 bit mode
+- don't use unsized arrays to avoid silly warnings by Visual C++:
+ warning C4746: 'inflate_mask' : unsized array treated as '__far'
+ (what's wrong with far data in far model?)
+- define enum out of inflate_blocks_state to allow compilation with C++
+
+Changes in 0.95 (16 Aug 95)
+- fix MSDOS small and medium model (now easier to adapt to any compiler)
+- inlined send_bits
+- fix the final (:-) bug for deflate with flush (output was correct but
+ not completely flushed in rare occasions)
+- default window size is same for compression and decompression
+ (it's now sufficient to set MAX_WBITS in zconf.h)
+- voidp -> voidpf and voidnp -> voidp (for consistency with other
+ typedefs and because voidnp was not near in large model)
+
+Changes in 0.94 (13 Aug 95)
+- support MSDOS medium model
+- fix deflate with flush (could sometimes generate bad output)
+- fix deflateReset (zlib header was incorrectly suppressed)
+- added support for VMS
+- allow a compression level in gzopen()
+- gzflush now calls fflush
+- For deflate with flush, flush even if no more input is provided
+- rename libgz.a as libz.a
+- avoid complex expression in infcodes.c triggering Turbo C bug
+- work around a problem with gcc on Alpha (in INSERT_STRING)
+- don't use inline functions (problem with some gcc versions)
+- allow renaming of Byte, uInt, etc... with #define
+- avoid warning about (unused) pointer before start of array in deflate.c
+- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
+- avoid reserved word 'new' in trees.c
+
+Changes in 0.93 (25 June 95)
+- temporarily disable inline functions
+- make deflate deterministic
+- give enough lookahead for PARTIAL_FLUSH
+- Set binary mode for stdin/stdout in minigzip.c for OS/2
+- don't even use signed char in inflate (not portable enough)
+- fix inflate memory leak for segmented architectures
+
+Changes in 0.92 (3 May 95)
+- don't assume that char is signed (problem on SGI)
+- Clear bit buffer when starting a stored block
+- no memcpy on Pyramid
+- suppressed inftest.c
+- optimized fill_window, put longest_match inline for gcc
+- optimized inflate on stored blocks
+- untabify all sources to simplify patches
+
+Changes in 0.91 (2 May 95)
+- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
+- Document the memory requirements in zconf.h
+- added "make install"
+- fix sync search logic in inflateSync
+- deflate(Z_FULL_FLUSH) now works even if output buffer too short
+- after inflateSync, don't scare people with just "lo world"
+- added support for DJGPP
+
+Changes in 0.9 (1 May 95)
+- don't assume that zalloc clears the allocated memory (the TurboC bug
+ was Mark's bug after all :)
+- let again gzread copy uncompressed data unchanged (was working in 0.71)
+- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
+- added a test of inflateSync in example.c
+- moved MAX_WBITS to zconf.h because users might want to change that
+- document explicitly that zalloc(64K) on MSDOS must return a normalized
+ pointer (zero offset)
+- added Makefiles for Microsoft C, Turbo C, Borland C++
+- faster crc32()
+
+Changes in 0.8 (29 April 95)
+- added fast inflate (inffast.c)
+- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
+ is incompatible with previous versions of zlib which returned Z_OK
+- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
+ (actually that was not a compiler bug, see 0.81 above)
+- gzread no longer reads one extra byte in certain cases
+- In gzio destroy(), don't reference a freed structure
+- avoid many warnings for MSDOS
+- avoid the ERROR symbol which is used by MS Windows
+
+Changes in 0.71 (14 April 95)
+- Fixed more MSDOS compilation problems :( There is still a bug with
+ TurboC large model
+
+Changes in 0.7 (14 April 95)
+- Added full inflate support
+- Simplified the crc32() interface. The pre- and post-conditioning
+ (one's complement) is now done inside crc32(). WARNING: this is
+ incompatible with previous versions; see zlib.h for the new usage
+
+Changes in 0.61 (12 April 95)
+- workaround for a bug in TurboC. example and minigzip now work on MSDOS
+
+Changes in 0.6 (11 April 95)
+- added minigzip.c
+- added gzdopen to reopen a file descriptor as gzFile
+- added transparent reading of non-gziped files in gzread
+- fixed bug in gzread (don't read crc as data)
+- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose)
+- don't allocate big arrays in the stack (for MSDOS)
+- fix some MSDOS compilation problems
+
+Changes in 0.5:
+- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
+ not yet Z_FULL_FLUSH
+- support decompression but only in a single step (forced Z_FINISH)
+- added opaque object for zalloc and zfree
+- added deflateReset and inflateReset
+- added a variable zlib_version for consistency checking
+- renamed the 'filter' parameter of deflateInit2 as 'strategy'
+ Added Z_FILTERED and Z_HUFFMAN_ONLY constants
+
+Changes in 0.4:
+- avoid "zip" everywhere, use zlib instead of ziplib
+- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
+ if compression method == 8
+- added adler32 and crc32
+- renamed deflateOptions as deflateInit2, call one or the other but not both
+- added the method parameter for deflateInit2
+- added inflateInit2
+- simplified considerably deflateInit and inflateInit by not supporting
+ user-provided history buffer. This is supported only in deflateInit2
+ and inflateInit2
+
+Changes in 0.3:
+- prefix all macro names with Z_
+- use Z_FINISH instead of deflateEnd to finish compression
+- added Z_HUFFMAN_ONLY
+- added gzerror()
ADDED compat/zlib/FAQ
Index: compat/zlib/FAQ
==================================================================
--- compat/zlib/FAQ
+++ compat/zlib/FAQ
@@ -0,0 +1,368 @@
+
+ Frequently Asked Questions about zlib
+
+
+If your question is not there, please check the zlib home page
+http://zlib.net/ which may have more recent information.
+The lastest zlib FAQ is at http://zlib.net/zlib_faq.html
+
+
+ 1. Is zlib Y2K-compliant?
+
+ Yes. zlib doesn't handle dates.
+
+ 2. Where can I get a Windows DLL version?
+
+ The zlib sources can be compiled without change to produce a DLL. See the
+ file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the
+ precompiled DLL are found in the zlib web site at http://zlib.net/ .
+
+ 3. Where can I get a Visual Basic interface to zlib?
+
+ See
+ * http://marknelson.us/1997/01/01/zlib-engine/
+ * win32/DLL_FAQ.txt in the zlib distribution
+
+ 4. compress() returns Z_BUF_ERROR.
+
+ Make sure that before the call of compress(), the length of the compressed
+ buffer is equal to the available size of the compressed buffer and not
+ zero. For Visual Basic, check that this parameter is passed by reference
+ ("as any"), not by value ("as long").
+
+ 5. deflate() or inflate() returns Z_BUF_ERROR.
+
+ Before making the call, make sure that avail_in and avail_out are not zero.
+ When setting the parameter flush equal to Z_FINISH, also make sure that
+ avail_out is big enough to allow processing all pending input. Note that a
+ Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be
+ made with more input or output space. A Z_BUF_ERROR may in fact be
+ unavoidable depending on how the functions are used, since it is not
+ possible to tell whether or not there is more output pending when
+ strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a
+ heavily annotated example.
+
+ 6. Where's the zlib documentation (man pages, etc.)?
+
+ It's in zlib.h . Examples of zlib usage are in the files test/example.c
+ and test/minigzip.c, with more in examples/ .
+
+ 7. Why don't you use GNU autoconf or libtool or ...?
+
+ Because we would like to keep zlib as a very small and simple package.
+ zlib is rather portable and doesn't need much configuration.
+
+ 8. I found a bug in zlib.
+
+ Most of the time, such problems are due to an incorrect usage of zlib.
+ Please try to reproduce the problem with a small program and send the
+ corresponding source to us at zlib@gzip.org . Do not send multi-megabyte
+ data files without prior agreement.
+
+ 9. Why do I get "undefined reference to gzputc"?
+
+ If "make test" produces something like
+
+ example.o(.text+0x154): undefined reference to `gzputc'
+
+ check that you don't have old files libz.* in /usr/lib, /usr/local/lib or
+ /usr/X11R6/lib. Remove any old versions, then do "make install".
+
+10. I need a Delphi interface to zlib.
+
+ See the contrib/delphi directory in the zlib distribution.
+
+11. Can zlib handle .zip archives?
+
+ Not by itself, no. See the directory contrib/minizip in the zlib
+ distribution.
+
+12. Can zlib handle .Z files?
+
+ No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt
+ the code of uncompress on your own.
+
+13. How can I make a Unix shared library?
+
+ By default a shared (and a static) library is built for Unix. So:
+
+ make distclean
+ ./configure
+ make
+
+14. How do I install a shared zlib library on Unix?
+
+ After the above, then:
+
+ make install
+
+ However, many flavors of Unix come with a shared zlib already installed.
+ Before going to the trouble of compiling a shared version of zlib and
+ trying to install it, you may want to check if it's already there! If you
+ can #include , it's there. The -lz option will probably link to
+ it. You can check the version at the top of zlib.h or with the
+ ZLIB_VERSION symbol defined in zlib.h .
+
+15. I have a question about OttoPDF.
+
+ We are not the authors of OttoPDF. The real author is on the OttoPDF web
+ site: Joel Hainley, jhainley@myndkryme.com.
+
+16. Can zlib decode Flate data in an Adobe PDF file?
+
+ Yes. See http://www.pdflib.com/ . To modify PDF forms, see
+ http://sourceforge.net/projects/acroformtool/ .
+
+17. Why am I getting this "register_frame_info not found" error on Solaris?
+
+ After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
+ generates an error such as:
+
+ ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
+ symbol __register_frame_info: referenced symbol not found
+
+ The symbol __register_frame_info is not part of zlib, it is generated by
+ the C compiler (cc or gcc). You must recompile applications using zlib
+ which have this problem. This problem is specific to Solaris. See
+ http://www.sunfreeware.com for Solaris versions of zlib and applications
+ using zlib.
+
+18. Why does gzip give an error on a file I make with compress/deflate?
+
+ The compress and deflate functions produce data in the zlib format, which
+ is different and incompatible with the gzip format. The gz* functions in
+ zlib on the other hand use the gzip format. Both the zlib and gzip formats
+ use the same compressed data format internally, but have different headers
+ and trailers around the compressed data.
+
+19. Ok, so why are there two different formats?
+
+ The gzip format was designed to retain the directory information about a
+ single file, such as the name and last modification date. The zlib format
+ on the other hand was designed for in-memory and communication channel
+ applications, and has a much more compact header and trailer and uses a
+ faster integrity check than gzip.
+
+20. Well that's nice, but how do I make a gzip file in memory?
+
+ You can request that deflate write the gzip format instead of the zlib
+ format using deflateInit2(). You can also request that inflate decode the
+ gzip format using inflateInit2(). Read zlib.h for more details.
+
+21. Is zlib thread-safe?
+
+ Yes. However any library routines that zlib uses and any application-
+ provided memory allocation routines must also be thread-safe. zlib's gz*
+ functions use stdio library routines, and most of zlib's functions use the
+ library memory allocation routines by default. zlib's *Init* functions
+ allow for the application to provide custom memory allocation routines.
+
+ Of course, you should only operate on any given zlib or gzip stream from a
+ single thread at a time.
+
+22. Can I use zlib in my commercial application?
+
+ Yes. Please read the license in zlib.h.
+
+23. Is zlib under the GNU license?
+
+ No. Please read the license in zlib.h.
+
+24. The license says that altered source versions must be "plainly marked". So
+ what exactly do I need to do to meet that requirement?
+
+ You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In
+ particular, the final version number needs to be changed to "f", and an
+ identification string should be appended to ZLIB_VERSION. Version numbers
+ x.x.x.f are reserved for modifications to zlib by others than the zlib
+ maintainers. For example, if the version of the base zlib you are altering
+ is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
+ ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also
+ update the version strings in deflate.c and inftrees.c.
+
+ For altered source distributions, you should also note the origin and
+ nature of the changes in zlib.h, as well as in ChangeLog and README, along
+ with the dates of the alterations. The origin should include at least your
+ name (or your company's name), and an email address to contact for help or
+ issues with the library.
+
+ Note that distributing a compiled zlib library along with zlib.h and
+ zconf.h is also a source distribution, and so you should change
+ ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
+ in zlib.h as you would for a full source distribution.
+
+25. Will zlib work on a big-endian or little-endian architecture, and can I
+ exchange compressed data between them?
+
+ Yes and yes.
+
+26. Will zlib work on a 64-bit machine?
+
+ Yes. It has been tested on 64-bit machines, and has no dependence on any
+ data types being limited to 32-bits in length. If you have any
+ difficulties, please provide a complete problem report to zlib@gzip.org
+
+27. Will zlib decompress data from the PKWare Data Compression Library?
+
+ No. The PKWare DCL uses a completely different compressed data format than
+ does PKZIP and zlib. However, you can look in zlib's contrib/blast
+ directory for a possible solution to your problem.
+
+28. Can I access data randomly in a compressed stream?
+
+ No, not without some preparation. If when compressing you periodically use
+ Z_FULL_FLUSH, carefully write all the pending data at those points, and
+ keep an index of those locations, then you can start decompression at those
+ points. You have to be careful to not use Z_FULL_FLUSH too often, since it
+ can significantly degrade compression. Alternatively, you can scan a
+ deflate stream once to generate an index, and then use that index for
+ random access. See examples/zran.c .
+
+29. Does zlib work on MVS, OS/390, CICS, etc.?
+
+ It has in the past, but we have not heard of any recent evidence. There
+ were working ports of zlib 1.1.4 to MVS, but those links no longer work.
+ If you know of recent, successful applications of zlib on these operating
+ systems, please let us know. Thanks.
+
+30. Is there some simpler, easier to read version of inflate I can look at to
+ understand the deflate format?
+
+ First off, you should read RFC 1951. Second, yes. Look in zlib's
+ contrib/puff directory.
+
+31. Does zlib infringe on any patents?
+
+ As far as we know, no. In fact, that was originally the whole point behind
+ zlib. Look here for some more information:
+
+ http://www.gzip.org/#faq11
+
+32. Can zlib work with greater than 4 GB of data?
+
+ Yes. inflate() and deflate() will process any amount of data correctly.
+ Each call of inflate() or deflate() is limited to input and output chunks
+ of the maximum value that can be stored in the compiler's "unsigned int"
+ type, but there is no limit to the number of chunks. Note however that the
+ strm.total_in and strm_total_out counters may be limited to 4 GB. These
+ counters are provided as a convenience and are not used internally by
+ inflate() or deflate(). The application can easily set up its own counters
+ updated after each call of inflate() or deflate() to count beyond 4 GB.
+ compress() and uncompress() may be limited to 4 GB, since they operate in a
+ single call. gzseek() and gztell() may be limited to 4 GB depending on how
+ zlib is compiled. See the zlibCompileFlags() function in zlib.h.
+
+ The word "may" appears several times above since there is a 4 GB limit only
+ if the compiler's "long" type is 32 bits. If the compiler's "long" type is
+ 64 bits, then the limit is 16 exabytes.
+
+33. Does zlib have any security vulnerabilities?
+
+ The only one that we are aware of is potentially in gzprintf(). If zlib is
+ compiled to use sprintf() or vsprintf(), then there is no protection
+ against a buffer overflow of an 8K string space (or other value as set by
+ gzbuffer()), other than the caller of gzprintf() assuring that the output
+ will not exceed 8K. On the other hand, if zlib is compiled to use
+ snprintf() or vsnprintf(), which should normally be the case, then there is
+ no vulnerability. The ./configure script will display warnings if an
+ insecure variation of sprintf() will be used by gzprintf(). Also the
+ zlibCompileFlags() function will return information on what variant of
+ sprintf() is used by gzprintf().
+
+ If you don't have snprintf() or vsnprintf() and would like one, you can
+ find a portable implementation here:
+
+ http://www.ijs.si/software/snprintf/
+
+ Note that you should be using the most recent version of zlib. Versions
+ 1.1.3 and before were subject to a double-free vulnerability, and versions
+ 1.2.1 and 1.2.2 were subject to an access exception when decompressing
+ invalid compressed data.
+
+34. Is there a Java version of zlib?
+
+ Probably what you want is to use zlib in Java. zlib is already included
+ as part of the Java SDK in the java.util.zip package. If you really want
+ a version of zlib written in the Java language, look on the zlib home
+ page for links: http://zlib.net/ .
+
+35. I get this or that compiler or source-code scanner warning when I crank it
+ up to maximally-pedantic. Can't you guys write proper code?
+
+ Many years ago, we gave up attempting to avoid warnings on every compiler
+ in the universe. It just got to be a waste of time, and some compilers
+ were downright silly as well as contradicted each other. So now, we simply
+ make sure that the code always works.
+
+36. Valgrind (or some similar memory access checker) says that deflate is
+ performing a conditional jump that depends on an uninitialized value.
+ Isn't that a bug?
+
+ No. That is intentional for performance reasons, and the output of deflate
+ is not affected. This only started showing up recently since zlib 1.2.x
+ uses malloc() by default for allocations, whereas earlier versions used
+ calloc(), which zeros out the allocated memory. Even though the code was
+ correct, versions 1.2.4 and later was changed to not stimulate these
+ checkers.
+
+37. Will zlib read the (insert any ancient or arcane format here) compressed
+ data format?
+
+ Probably not. Look in the comp.compression FAQ for pointers to various
+ formats and associated software.
+
+38. How can I encrypt/decrypt zip files with zlib?
+
+ zlib doesn't support encryption. The original PKZIP encryption is very
+ weak and can be broken with freely available programs. To get strong
+ encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib
+ compression. For PKZIP compatible "encryption", look at
+ http://www.info-zip.org/
+
+39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
+
+ "gzip" is the gzip format, and "deflate" is the zlib format. They should
+ probably have called the second one "zlib" instead to avoid confusion with
+ the raw deflate compressed data format. While the HTTP 1.1 RFC 2616
+ correctly points to the zlib specification in RFC 1950 for the "deflate"
+ transfer encoding, there have been reports of servers and browsers that
+ incorrectly produce or expect raw deflate data per the deflate
+ specification in RFC 1951, most notably Microsoft. So even though the
+ "deflate" transfer encoding using the zlib format would be the more
+ efficient approach (and in fact exactly what the zlib format was designed
+ for), using the "gzip" transfer encoding is probably more reliable due to
+ an unfortunate choice of name on the part of the HTTP 1.1 authors.
+
+ Bottom line: use the gzip format for HTTP 1.1 encoding.
+
+40. Does zlib support the new "Deflate64" format introduced by PKWare?
+
+ No. PKWare has apparently decided to keep that format proprietary, since
+ they have not documented it as they have previous compression formats. In
+ any case, the compression improvements are so modest compared to other more
+ modern approaches, that it's not worth the effort to implement.
+
+41. I'm having a problem with the zip functions in zlib, can you help?
+
+ There are no zip functions in zlib. You are probably using minizip by
+ Giles Vollant, which is found in the contrib directory of zlib. It is not
+ part of zlib. In fact none of the stuff in contrib is part of zlib. The
+ files in there are not supported by the zlib authors. You need to contact
+ the authors of the respective contribution for help.
+
+42. The match.asm code in contrib is under the GNU General Public License.
+ Since it's part of zlib, doesn't that mean that all of zlib falls under the
+ GNU GPL?
+
+ No. The files in contrib are not part of zlib. They were contributed by
+ other authors and are provided as a convenience to the user within the zlib
+ distribution. Each item in contrib has its own license.
+
+43. Is zlib subject to export controls? What is its ECCN?
+
+ zlib is not subject to export controls, and so is classified as EAR99.
+
+44. Can you please sign these lengthy legal documents and fax them back to us
+ so that we can use your software in our product?
+
+ No. Go away. Shoo.
ADDED compat/zlib/INDEX
Index: compat/zlib/INDEX
==================================================================
--- compat/zlib/INDEX
+++ compat/zlib/INDEX
@@ -0,0 +1,68 @@
+CMakeLists.txt cmake build file
+ChangeLog history of changes
+FAQ Frequently Asked Questions about zlib
+INDEX this file
+Makefile dummy Makefile that tells you to ./configure
+Makefile.in template for Unix Makefile
+README guess what
+configure configure script for Unix
+make_vms.com makefile for VMS
+test/example.c zlib usages examples for build testing
+test/minigzip.c minimal gzip-like functionality for build testing
+test/infcover.c inf*.c code coverage for build coverage testing
+treebuild.xml XML description of source file dependencies
+zconf.h.cmakein zconf.h template for cmake
+zconf.h.in zconf.h template for configure
+zlib.3 Man page for zlib
+zlib.3.pdf Man page in PDF format
+zlib.map Linux symbol information
+zlib.pc.in Template for pkg-config descriptor
+zlib.pc.cmakein zlib.pc template for cmake
+zlib2ansi perl script to convert source files for C++ compilation
+
+amiga/ makefiles for Amiga SAS C
+as400/ makefiles for AS/400
+doc/ documentation for formats and algorithms
+msdos/ makefiles for MSDOS
+nintendods/ makefile for Nintendo DS
+old/ makefiles for various architectures and zlib documentation
+ files that have not yet been updated for zlib 1.2.x
+qnx/ makefiles for QNX
+watcom/ makefiles for OpenWatcom
+win32/ makefiles for Windows
+
+ zlib public header files (required for library use):
+zconf.h
+zlib.h
+
+ private source files used to build the zlib library:
+adler32.c
+compress.c
+crc32.c
+crc32.h
+deflate.c
+deflate.h
+gzclose.c
+gzguts.h
+gzlib.c
+gzread.c
+gzwrite.c
+infback.c
+inffast.c
+inffast.h
+inffixed.h
+inflate.c
+inflate.h
+inftrees.c
+inftrees.h
+trees.c
+trees.h
+uncompr.c
+zutil.c
+zutil.h
+
+ source files for sample programs
+See examples/README.examples
+
+ unsupported contributions by third parties
+See contrib/README.contrib
ADDED compat/zlib/LICENSE
Index: compat/zlib/LICENSE
==================================================================
--- compat/zlib/LICENSE
+++ compat/zlib/LICENSE
@@ -0,0 +1,22 @@
+Copyright notice:
+
+ (C) 1995-2022 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
ADDED compat/zlib/Makefile
Index: compat/zlib/Makefile
==================================================================
--- compat/zlib/Makefile
+++ compat/zlib/Makefile
@@ -0,0 +1,5 @@
+all:
+ -@echo "Please use ./configure first. Thank you."
+
+distclean:
+ make -f Makefile.in distclean
ADDED compat/zlib/Makefile.in
Index: compat/zlib/Makefile.in
==================================================================
--- compat/zlib/Makefile.in
+++ compat/zlib/Makefile.in
@@ -0,0 +1,404 @@
+# Makefile for zlib
+# Copyright (C) 1995-2017 Jean-loup Gailly, Mark Adler
+# For conditions of distribution and use, see copyright notice in zlib.h
+
+# To compile and test, type:
+# ./configure; make test
+# Normally configure builds both a static and a shared library.
+# If you want to build just a static library, use: ./configure --static
+
+# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
+# make install
+# To install in $HOME instead of /usr/local, use:
+# make install prefix=$HOME
+
+CC=cc
+
+CFLAGS=-O
+#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
+#CFLAGS=-g -DZLIB_DEBUG
+#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
+# -Wstrict-prototypes -Wmissing-prototypes
+
+SFLAGS=-O
+LDFLAGS=
+TEST_LDFLAGS=$(LDFLAGS) -L. libz.a
+LDSHARED=$(CC)
+CPP=$(CC) -E
+
+STATICLIB=libz.a
+SHAREDLIB=libz.so
+SHAREDLIBV=libz.so.1.2.13
+SHAREDLIBM=libz.so.1
+LIBS=$(STATICLIB) $(SHAREDLIBV)
+
+AR=ar
+ARFLAGS=rc
+RANLIB=ranlib
+LDCONFIG=ldconfig
+LDSHAREDLIBC=-lc
+TAR=tar
+SHELL=/bin/sh
+EXE=
+
+prefix = /usr/local
+exec_prefix = ${prefix}
+libdir = ${exec_prefix}/lib
+sharedlibdir = ${libdir}
+includedir = ${prefix}/include
+mandir = ${prefix}/share/man
+man3dir = ${mandir}/man3
+pkgconfigdir = ${libdir}/pkgconfig
+SRCDIR=
+ZINC=
+ZINCOUT=-I.
+
+OBJZ = adler32.o crc32.o deflate.o infback.o inffast.o inflate.o inftrees.o trees.o zutil.o
+OBJG = compress.o uncompr.o gzclose.o gzlib.o gzread.o gzwrite.o
+OBJC = $(OBJZ) $(OBJG)
+
+PIC_OBJZ = adler32.lo crc32.lo deflate.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo zutil.lo
+PIC_OBJG = compress.lo uncompr.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo
+PIC_OBJC = $(PIC_OBJZ) $(PIC_OBJG)
+
+# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo
+OBJA =
+PIC_OBJA =
+
+OBJS = $(OBJC) $(OBJA)
+
+PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA)
+
+all: static shared
+
+static: example$(EXE) minigzip$(EXE)
+
+shared: examplesh$(EXE) minigzipsh$(EXE)
+
+all64: example64$(EXE) minigzip64$(EXE)
+
+check: test
+
+test: all teststatic testshared
+
+teststatic: static
+ @TMPST=tmpst_$$; \
+ if echo hello world | ${QEMU_RUN} ./minigzip | ${QEMU_RUN} ./minigzip -d && ${QEMU_RUN} ./example $$TMPST ; then \
+ echo ' *** zlib test OK ***'; \
+ else \
+ echo ' *** zlib test FAILED ***'; false; \
+ fi
+ @rm -f tmpst_$$
+
+testshared: shared
+ @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
+ LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \
+ DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \
+ SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \
+ TMPSH=tmpsh_$$; \
+ if echo hello world | ${QEMU_RUN} ./minigzipsh | ${QEMU_RUN} ./minigzipsh -d && ${QEMU_RUN} ./examplesh $$TMPSH; then \
+ echo ' *** zlib shared test OK ***'; \
+ else \
+ echo ' *** zlib shared test FAILED ***'; false; \
+ fi
+ @rm -f tmpsh_$$
+
+test64: all64
+ @TMP64=tmp64_$$; \
+ if echo hello world | ${QEMU_RUN} ./minigzip64 | ${QEMU_RUN} ./minigzip64 -d && ${QEMU_RUN} ./example64 $$TMP64; then \
+ echo ' *** zlib 64-bit test OK ***'; \
+ else \
+ echo ' *** zlib 64-bit test FAILED ***'; false; \
+ fi
+ @rm -f tmp64_$$
+
+infcover.o: $(SRCDIR)test/infcover.c $(SRCDIR)zlib.h zconf.h
+ $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/infcover.c
+
+infcover: infcover.o libz.a
+ $(CC) $(CFLAGS) -o $@ infcover.o libz.a
+
+cover: infcover
+ rm -f *.gcda
+ ${QEMU_RUN} ./infcover
+ gcov inf*.c
+
+libz.a: $(OBJS)
+ $(AR) $(ARFLAGS) $@ $(OBJS)
+ -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
+
+match.o: match.S
+ $(CPP) match.S > _match.s
+ $(CC) -c _match.s
+ mv _match.o match.o
+ rm -f _match.s
+
+match.lo: match.S
+ $(CPP) match.S > _match.s
+ $(CC) -c -fPIC _match.s
+ mv _match.o match.lo
+ rm -f _match.s
+
+example.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h
+ $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/example.c
+
+minigzip.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h
+ $(CC) $(CFLAGS) $(ZINCOUT) -c -o $@ $(SRCDIR)test/minigzip.c
+
+example64.o: $(SRCDIR)test/example.c $(SRCDIR)zlib.h zconf.h
+ $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/example.c
+
+minigzip64.o: $(SRCDIR)test/minigzip.c $(SRCDIR)zlib.h zconf.h
+ $(CC) $(CFLAGS) $(ZINCOUT) -D_FILE_OFFSET_BITS=64 -c -o $@ $(SRCDIR)test/minigzip.c
+
+
+adler32.o: $(SRCDIR)adler32.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)adler32.c
+
+crc32.o: $(SRCDIR)crc32.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)crc32.c
+
+deflate.o: $(SRCDIR)deflate.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)deflate.c
+
+infback.o: $(SRCDIR)infback.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)infback.c
+
+inffast.o: $(SRCDIR)inffast.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inffast.c
+
+inflate.o: $(SRCDIR)inflate.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inflate.c
+
+inftrees.o: $(SRCDIR)inftrees.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)inftrees.c
+
+trees.o: $(SRCDIR)trees.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)trees.c
+
+zutil.o: $(SRCDIR)zutil.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)zutil.c
+
+compress.o: $(SRCDIR)compress.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)compress.c
+
+uncompr.o: $(SRCDIR)uncompr.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)uncompr.c
+
+gzclose.o: $(SRCDIR)gzclose.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzclose.c
+
+gzlib.o: $(SRCDIR)gzlib.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzlib.c
+
+gzread.o: $(SRCDIR)gzread.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzread.c
+
+gzwrite.o: $(SRCDIR)gzwrite.c
+ $(CC) $(CFLAGS) $(ZINC) -c -o $@ $(SRCDIR)gzwrite.c
+
+
+adler32.lo: $(SRCDIR)adler32.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/adler32.o $(SRCDIR)adler32.c
+ -@mv objs/adler32.o $@
+
+crc32.lo: $(SRCDIR)crc32.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/crc32.o $(SRCDIR)crc32.c
+ -@mv objs/crc32.o $@
+
+deflate.lo: $(SRCDIR)deflate.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/deflate.o $(SRCDIR)deflate.c
+ -@mv objs/deflate.o $@
+
+infback.lo: $(SRCDIR)infback.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/infback.o $(SRCDIR)infback.c
+ -@mv objs/infback.o $@
+
+inffast.lo: $(SRCDIR)inffast.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/inffast.o $(SRCDIR)inffast.c
+ -@mv objs/inffast.o $@
+
+inflate.lo: $(SRCDIR)inflate.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/inflate.o $(SRCDIR)inflate.c
+ -@mv objs/inflate.o $@
+
+inftrees.lo: $(SRCDIR)inftrees.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/inftrees.o $(SRCDIR)inftrees.c
+ -@mv objs/inftrees.o $@
+
+trees.lo: $(SRCDIR)trees.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/trees.o $(SRCDIR)trees.c
+ -@mv objs/trees.o $@
+
+zutil.lo: $(SRCDIR)zutil.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/zutil.o $(SRCDIR)zutil.c
+ -@mv objs/zutil.o $@
+
+compress.lo: $(SRCDIR)compress.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/compress.o $(SRCDIR)compress.c
+ -@mv objs/compress.o $@
+
+uncompr.lo: $(SRCDIR)uncompr.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/uncompr.o $(SRCDIR)uncompr.c
+ -@mv objs/uncompr.o $@
+
+gzclose.lo: $(SRCDIR)gzclose.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/gzclose.o $(SRCDIR)gzclose.c
+ -@mv objs/gzclose.o $@
+
+gzlib.lo: $(SRCDIR)gzlib.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/gzlib.o $(SRCDIR)gzlib.c
+ -@mv objs/gzlib.o $@
+
+gzread.lo: $(SRCDIR)gzread.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/gzread.o $(SRCDIR)gzread.c
+ -@mv objs/gzread.o $@
+
+gzwrite.lo: $(SRCDIR)gzwrite.c
+ -@mkdir objs 2>/dev/null || test -d objs
+ $(CC) $(SFLAGS) $(ZINC) -fPIC -c -o objs/gzwrite.o $(SRCDIR)gzwrite.c
+ -@mv objs/gzwrite.o $@
+
+
+placebo $(SHAREDLIBV): $(PIC_OBJS) libz.a
+ $(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) $(LDSHAREDLIBC) $(LDFLAGS)
+ rm -f $(SHAREDLIB) $(SHAREDLIBM)
+ ln -s $@ $(SHAREDLIB)
+ ln -s $@ $(SHAREDLIBM)
+ -@rmdir objs
+
+example$(EXE): example.o $(STATICLIB)
+ $(CC) $(CFLAGS) -o $@ example.o $(TEST_LDFLAGS)
+
+minigzip$(EXE): minigzip.o $(STATICLIB)
+ $(CC) $(CFLAGS) -o $@ minigzip.o $(TEST_LDFLAGS)
+
+examplesh$(EXE): example.o $(SHAREDLIBV)
+ $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS) -L. $(SHAREDLIBV)
+
+minigzipsh$(EXE): minigzip.o $(SHAREDLIBV)
+ $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS) -L. $(SHAREDLIBV)
+
+example64$(EXE): example64.o $(STATICLIB)
+ $(CC) $(CFLAGS) -o $@ example64.o $(TEST_LDFLAGS)
+
+minigzip64$(EXE): minigzip64.o $(STATICLIB)
+ $(CC) $(CFLAGS) -o $@ minigzip64.o $(TEST_LDFLAGS)
+
+install-libs: $(LIBS)
+ -@if [ ! -d $(DESTDIR)$(exec_prefix) ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi
+ -@if [ ! -d $(DESTDIR)$(libdir) ]; then mkdir -p $(DESTDIR)$(libdir); fi
+ -@if [ ! -d $(DESTDIR)$(sharedlibdir) ]; then mkdir -p $(DESTDIR)$(sharedlibdir); fi
+ -@if [ ! -d $(DESTDIR)$(man3dir) ]; then mkdir -p $(DESTDIR)$(man3dir); fi
+ -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi
+ rm -f $(DESTDIR)$(libdir)/$(STATICLIB)
+ cp $(STATICLIB) $(DESTDIR)$(libdir)
+ chmod 644 $(DESTDIR)$(libdir)/$(STATICLIB)
+ -@($(RANLIB) $(DESTDIR)$(libdir)/libz.a || true) >/dev/null 2>&1
+ -@if test -n "$(SHAREDLIBV)"; then \
+ rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \
+ cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir); \
+ echo "cp $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)"; \
+ chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV); \
+ echo "chmod 755 $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBV)"; \
+ rm -f $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
+ ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIB); \
+ ln -s $(SHAREDLIBV) $(DESTDIR)$(sharedlibdir)/$(SHAREDLIBM); \
+ ($(LDCONFIG) || true) >/dev/null 2>&1; \
+ fi
+ rm -f $(DESTDIR)$(man3dir)/zlib.3
+ cp $(SRCDIR)zlib.3 $(DESTDIR)$(man3dir)
+ chmod 644 $(DESTDIR)$(man3dir)/zlib.3
+ rm -f $(DESTDIR)$(pkgconfigdir)/zlib.pc
+ cp zlib.pc $(DESTDIR)$(pkgconfigdir)
+ chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc
+# The ranlib in install is needed on NeXTSTEP which checks file times
+# ldconfig is for Linux
+
+install: install-libs
+ -@if [ ! -d $(DESTDIR)$(includedir) ]; then mkdir -p $(DESTDIR)$(includedir); fi
+ rm -f $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
+ cp $(SRCDIR)zlib.h zconf.h $(DESTDIR)$(includedir)
+ chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
+
+uninstall:
+ cd $(DESTDIR)$(includedir) && rm -f zlib.h zconf.h
+ cd $(DESTDIR)$(libdir) && rm -f libz.a; \
+ if test -n "$(SHAREDLIBV)" -a -f $(SHAREDLIBV); then \
+ rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
+ fi
+ cd $(DESTDIR)$(man3dir) && rm -f zlib.3
+ cd $(DESTDIR)$(pkgconfigdir) && rm -f zlib.pc
+
+docs: zlib.3.pdf
+
+zlib.3.pdf: $(SRCDIR)zlib.3
+ groff -mandoc -f H -T ps $(SRCDIR)zlib.3 | ps2pdf - $@
+
+zconf.h.cmakein: $(SRCDIR)zconf.h.in
+ -@ TEMPFILE=zconfh_$$; \
+ echo "/#define ZCONF_H/ a\\\\\n#cmakedefine Z_PREFIX\\\\\n#cmakedefine Z_HAVE_UNISTD_H\n" >> $$TEMPFILE &&\
+ sed -f $$TEMPFILE $(SRCDIR)zconf.h.in > $@ &&\
+ touch -r $(SRCDIR)zconf.h.in $@ &&\
+ rm $$TEMPFILE
+
+zconf: $(SRCDIR)zconf.h.in
+ cp -p $(SRCDIR)zconf.h.in zconf.h
+
+mostlyclean: clean
+clean:
+ rm -f *.o *.lo *~ \
+ example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \
+ example64$(EXE) minigzip64$(EXE) \
+ infcover \
+ libz.* foo.gz so_locations \
+ _match.s maketree contrib/infback9/*.o
+ rm -rf objs
+ rm -f *.gcda *.gcno *.gcov
+ rm -f contrib/infback9/*.gcda contrib/infback9/*.gcno contrib/infback9/*.gcov
+
+maintainer-clean: distclean
+distclean: clean zconf zconf.h.cmakein
+ rm -f Makefile zlib.pc configure.log
+ -@rm -f .DS_Store
+ @if [ -f Makefile.in ]; then \
+ printf 'all:\n\t-@echo "Please use ./configure first. Thank you."\n' > Makefile ; \
+ printf '\ndistclean:\n\tmake -f Makefile.in distclean\n' >> Makefile ; \
+ touch -r $(SRCDIR)Makefile.in Makefile ; fi
+
+tags:
+ etags $(SRCDIR)*.[ch]
+
+adler32.o zutil.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
+gzclose.o gzlib.o gzread.o gzwrite.o: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h
+compress.o example.o minigzip.o uncompr.o: $(SRCDIR)zlib.h zconf.h
+crc32.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h
+deflate.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
+infback.o inflate.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h
+inffast.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h
+inftrees.o: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h
+trees.o: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h
+
+adler32.lo zutil.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
+gzclose.lo gzlib.lo gzread.lo gzwrite.lo: $(SRCDIR)zlib.h zconf.h $(SRCDIR)gzguts.h
+compress.lo example.lo minigzip.lo uncompr.lo: $(SRCDIR)zlib.h zconf.h
+crc32.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)crc32.h
+deflate.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h
+infback.lo inflate.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h $(SRCDIR)inffixed.h
+inffast.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h $(SRCDIR)inflate.h $(SRCDIR)inffast.h
+inftrees.lo: $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)inftrees.h
+trees.lo: $(SRCDIR)deflate.h $(SRCDIR)zutil.h $(SRCDIR)zlib.h zconf.h $(SRCDIR)trees.h
ADDED compat/zlib/README
Index: compat/zlib/README
==================================================================
--- compat/zlib/README
+++ compat/zlib/README
@@ -0,0 +1,118 @@
+ZLIB DATA COMPRESSION LIBRARY
+
+zlib 1.2.13 is a general purpose data compression library. All the code is
+thread safe. The data format used by the zlib library is described by RFCs
+(Request for Comments) 1950 to 1952 in the files
+http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
+rfc1952 (gzip format).
+
+All functions of the compression library are documented in the file zlib.h
+(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example
+of the library is given in the file test/example.c which also tests that
+the library is working correctly. Another example is given in the file
+test/minigzip.c. The compression library itself is composed of all source
+files in the root directory.
+
+To compile all files and run the test program, follow the instructions given at
+the top of Makefile.in. In short "./configure; make test", and if that goes
+well, "make install" should work for most flavors of Unix. For Windows, use
+one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use
+make_vms.com.
+
+Questions about zlib should be sent to , or to Gilles Vollant
+ for the Windows DLL version. The zlib home page is
+http://zlib.net/ . Before reporting a problem, please check this site to
+verify that you have the latest version of zlib; otherwise get the latest
+version and check whether the problem still exists or not.
+
+PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
+
+Mark Nelson wrote an article about zlib for the Jan. 1997
+issue of Dr. Dobb's Journal; a copy of the article is available at
+http://marknelson.us/1997/01/01/zlib-engine/ .
+
+The changes made in version 1.2.13 are documented in the file ChangeLog.
+
+Unsupported third party contributions are provided in directory contrib/ .
+
+zlib is available in Java using the java.util.zip package, documented at
+http://java.sun.com/developer/technicalArticles/Programming/compression/ .
+
+A Perl interface to zlib written by Paul Marquess is available
+at CPAN (Comprehensive Perl Archive Network) sites, including
+http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
+
+A Python interface to zlib written by A.M. Kuchling is
+available in Python 1.5 and later versions, see
+http://docs.python.org/library/zlib.html .
+
+zlib is built into tcl: http://wiki.tcl.tk/4610 .
+
+An experimental package to read and write files in .zip format, written on top
+of zlib by Gilles Vollant , is available in the
+contrib/minizip directory of zlib.
+
+
+Notes for some targets:
+
+- For Windows DLL versions, please see win32/DLL_FAQ.txt
+
+- For 64-bit Irix, deflate.c must be compiled without any optimization. With
+ -O, one libpng test fails. The test works in 32 bit mode (with the -n32
+ compiler flag). The compiler bug has been reported to SGI.
+
+- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
+ when compiled with cc.
+
+- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
+ necessary to get gzprintf working correctly. This is done by configure.
+
+- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
+ other compilers. Use "make test" to check your compiler.
+
+- gzdopen is not supported on RISCOS or BEOS.
+
+- For PalmOs, see http://palmzlib.sourceforge.net/
+
+
+Acknowledgments:
+
+ The deflate format used by zlib was defined by Phil Katz. The deflate and
+ zlib specifications were written by L. Peter Deutsch. Thanks to all the
+ people who reported problems and suggested various improvements in zlib; they
+ are too numerous to cite here.
+
+Copyright notice:
+
+ (C) 1995-2022 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+
+If you use the zlib library in a product, we would appreciate *not* receiving
+lengthy legal documents to sign. The sources are provided for free but without
+warranty of any kind. The library has been entirely written by Jean-loup
+Gailly and Mark Adler; it does not include third-party code. We make all
+contributions to and distributions of this project solely in our personal
+capacity, and are not conveying any rights to any intellectual property of
+any third parties.
+
+If you redistribute modified sources, we would appreciate that you include in
+the file ChangeLog history information documenting your changes. Please read
+the FAQ for more information on the distribution of modified source versions.
ADDED compat/zlib/adler32.c
Index: compat/zlib/adler32.c
==================================================================
--- compat/zlib/adler32.c
+++ compat/zlib/adler32.c
@@ -0,0 +1,186 @@
+/* adler32.c -- compute the Adler-32 checksum of a data stream
+ * Copyright (C) 1995-2011, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zutil.h"
+
+local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
+
+#define BASE 65521U /* largest prime smaller than 65536 */
+#define NMAX 5552
+/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
+
+#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
+#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
+#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
+#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
+#define DO16(buf) DO8(buf,0); DO8(buf,8);
+
+/* use NO_DIVIDE if your processor does not do division in hardware --
+ try it both ways to see which is faster */
+#ifdef NO_DIVIDE
+/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
+ (thank you to John Reiser for pointing this out) */
+# define CHOP(a) \
+ do { \
+ unsigned long tmp = a >> 16; \
+ a &= 0xffffUL; \
+ a += (tmp << 4) - tmp; \
+ } while (0)
+# define MOD28(a) \
+ do { \
+ CHOP(a); \
+ if (a >= BASE) a -= BASE; \
+ } while (0)
+# define MOD(a) \
+ do { \
+ CHOP(a); \
+ MOD28(a); \
+ } while (0)
+# define MOD63(a) \
+ do { /* this assumes a is not negative */ \
+ z_off64_t tmp = a >> 32; \
+ a &= 0xffffffffL; \
+ a += (tmp << 8) - (tmp << 5) + tmp; \
+ tmp = a >> 16; \
+ a &= 0xffffL; \
+ a += (tmp << 4) - tmp; \
+ tmp = a >> 16; \
+ a &= 0xffffL; \
+ a += (tmp << 4) - tmp; \
+ if (a >= BASE) a -= BASE; \
+ } while (0)
+#else
+# define MOD(a) a %= BASE
+# define MOD28(a) a %= BASE
+# define MOD63(a) a %= BASE
+#endif
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_z(adler, buf, len)
+ uLong adler;
+ const Bytef *buf;
+ z_size_t len;
+{
+ unsigned long sum2;
+ unsigned n;
+
+ /* split Adler-32 into component sums */
+ sum2 = (adler >> 16) & 0xffff;
+ adler &= 0xffff;
+
+ /* in case user likes doing a byte at a time, keep it fast */
+ if (len == 1) {
+ adler += buf[0];
+ if (adler >= BASE)
+ adler -= BASE;
+ sum2 += adler;
+ if (sum2 >= BASE)
+ sum2 -= BASE;
+ return adler | (sum2 << 16);
+ }
+
+ /* initial Adler-32 value (deferred check for len == 1 speed) */
+ if (buf == Z_NULL)
+ return 1L;
+
+ /* in case short lengths are provided, keep it somewhat fast */
+ if (len < 16) {
+ while (len--) {
+ adler += *buf++;
+ sum2 += adler;
+ }
+ if (adler >= BASE)
+ adler -= BASE;
+ MOD28(sum2); /* only added so many BASE's */
+ return adler | (sum2 << 16);
+ }
+
+ /* do length NMAX blocks -- requires just one modulo operation */
+ while (len >= NMAX) {
+ len -= NMAX;
+ n = NMAX / 16; /* NMAX is divisible by 16 */
+ do {
+ DO16(buf); /* 16 sums unrolled */
+ buf += 16;
+ } while (--n);
+ MOD(adler);
+ MOD(sum2);
+ }
+
+ /* do remaining bytes (less than NMAX, still just one modulo) */
+ if (len) { /* avoid modulos if none remaining */
+ while (len >= 16) {
+ len -= 16;
+ DO16(buf);
+ buf += 16;
+ }
+ while (len--) {
+ adler += *buf++;
+ sum2 += adler;
+ }
+ MOD(adler);
+ MOD(sum2);
+ }
+
+ /* return recombined sums */
+ return adler | (sum2 << 16);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT adler32(adler, buf, len)
+ uLong adler;
+ const Bytef *buf;
+ uInt len;
+{
+ return adler32_z(adler, buf, len);
+}
+
+/* ========================================================================= */
+local uLong adler32_combine_(adler1, adler2, len2)
+ uLong adler1;
+ uLong adler2;
+ z_off64_t len2;
+{
+ unsigned long sum1;
+ unsigned long sum2;
+ unsigned rem;
+
+ /* for negative len, return invalid adler32 as a clue for debugging */
+ if (len2 < 0)
+ return 0xffffffffUL;
+
+ /* the derivation of this formula is left as an exercise for the reader */
+ MOD63(len2); /* assumes len2 >= 0 */
+ rem = (unsigned)len2;
+ sum1 = adler1 & 0xffff;
+ sum2 = rem * sum1;
+ MOD(sum2);
+ sum1 += (adler2 & 0xffff) + BASE - 1;
+ sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
+ if (sum1 >= BASE) sum1 -= BASE;
+ if (sum1 >= BASE) sum1 -= BASE;
+ if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1);
+ if (sum2 >= BASE) sum2 -= BASE;
+ return sum1 | (sum2 << 16);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+ uLong adler1;
+ uLong adler2;
+ z_off_t len2;
+{
+ return adler32_combine_(adler1, adler2, len2);
+}
+
+uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
+ uLong adler1;
+ uLong adler2;
+ z_off64_t len2;
+{
+ return adler32_combine_(adler1, adler2, len2);
+}
ADDED compat/zlib/amiga/Makefile.pup
Index: compat/zlib/amiga/Makefile.pup
==================================================================
--- compat/zlib/amiga/Makefile.pup
+++ compat/zlib/amiga/Makefile.pup
@@ -0,0 +1,69 @@
+# Amiga powerUP (TM) Makefile
+# makefile for libpng and SAS C V6.58/7.00 PPC compiler
+# Copyright (C) 1998 by Andreas R. Kleinert
+
+LIBNAME = libzip.a
+
+CC = scppc
+CFLAGS = NOSTKCHK NOSINT OPTIMIZE OPTGO OPTPEEP OPTINLOCAL OPTINL \
+ OPTLOOP OPTRDEP=8 OPTDEP=8 OPTCOMP=8 NOVER
+AR = ppc-amigaos-ar cr
+RANLIB = ppc-amigaos-ranlib
+LD = ppc-amigaos-ld -r
+LDFLAGS = -o
+LDLIBS = LIB:scppc.a LIB:end.o
+RM = delete quiet
+
+OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \
+ uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
+
+TEST_OBJS = example.o minigzip.o
+
+all: example minigzip
+
+check: test
+test: all
+ example
+ echo hello world | minigzip | minigzip -d
+
+$(LIBNAME): $(OBJS)
+ $(AR) $@ $(OBJS)
+ -$(RANLIB) $@
+
+example: example.o $(LIBNAME)
+ $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS)
+
+minigzip: minigzip.o $(LIBNAME)
+ $(LD) $(LDFLAGS) $@ LIB:c_ppc.o $@.o $(LIBNAME) $(LDLIBS)
+
+mostlyclean: clean
+clean:
+ $(RM) *.o example minigzip $(LIBNAME) foo.gz
+
+zip:
+ zip -ul9 zlib README ChangeLog Makefile Make????.??? Makefile.?? \
+ descrip.mms *.[ch]
+
+tgz:
+ cd ..; tar cfz zlib/zlib.tgz zlib/README zlib/ChangeLog zlib/Makefile \
+ zlib/Make????.??? zlib/Makefile.?? zlib/descrip.mms zlib/*.[ch]
+
+# DO NOT DELETE THIS LINE -- make depend depends on it.
+
+adler32.o: zlib.h zconf.h
+compress.o: zlib.h zconf.h
+crc32.o: crc32.h zlib.h zconf.h
+deflate.o: deflate.h zutil.h zlib.h zconf.h
+example.o: zlib.h zconf.h
+gzclose.o: zlib.h zconf.h gzguts.h
+gzlib.o: zlib.h zconf.h gzguts.h
+gzread.o: zlib.h zconf.h gzguts.h
+gzwrite.o: zlib.h zconf.h gzguts.h
+inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
+inftrees.o: zutil.h zlib.h zconf.h inftrees.h
+minigzip.o: zlib.h zconf.h
+trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
+uncompr.o: zlib.h zconf.h
+zutil.o: zutil.h zlib.h zconf.h
ADDED compat/zlib/amiga/Makefile.sas
Index: compat/zlib/amiga/Makefile.sas
==================================================================
--- compat/zlib/amiga/Makefile.sas
+++ compat/zlib/amiga/Makefile.sas
@@ -0,0 +1,68 @@
+# SMakefile for zlib
+# Modified from the standard UNIX Makefile Copyright Jean-loup Gailly
+# Osma Ahvenlampi
+# Amiga, SAS/C 6.56 & Smake
+
+CC=sc
+CFLAGS=OPT
+#CFLAGS=OPT CPU=68030
+#CFLAGS=DEBUG=LINE
+LDFLAGS=LIB z.lib
+
+SCOPTIONS=OPTSCHED OPTINLINE OPTALIAS OPTTIME OPTINLOCAL STRMERGE \
+ NOICONS PARMS=BOTH NOSTACKCHECK UTILLIB NOVERSION ERRORREXX \
+ DEF=POSTINC
+
+OBJS = adler32.o compress.o crc32.o gzclose.o gzlib.o gzread.o gzwrite.o \
+ uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
+
+TEST_OBJS = example.o minigzip.o
+
+all: SCOPTIONS example minigzip
+
+check: test
+test: all
+ example
+ echo hello world | minigzip | minigzip -d
+
+install: z.lib
+ copy clone zlib.h zconf.h INCLUDE:
+ copy clone z.lib LIB:
+
+z.lib: $(OBJS)
+ oml z.lib r $(OBJS)
+
+example: example.o z.lib
+ $(CC) $(CFLAGS) LINK TO $@ example.o $(LDFLAGS)
+
+minigzip: minigzip.o z.lib
+ $(CC) $(CFLAGS) LINK TO $@ minigzip.o $(LDFLAGS)
+
+mostlyclean: clean
+clean:
+ -delete force quiet example minigzip *.o z.lib foo.gz *.lnk SCOPTIONS
+
+SCOPTIONS: Makefile.sas
+ copy to $@ (uLong)max ? max : (uInt)left;
+ left -= stream.avail_out;
+ }
+ if (stream.avail_in == 0) {
+ stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen;
+ sourceLen -= stream.avail_in;
+ }
+ err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);
+ } while (err == Z_OK);
+
+ *destLen = stream.total_out;
+ deflateEnd(&stream);
+ return err == Z_STREAM_END ? Z_OK : err;
+}
+
+/* ===========================================================================
+ */
+int ZEXPORT compress(dest, destLen, source, sourceLen)
+ Bytef *dest;
+ uLongf *destLen;
+ const Bytef *source;
+ uLong sourceLen;
+{
+ return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
+}
+
+/* ===========================================================================
+ If the default memLevel or windowBits for deflateInit() is changed, then
+ this function needs to be updated.
+ */
+uLong ZEXPORT compressBound(sourceLen)
+ uLong sourceLen;
+{
+ return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+ (sourceLen >> 25) + 13;
+}
ADDED compat/zlib/configure
Index: compat/zlib/configure
==================================================================
--- compat/zlib/configure
+++ compat/zlib/configure
@@ -0,0 +1,922 @@
+#!/bin/sh
+# configure script for zlib.
+#
+# Normally configure builds both a static and a shared library.
+# If you want to build just a static library, use: ./configure --static
+#
+# To impose specific compiler or flags or install directory, use for example:
+# prefix=$HOME CC=cc CFLAGS="-O4" ./configure
+# or for csh/tcsh users:
+# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure)
+
+# Incorrect settings of CC or CFLAGS may prevent creating a shared library.
+# If you have problems, try without defining CC and CFLAGS before reporting
+# an error.
+
+# start off configure.log
+echo -------------------- >> configure.log
+echo $0 $* >> configure.log
+date >> configure.log
+
+# get source directory
+SRCDIR=`dirname $0`
+if test $SRCDIR = "."; then
+ ZINC=""
+ ZINCOUT="-I."
+ SRCDIR=""
+else
+ ZINC='-include zconf.h'
+ ZINCOUT='-I. -I$(SRCDIR)'
+ SRCDIR="$SRCDIR/"
+fi
+
+# set command prefix for cross-compilation
+if [ -n "${CHOST}" ]; then
+ uname=${CHOST}
+ mname=${CHOST}
+ CROSS_PREFIX="${CHOST}-"
+else
+ mname=`(uname -a || echo unknown) 2>/dev/null`
+fi
+
+# destination name for static library
+STATICLIB=libz.a
+
+# extract zlib version numbers from zlib.h
+VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < ${SRCDIR}zlib.h`
+VER3=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\\.[0-9]*\).*/\1/p' < ${SRCDIR}zlib.h`
+VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h`
+VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < ${SRCDIR}zlib.h`
+
+# establish commands for library building
+if "${CROSS_PREFIX}ar" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+ AR=${AR-"${CROSS_PREFIX}ar"}
+ test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log
+else
+ AR=${AR-"ar"}
+ test -n "${CROSS_PREFIX}" && echo Using ${AR} | tee -a configure.log
+fi
+ARFLAGS=${ARFLAGS-"rc"}
+if "${CROSS_PREFIX}ranlib" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+ RANLIB=${RANLIB-"${CROSS_PREFIX}ranlib"}
+ test -n "${CROSS_PREFIX}" && echo Using ${RANLIB} | tee -a configure.log
+else
+ RANLIB=${RANLIB-"ranlib"}
+fi
+if "${CROSS_PREFIX}nm" --version >/dev/null 2>/dev/null || test $? -lt 126; then
+ NM=${NM-"${CROSS_PREFIX}nm"}
+ test -n "${CROSS_PREFIX}" && echo Using ${NM} | tee -a configure.log
+else
+ NM=${NM-"nm"}
+fi
+
+# set defaults before processing command line options
+LDCONFIG=${LDCONFIG-"ldconfig"}
+LDSHAREDLIBC="${LDSHAREDLIBC--lc}"
+ARCHS=
+prefix=${prefix-/usr/local}
+exec_prefix=${exec_prefix-'${prefix}'}
+libdir=${libdir-'${exec_prefix}/lib'}
+sharedlibdir=${sharedlibdir-'${libdir}'}
+includedir=${includedir-'${prefix}/include'}
+mandir=${mandir-'${prefix}/share/man'}
+shared_ext='.so'
+shared=1
+solo=0
+cover=0
+zprefix=0
+zconst=0
+build64=0
+gcc=0
+warn=0
+debug=0
+sanitize=0
+old_cc="$CC"
+old_cflags="$CFLAGS"
+OBJC='$(OBJZ) $(OBJG)'
+PIC_OBJC='$(PIC_OBJZ) $(PIC_OBJG)'
+
+# leave this script, optionally in a bad way
+leave()
+{
+ if test "$*" != "0"; then
+ echo "** $0 aborting." | tee -a configure.log
+ fi
+ rm -f $test.[co] $test $test$shared_ext $test.gcno ./--version
+ echo -------------------- >> configure.log
+ echo >> configure.log
+ echo >> configure.log
+ exit $1
+}
+
+# process command line options
+while test $# -ge 1
+do
+case "$1" in
+ -h* | --help)
+ echo 'usage:' | tee -a configure.log
+ echo ' configure [--const] [--zprefix] [--prefix=PREFIX] [--eprefix=EXPREFIX]' | tee -a configure.log
+ echo ' [--static] [--64] [--libdir=LIBDIR] [--sharedlibdir=LIBDIR]' | tee -a configure.log
+ echo ' [--includedir=INCLUDEDIR] [--archs="-arch i386 -arch x86_64"]' | tee -a configure.log
+ exit 0 ;;
+ -p*=* | --prefix=*) prefix=`echo $1 | sed 's/.*=//'`; shift ;;
+ -e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/.*=//'`; shift ;;
+ -l*=* | --libdir=*) libdir=`echo $1 | sed 's/.*=//'`; shift ;;
+ --sharedlibdir=*) sharedlibdir=`echo $1 | sed 's/.*=//'`; shift ;;
+ -i*=* | --includedir=*) includedir=`echo $1 | sed 's/.*=//'`;shift ;;
+ -u*=* | --uname=*) uname=`echo $1 | sed 's/.*=//'`;shift ;;
+ -p* | --prefix) prefix="$2"; shift; shift ;;
+ -e* | --eprefix) exec_prefix="$2"; shift; shift ;;
+ -l* | --libdir) libdir="$2"; shift; shift ;;
+ -i* | --includedir) includedir="$2"; shift; shift ;;
+ -s* | --shared | --enable-shared) shared=1; shift ;;
+ -t | --static) shared=0; shift ;;
+ --solo) solo=1; shift ;;
+ --cover) cover=1; shift ;;
+ -z* | --zprefix) zprefix=1; shift ;;
+ -6* | --64) build64=1; shift ;;
+ -a*=* | --archs=*) ARCHS=`echo $1 | sed 's/.*=//'`; shift ;;
+ --sysconfdir=*) echo "ignored option: --sysconfdir" | tee -a configure.log; shift ;;
+ --localstatedir=*) echo "ignored option: --localstatedir" | tee -a configure.log; shift ;;
+ -c* | --const) zconst=1; shift ;;
+ -w* | --warn) warn=1; shift ;;
+ -d* | --debug) debug=1; shift ;;
+ --sanitize) sanitize=1; shift ;;
+ *)
+ echo "unknown option: $1" | tee -a configure.log
+ echo "$0 --help for help" | tee -a configure.log
+ leave 1;;
+ esac
+done
+
+# temporary file name
+test=ztest$$
+
+# put arguments in log, also put test file in log if used in arguments
+show()
+{
+ case "$*" in
+ *$test.c*)
+ echo === $test.c === >> configure.log
+ cat $test.c >> configure.log
+ echo === >> configure.log;;
+ esac
+ echo $* >> configure.log
+}
+
+# check for gcc vs. cc and set compile and link flags based on the system identified by uname
+cat > $test.c </dev/null 2>&1; then
+ cc=${CROSS_PREFIX}gcc
+ else
+ cc=${CROSS_PREFIX}cc
+ fi
+else
+ cc=${CC}
+fi
+
+case "$cc" in
+ *gcc*) gcc=1 ;;
+ *clang*) gcc=1 ;;
+esac
+case `$cc -v 2>&1` in
+ *gcc*) gcc=1 ;;
+ *clang*) gcc=1 ;;
+esac
+
+show $cc -c $test.c
+if test "$gcc" -eq 1 && ($cc -c $test.c) >> configure.log 2>&1; then
+ echo ... using gcc >> configure.log
+ CC="$cc"
+ CFLAGS="${CFLAGS--O3}"
+ SFLAGS="${CFLAGS--O3} -fPIC"
+ if test "$ARCHS"; then
+ CFLAGS="${CFLAGS} ${ARCHS}"
+ LDFLAGS="${LDFLAGS} ${ARCHS}"
+ fi
+ if test $build64 -eq 1; then
+ CFLAGS="${CFLAGS} -m64"
+ SFLAGS="${SFLAGS} -m64"
+ fi
+ if test "$warn" -eq 1; then
+ if test "$zconst" -eq 1; then
+ CFLAGS="${CFLAGS} -Wall -Wextra -Wcast-qual -DZLIB_CONST"
+ else
+ CFLAGS="${CFLAGS} -Wall -Wextra"
+ fi
+ fi
+ if test $sanitize -eq 1; then
+ CFLAGS="${CFLAGS} -g -fsanitize=address"
+ fi
+ if test $debug -eq 1; then
+ CFLAGS="${CFLAGS} -DZLIB_DEBUG"
+ SFLAGS="${SFLAGS} -DZLIB_DEBUG"
+ fi
+ if test -z "$uname"; then
+ uname=`(uname -s || echo unknown) 2>/dev/null`
+ fi
+ case "$uname" in
+ Linux* | linux* | *-linux* | GNU | GNU/* | solaris*)
+ case "$mname" in
+ *sparc*)
+ LDFLAGS="${LDFLAGS} -Wl,--no-warn-rwx-segments" ;;
+ esac
+ LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"} ;;
+ *BSD | *bsd* | DragonFly)
+ LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,${SRCDIR}zlib.map"}
+ LDCONFIG="ldconfig -m" ;;
+ CYGWIN* | Cygwin* | cygwin* | *-cygwin* | OS/2*)
+ EXE='.exe' ;;
+ MINGW* | mingw* | *-mingw*)
+ rm -f $test.[co] $test $test$shared_ext
+ echo "If this doesn't work for you, try win32/Makefile.gcc." | tee -a configure.log
+ LDSHARED=${LDSHARED-"$cc -shared"}
+ LDSHAREDLIBC=""
+ EXE='.exe' ;;
+ QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4
+ # (alain.bonnefoy@icbt.com)
+ LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"} ;;
+ HP-UX*)
+ LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"}
+ case `(uname -m || echo unknown) 2>/dev/null` in
+ ia64)
+ shared_ext='.so'
+ SHAREDLIB='libz.so' ;;
+ *)
+ shared_ext='.sl'
+ SHAREDLIB='libz.sl' ;;
+ esac ;;
+ AIX*)
+ LDFLAGS="${LDFLAGS} -Wl,-brtl" ;;
+ Darwin* | darwin* | *-darwin*)
+ shared_ext='.dylib'
+ SHAREDLIB=libz$shared_ext
+ SHAREDLIBV=libz.$VER$shared_ext
+ SHAREDLIBM=libz.$VER1$shared_ext
+ LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER3"}
+ if libtool -V 2>&1 | grep Apple > /dev/null; then
+ AR="libtool"
+ else
+ AR="/usr/bin/libtool"
+ fi
+ ARFLAGS="-o" ;;
+ *)
+ LDSHARED=${LDSHARED-"$cc -shared"} ;;
+ esac
+else
+ # find system name and corresponding cc options
+ CC=${CC-cc}
+ gcc=0
+ echo ... using $CC >> configure.log
+ if test -z "$uname"; then
+ uname=`(uname -sr || echo unknown) 2>/dev/null`
+ fi
+ case "$uname" in
+ HP-UX*) SFLAGS=${CFLAGS-"-O +z"}
+ CFLAGS=${CFLAGS-"-O"}
+# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"}
+ LDSHARED=${LDSHARED-"ld -b"}
+ case `(uname -m || echo unknown) 2>/dev/null` in
+ ia64)
+ shared_ext='.so'
+ SHAREDLIB='libz.so' ;;
+ *)
+ shared_ext='.sl'
+ SHAREDLIB='libz.sl' ;;
+ esac ;;
+ IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."}
+ CFLAGS=${CFLAGS-"-ansi -O2"}
+ LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
+ OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"}
+ CFLAGS=${CFLAGS-"-O -std1"}
+ LDFLAGS="${LDFLAGS} -Wl,-rpath,."
+ LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"} ;;
+ OSF1*) SFLAGS=${CFLAGS-"-O -std1"}
+ CFLAGS=${CFLAGS-"-O -std1"}
+ LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
+ QNX*) SFLAGS=${CFLAGS-"-4 -O"}
+ CFLAGS=${CFLAGS-"-4 -O"}
+ LDSHARED=${LDSHARED-"cc"}
+ RANLIB=${RANLIB-"true"}
+ AR="cc"
+ ARFLAGS="-A" ;;
+ SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "}
+ CFLAGS=${CFLAGS-"-O3"}
+ LDSHARED=${LDSHARED-"cc -dy -KPIC -G"} ;;
+ SunOS\ 5* | solaris*)
+ LDSHARED=${LDSHARED-"cc -G -h libz$shared_ext.$VER1"}
+ SFLAGS=${CFLAGS-"-fast -KPIC"}
+ CFLAGS=${CFLAGS-"-fast"}
+ if test $build64 -eq 1; then
+ # old versions of SunPRO/Workshop/Studio don't support -m64,
+ # but newer ones do. Check for it.
+ flag64=`$CC -flags | egrep -- '^-m64'`
+ if test x"$flag64" != x"" ; then
+ CFLAGS="${CFLAGS} -m64"
+ SFLAGS="${SFLAGS} -m64"
+ else
+ case `(uname -m || echo unknown) 2>/dev/null` in
+ i86*)
+ SFLAGS="$SFLAGS -xarch=amd64"
+ CFLAGS="$CFLAGS -xarch=amd64" ;;
+ *)
+ SFLAGS="$SFLAGS -xarch=v9"
+ CFLAGS="$CFLAGS -xarch=v9" ;;
+ esac
+ fi
+ fi
+ if test -n "$ZINC"; then
+ ZINC='-I- -I. -I$(SRCDIR)'
+ fi
+ ;;
+ SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"}
+ CFLAGS=${CFLAGS-"-O2"}
+ LDSHARED=${LDSHARED-"ld"} ;;
+ SunStudio\ 9*) SFLAGS=${CFLAGS-"-fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
+ CFLAGS=${CFLAGS-"-fast -xtarget=ultra3 -xarch=v9b"}
+ LDSHARED=${LDSHARED-"cc -xarch=v9b"} ;;
+ UNIX_System_V\ 4.2.0)
+ SFLAGS=${CFLAGS-"-KPIC -O"}
+ CFLAGS=${CFLAGS-"-O"}
+ LDSHARED=${LDSHARED-"cc -G"} ;;
+ UNIX_SV\ 4.2MP)
+ SFLAGS=${CFLAGS-"-Kconform_pic -O"}
+ CFLAGS=${CFLAGS-"-O"}
+ LDSHARED=${LDSHARED-"cc -G"} ;;
+ OpenUNIX\ 5)
+ SFLAGS=${CFLAGS-"-KPIC -O"}
+ CFLAGS=${CFLAGS-"-O"}
+ LDSHARED=${LDSHARED-"cc -G"} ;;
+ AIX*) # Courtesy of dbakker@arrayasolutions.com
+ SFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
+ CFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
+ LDSHARED=${LDSHARED-"xlc -G"} ;;
+ # send working options for other systems to zlib@gzip.org
+ *) SFLAGS=${CFLAGS-"-O"}
+ CFLAGS=${CFLAGS-"-O"}
+ LDSHARED=${LDSHARED-"cc -shared"} ;;
+ esac
+fi
+
+# destination names for shared library if not defined above
+SHAREDLIB=${SHAREDLIB-"libz$shared_ext"}
+SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"}
+SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"}
+
+echo >> configure.log
+
+# define functions for testing compiler and library characteristics and logging the results
+
+cat > $test.c </dev/null; then
+ try()
+ {
+ show $*
+ test "`( $* ) 2>&1 | tee -a configure.log`" = ""
+ }
+ echo - using any output from compiler to indicate an error >> configure.log
+else
+ try()
+ {
+ show $*
+ got=`( $* ) 2>&1`
+ ret=$?
+ if test "$got" != ""; then
+ printf "%s\n" "$got" >> configure.log
+ fi
+ if test $ret -ne 0; then
+ echo "(exit code "$ret")" >> configure.log
+ fi
+ return $ret
+ }
+fi
+
+tryboth()
+{
+ show $*
+ got=`( $* ) 2>&1`
+ ret=$?
+ if test "$got" != ""; then
+ printf "%s\n" "$got" >> configure.log
+ fi
+ if test $ret -ne 0; then
+ echo "(exit code "$ret")" >> configure.log
+ return $ret
+ fi
+ test "$got" = ""
+}
+
+cat > $test.c << EOF
+int foo() { return 0; }
+EOF
+echo "Checking for obsessive-compulsive compiler options..." >> configure.log
+if try $CC -c $CFLAGS $test.c; then
+ :
+else
+ echo "Compiler error reporting is too harsh for $0 (perhaps remove -Werror)." | tee -a configure.log
+ leave 1
+fi
+
+echo >> configure.log
+
+# see if shared library build supported
+cat > $test.c <> configure.log
+
+# check for size_t
+cat > $test.c <
+#include
+size_t dummy = 0;
+EOF
+if try $CC -c $CFLAGS $test.c; then
+ echo "Checking for size_t... Yes." | tee -a configure.log
+else
+ echo "Checking for size_t... No." | tee -a configure.log
+ # find a size_t integer type
+ # check for long long
+ cat > $test.c << EOF
+long long dummy = 0;
+EOF
+ if try $CC -c $CFLAGS $test.c; then
+ echo "Checking for long long... Yes." | tee -a configure.log
+ cat > $test.c <
+int main(void) {
+ if (sizeof(void *) <= sizeof(int)) puts("int");
+ else if (sizeof(void *) <= sizeof(long)) puts("long");
+ else puts("z_longlong");
+ return 0;
+}
+EOF
+ else
+ echo "Checking for long long... No." | tee -a configure.log
+ cat > $test.c <
+int main(void) {
+ if (sizeof(void *) <= sizeof(int)) puts("int");
+ else puts("long");
+ return 0;
+}
+EOF
+ fi
+ if try $CC $CFLAGS -o $test $test.c; then
+ sizet=`./$test`
+ echo "Checking for a pointer-size integer type..." $sizet"." | tee -a configure.log
+ CFLAGS="${CFLAGS} -DNO_SIZE_T=${sizet}"
+ SFLAGS="${SFLAGS} -DNO_SIZE_T=${sizet}"
+ else
+ echo "Checking for a pointer-size integer type... not found." | tee -a configure.log
+ fi
+fi
+
+echo >> configure.log
+
+# check for large file support, and if none, check for fseeko()
+cat > $test.c <
+off64_t dummy = 0;
+EOF
+if try $CC -c $CFLAGS -D_LARGEFILE64_SOURCE=1 $test.c; then
+ CFLAGS="${CFLAGS} -D_LARGEFILE64_SOURCE=1"
+ SFLAGS="${SFLAGS} -D_LARGEFILE64_SOURCE=1"
+ ALL="${ALL} all64"
+ TEST="${TEST} test64"
+ echo "Checking for off64_t... Yes." | tee -a configure.log
+ echo "Checking for fseeko... Yes." | tee -a configure.log
+else
+ echo "Checking for off64_t... No." | tee -a configure.log
+ echo >> configure.log
+ cat > $test.c <
+int main(void) {
+ fseeko(NULL, 0, 0);
+ return 0;
+}
+EOF
+ if try $CC $CFLAGS -o $test $test.c; then
+ echo "Checking for fseeko... Yes." | tee -a configure.log
+ else
+ CFLAGS="${CFLAGS} -DNO_FSEEKO"
+ SFLAGS="${SFLAGS} -DNO_FSEEKO"
+ echo "Checking for fseeko... No." | tee -a configure.log
+ fi
+fi
+
+echo >> configure.log
+
+# check for strerror() for use by gz* functions
+cat > $test.c <
+#include
+int main() { return strlen(strerror(errno)); }
+EOF
+if try $CC $CFLAGS -o $test $test.c; then
+ echo "Checking for strerror... Yes." | tee -a configure.log
+else
+ CFLAGS="${CFLAGS} -DNO_STRERROR"
+ SFLAGS="${SFLAGS} -DNO_STRERROR"
+ echo "Checking for strerror... No." | tee -a configure.log
+fi
+
+# copy clean zconf.h for subsequent edits
+cp -p ${SRCDIR}zconf.h.in zconf.h
+
+echo >> configure.log
+
+# check for unistd.h and save result in zconf.h
+cat > $test.c <
+int main() { return 0; }
+EOF
+if try $CC -c $CFLAGS $test.c; then
+ sed < zconf.h "/^#ifdef HAVE_UNISTD_H.* may be/s/def HAVE_UNISTD_H\(.*\) may be/ 1\1 was/" > zconf.temp.h
+ mv zconf.temp.h zconf.h
+ echo "Checking for unistd.h... Yes." | tee -a configure.log
+else
+ echo "Checking for unistd.h... No." | tee -a configure.log
+fi
+
+echo >> configure.log
+
+# check for stdarg.h and save result in zconf.h
+cat > $test.c <
+int main() { return 0; }
+EOF
+if try $CC -c $CFLAGS $test.c; then
+ sed < zconf.h "/^#ifdef HAVE_STDARG_H.* may be/s/def HAVE_STDARG_H\(.*\) may be/ 1\1 was/" > zconf.temp.h
+ mv zconf.temp.h zconf.h
+ echo "Checking for stdarg.h... Yes." | tee -a configure.log
+else
+ echo "Checking for stdarg.h... No." | tee -a configure.log
+fi
+
+# if the z_ prefix was requested, save that in zconf.h
+if test $zprefix -eq 1; then
+ sed < zconf.h "/#ifdef Z_PREFIX.* may be/s/def Z_PREFIX\(.*\) may be/ 1\1 was/" > zconf.temp.h
+ mv zconf.temp.h zconf.h
+ echo >> configure.log
+ echo "Using z_ prefix on all symbols." | tee -a configure.log
+fi
+
+# if --solo compilation was requested, save that in zconf.h and remove gz stuff from object lists
+if test $solo -eq 1; then
+ sed '/#define ZCONF_H/a\
+#define Z_SOLO
+
+' < zconf.h > zconf.temp.h
+ mv zconf.temp.h zconf.h
+OBJC='$(OBJZ)'
+PIC_OBJC='$(PIC_OBJZ)'
+fi
+
+# if code coverage testing was requested, use older gcc if defined, e.g. "gcc-4.2" on Mac OS X
+if test $cover -eq 1; then
+ CFLAGS="${CFLAGS} -fprofile-arcs -ftest-coverage"
+ if test -n "$GCC_CLASSIC"; then
+ CC=$GCC_CLASSIC
+ fi
+fi
+
+echo >> configure.log
+
+# conduct a series of tests to resolve eight possible cases of using "vs" or "s" printf functions
+# (using stdarg or not), with or without "n" (proving size of buffer), and with or without a
+# return value. The most secure result is vsnprintf() with a return value. snprintf() with a
+# return value is secure as well, but then gzprintf() will be limited to 20 arguments.
+cat > $test.c <
+#include
+#include "zconf.h"
+int main()
+{
+#ifndef STDC
+ choke me
+#endif
+ return 0;
+}
+EOF
+if try $CC -c $CFLAGS $test.c; then
+ echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()." | tee -a configure.log
+
+ echo >> configure.log
+ cat > $test.c <
+#include
+int mytest(const char *fmt, ...)
+{
+ char buf[20];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(buf, sizeof(buf), fmt, ap);
+ va_end(ap);
+ return 0;
+}
+int main()
+{
+ return (mytest("Hello%d\n", 1));
+}
+EOF
+ if try $CC $CFLAGS -o $test $test.c; then
+ echo "Checking for vsnprintf() in stdio.h... Yes." | tee -a configure.log
+
+ echo >> configure.log
+ cat >$test.c <
+#include
+int mytest(const char *fmt, ...)
+{
+ int n;
+ char buf[20];
+ va_list ap;
+ va_start(ap, fmt);
+ n = vsnprintf(buf, sizeof(buf), fmt, ap);
+ va_end(ap);
+ return n;
+}
+int main()
+{
+ return (mytest("Hello%d\n", 1));
+}
+EOF
+
+ if try $CC -c $CFLAGS $test.c; then
+ echo "Checking for return value of vsnprintf()... Yes." | tee -a configure.log
+ else
+ CFLAGS="$CFLAGS -DHAS_vsnprintf_void"
+ SFLAGS="$SFLAGS -DHAS_vsnprintf_void"
+ echo "Checking for return value of vsnprintf()... No." | tee -a configure.log
+ echo " WARNING: apparently vsnprintf() does not return a value. zlib" | tee -a configure.log
+ echo " can build but will be open to possible string-format security" | tee -a configure.log
+ echo " vulnerabilities." | tee -a configure.log
+ fi
+ else
+ CFLAGS="$CFLAGS -DNO_vsnprintf"
+ SFLAGS="$SFLAGS -DNO_vsnprintf"
+ echo "Checking for vsnprintf() in stdio.h... No." | tee -a configure.log
+ echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib" | tee -a configure.log
+ echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log
+ echo " vulnerabilities." | tee -a configure.log
+
+ echo >> configure.log
+ cat >$test.c <
+#include
+int mytest(const char *fmt, ...)
+{
+ int n;
+ char buf[20];
+ va_list ap;
+ va_start(ap, fmt);
+ n = vsprintf(buf, fmt, ap);
+ va_end(ap);
+ return n;
+}
+int main()
+{
+ return (mytest("Hello%d\n", 1));
+}
+EOF
+
+ if try $CC -c $CFLAGS $test.c; then
+ echo "Checking for return value of vsprintf()... Yes." | tee -a configure.log
+ else
+ CFLAGS="$CFLAGS -DHAS_vsprintf_void"
+ SFLAGS="$SFLAGS -DHAS_vsprintf_void"
+ echo "Checking for return value of vsprintf()... No." | tee -a configure.log
+ echo " WARNING: apparently vsprintf() does not return a value. zlib" | tee -a configure.log
+ echo " can build but will be open to possible string-format security" | tee -a configure.log
+ echo " vulnerabilities." | tee -a configure.log
+ fi
+ fi
+else
+ echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()." | tee -a configure.log
+
+ echo >> configure.log
+ cat >$test.c <
+int mytest()
+{
+ char buf[20];
+ snprintf(buf, sizeof(buf), "%s", "foo");
+ return 0;
+}
+int main()
+{
+ return (mytest());
+}
+EOF
+
+ if try $CC $CFLAGS -o $test $test.c; then
+ echo "Checking for snprintf() in stdio.h... Yes." | tee -a configure.log
+
+ echo >> configure.log
+ cat >$test.c <
+int mytest()
+{
+ char buf[20];
+ return snprintf(buf, sizeof(buf), "%s", "foo");
+}
+int main()
+{
+ return (mytest());
+}
+EOF
+
+ if try $CC -c $CFLAGS $test.c; then
+ echo "Checking for return value of snprintf()... Yes." | tee -a configure.log
+ else
+ CFLAGS="$CFLAGS -DHAS_snprintf_void"
+ SFLAGS="$SFLAGS -DHAS_snprintf_void"
+ echo "Checking for return value of snprintf()... No." | tee -a configure.log
+ echo " WARNING: apparently snprintf() does not return a value. zlib" | tee -a configure.log
+ echo " can build but will be open to possible string-format security" | tee -a configure.log
+ echo " vulnerabilities." | tee -a configure.log
+ fi
+ else
+ CFLAGS="$CFLAGS -DNO_snprintf"
+ SFLAGS="$SFLAGS -DNO_snprintf"
+ echo "Checking for snprintf() in stdio.h... No." | tee -a configure.log
+ echo " WARNING: snprintf() not found, falling back to sprintf(). zlib" | tee -a configure.log
+ echo " can build but will be open to possible buffer-overflow security" | tee -a configure.log
+ echo " vulnerabilities." | tee -a configure.log
+
+ echo >> configure.log
+ cat >$test.c <
+int mytest()
+{
+ char buf[20];
+ return sprintf(buf, "%s", "foo");
+}
+int main()
+{
+ return (mytest());
+}
+EOF
+
+ if try $CC -c $CFLAGS $test.c; then
+ echo "Checking for return value of sprintf()... Yes." | tee -a configure.log
+ else
+ CFLAGS="$CFLAGS -DHAS_sprintf_void"
+ SFLAGS="$SFLAGS -DHAS_sprintf_void"
+ echo "Checking for return value of sprintf()... No." | tee -a configure.log
+ echo " WARNING: apparently sprintf() does not return a value. zlib" | tee -a configure.log
+ echo " can build but will be open to possible string-format security" | tee -a configure.log
+ echo " vulnerabilities." | tee -a configure.log
+ fi
+ fi
+fi
+
+# see if we can hide zlib internal symbols that are linked between separate source files
+if test "$gcc" -eq 1; then
+ echo >> configure.log
+ cat > $test.c <> configure.log
+echo ALL = $ALL >> configure.log
+echo AR = $AR >> configure.log
+echo ARFLAGS = $ARFLAGS >> configure.log
+echo CC = $CC >> configure.log
+echo CFLAGS = $CFLAGS >> configure.log
+echo CPP = $CPP >> configure.log
+echo EXE = $EXE >> configure.log
+echo LDCONFIG = $LDCONFIG >> configure.log
+echo LDFLAGS = $LDFLAGS >> configure.log
+echo LDSHARED = $LDSHARED >> configure.log
+echo LDSHAREDLIBC = $LDSHAREDLIBC >> configure.log
+echo OBJC = $OBJC >> configure.log
+echo PIC_OBJC = $PIC_OBJC >> configure.log
+echo RANLIB = $RANLIB >> configure.log
+echo SFLAGS = $SFLAGS >> configure.log
+echo SHAREDLIB = $SHAREDLIB >> configure.log
+echo SHAREDLIBM = $SHAREDLIBM >> configure.log
+echo SHAREDLIBV = $SHAREDLIBV >> configure.log
+echo STATICLIB = $STATICLIB >> configure.log
+echo TEST = $TEST >> configure.log
+echo VER = $VER >> configure.log
+echo SRCDIR = $SRCDIR >> configure.log
+echo exec_prefix = $exec_prefix >> configure.log
+echo includedir = $includedir >> configure.log
+echo libdir = $libdir >> configure.log
+echo mandir = $mandir >> configure.log
+echo prefix = $prefix >> configure.log
+echo sharedlibdir = $sharedlibdir >> configure.log
+echo uname = $uname >> configure.log
+
+# udpate Makefile with the configure results
+sed < ${SRCDIR}Makefile.in "
+/^CC *=/s#=.*#=$CC#
+/^CFLAGS *=/s#=.*#=$CFLAGS#
+/^SFLAGS *=/s#=.*#=$SFLAGS#
+/^LDFLAGS *=/s#=.*#=$LDFLAGS#
+/^LDSHARED *=/s#=.*#=$LDSHARED#
+/^CPP *=/s#=.*#=$CPP#
+/^STATICLIB *=/s#=.*#=$STATICLIB#
+/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
+/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
+/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
+/^AR *=/s#=.*#=$AR#
+/^ARFLAGS *=/s#=.*#=$ARFLAGS#
+/^RANLIB *=/s#=.*#=$RANLIB#
+/^LDCONFIG *=/s#=.*#=$LDCONFIG#
+/^LDSHAREDLIBC *=/s#=.*#=$LDSHAREDLIBC#
+/^EXE *=/s#=.*#=$EXE#
+/^SRCDIR *=/s#=.*#=$SRCDIR#
+/^ZINC *=/s#=.*#=$ZINC#
+/^ZINCOUT *=/s#=.*#=$ZINCOUT#
+/^prefix *=/s#=.*#=$prefix#
+/^exec_prefix *=/s#=.*#=$exec_prefix#
+/^libdir *=/s#=.*#=$libdir#
+/^sharedlibdir *=/s#=.*#=$sharedlibdir#
+/^includedir *=/s#=.*#=$includedir#
+/^mandir *=/s#=.*#=$mandir#
+/^OBJC *=/s#=.*#= $OBJC#
+/^PIC_OBJC *=/s#=.*#= $PIC_OBJC#
+/^all: */s#:.*#: $ALL#
+/^test: */s#:.*#: $TEST#
+" > Makefile
+
+# create zlib.pc with the configure results
+sed < ${SRCDIR}zlib.pc.in "
+/^CC *=/s#=.*#=$CC#
+/^CFLAGS *=/s#=.*#=$CFLAGS#
+/^CPP *=/s#=.*#=$CPP#
+/^LDSHARED *=/s#=.*#=$LDSHARED#
+/^STATICLIB *=/s#=.*#=$STATICLIB#
+/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
+/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
+/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
+/^AR *=/s#=.*#=$AR#
+/^ARFLAGS *=/s#=.*#=$ARFLAGS#
+/^RANLIB *=/s#=.*#=$RANLIB#
+/^EXE *=/s#=.*#=$EXE#
+/^prefix *=/s#=.*#=$prefix#
+/^exec_prefix *=/s#=.*#=$exec_prefix#
+/^libdir *=/s#=.*#=$libdir#
+/^sharedlibdir *=/s#=.*#=$sharedlibdir#
+/^includedir *=/s#=.*#=$includedir#
+/^mandir *=/s#=.*#=$mandir#
+/^LDFLAGS *=/s#=.*#=$LDFLAGS#
+" | sed -e "
+s/\@VERSION\@/$VER/g;
+" > zlib.pc
+
+# done
+leave 0
ADDED compat/zlib/contrib/README.contrib
Index: compat/zlib/contrib/README.contrib
==================================================================
--- compat/zlib/contrib/README.contrib
+++ compat/zlib/contrib/README.contrib
@@ -0,0 +1,57 @@
+All files under this contrib directory are UNSUPPORTED. They were
+provided by users of zlib and were not tested by the authors of zlib.
+Use at your own risk. Please contact the authors of the contributions
+for help about these, not the zlib authors. Thanks.
+
+
+ada/ by Dmitriy Anisimkov
+ Support for Ada
+ See http://zlib-ada.sourceforge.net/
+
+blast/ by Mark Adler
+ Decompressor for output of PKWare Data Compression Library (DCL)
+
+delphi/ by Cosmin Truta
+ Support for Delphi and C++ Builder
+
+dotzlib/ by Henrik Ravn
+ Support for Microsoft .Net and Visual C++ .Net
+
+gcc_gvmat64/by Gilles Vollant
+ GCC Version of x86 64-bit (AMD64 and Intel EM64t) code for x64
+ assembler to replace longest_match() and inflate_fast()
+
+infback9/ by Mark Adler
+ Unsupported diffs to infback to decode the deflate64 format
+
+iostream/ by Kevin Ruland
+ A C++ I/O streams interface to the zlib gz* functions
+
+iostream2/ by Tyge Løvset
+ Another C++ I/O streams interface
+
+iostream3/ by Ludwig Schwardt
+ and Kevin Ruland
+ Yet another C++ I/O streams interface
+
+minizip/ by Gilles Vollant
+ Mini zip and unzip based on zlib
+ Includes Zip64 support by Mathias Svensson
+ See http://www.winimage.com/zLibDll/minizip.html
+
+pascal/ by Bob Dellaca et al.
+ Support for Pascal
+
+puff/ by Mark Adler
+ Small, low memory usage inflate. Also serves to provide an
+ unambiguous description of the deflate format.
+
+testzlib/ by Gilles Vollant
+ Example of the use of zlib
+
+untgz/ by Pedro A. Aranda Gutierrez
+ A very simple tar.gz file extractor using zlib
+
+vstudio/ by Gilles Vollant
+ Building a minizip-enhanced zlib with Microsoft Visual Studio
+ Includes vc11 from kreuzerkrieg and vc12 from davispuh
ADDED compat/zlib/contrib/blast/Makefile
Index: compat/zlib/contrib/blast/Makefile
==================================================================
--- compat/zlib/contrib/blast/Makefile
+++ compat/zlib/contrib/blast/Makefile
@@ -0,0 +1,8 @@
+blast: blast.c blast.h
+ cc -DTEST -o blast blast.c
+
+test: blast
+ blast < test.pk | cmp - test.txt
+
+clean:
+ rm -f blast blast.o
ADDED compat/zlib/contrib/blast/README
Index: compat/zlib/contrib/blast/README
==================================================================
--- compat/zlib/contrib/blast/README
+++ compat/zlib/contrib/blast/README
@@ -0,0 +1,4 @@
+Read blast.h for purpose and usage.
+
+Mark Adler
+madler@alumni.caltech.edu
ADDED compat/zlib/contrib/blast/blast.c
Index: compat/zlib/contrib/blast/blast.c
==================================================================
--- compat/zlib/contrib/blast/blast.c
+++ compat/zlib/contrib/blast/blast.c
@@ -0,0 +1,466 @@
+/* blast.c
+ * Copyright (C) 2003, 2012, 2013 Mark Adler
+ * For conditions of distribution and use, see copyright notice in blast.h
+ * version 1.3, 24 Aug 2013
+ *
+ * blast.c decompresses data compressed by the PKWare Compression Library.
+ * This function provides functionality similar to the explode() function of
+ * the PKWare library, hence the name "blast".
+ *
+ * This decompressor is based on the excellent format description provided by
+ * Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the
+ * example Ben provided in the post is incorrect. The distance 110001 should
+ * instead be 111000. When corrected, the example byte stream becomes:
+ *
+ * 00 04 82 24 25 8f 80 7f
+ *
+ * which decompresses to "AIAIAIAIAIAIA" (without the quotes).
+ */
+
+/*
+ * Change history:
+ *
+ * 1.0 12 Feb 2003 - First version
+ * 1.1 16 Feb 2003 - Fixed distance check for > 4 GB uncompressed data
+ * 1.2 24 Oct 2012 - Add note about using binary mode in stdio
+ * - Fix comparisons of differently signed integers
+ * 1.3 24 Aug 2013 - Return unused input from blast()
+ * - Fix test code to correctly report unused input
+ * - Enable the provision of initial input to blast()
+ */
+
+#include /* for NULL */
+#include /* for setjmp(), longjmp(), and jmp_buf */
+#include "blast.h" /* prototype for blast() */
+
+#define local static /* for local function definitions */
+#define MAXBITS 13 /* maximum code length */
+#define MAXWIN 4096 /* maximum window size */
+
+/* input and output state */
+struct state {
+ /* input state */
+ blast_in infun; /* input function provided by user */
+ void *inhow; /* opaque information passed to infun() */
+ unsigned char *in; /* next input location */
+ unsigned left; /* available input at in */
+ int bitbuf; /* bit buffer */
+ int bitcnt; /* number of bits in bit buffer */
+
+ /* input limit error return state for bits() and decode() */
+ jmp_buf env;
+
+ /* output state */
+ blast_out outfun; /* output function provided by user */
+ void *outhow; /* opaque information passed to outfun() */
+ unsigned next; /* index of next write location in out[] */
+ int first; /* true to check distances (for first 4K) */
+ unsigned char out[MAXWIN]; /* output buffer and sliding window */
+};
+
+/*
+ * Return need bits from the input stream. This always leaves less than
+ * eight bits in the buffer. bits() works properly for need == 0.
+ *
+ * Format notes:
+ *
+ * - Bits are stored in bytes from the least significant bit to the most
+ * significant bit. Therefore bits are dropped from the bottom of the bit
+ * buffer, using shift right, and new bytes are appended to the top of the
+ * bit buffer, using shift left.
+ */
+local int bits(struct state *s, int need)
+{
+ int val; /* bit accumulator */
+
+ /* load at least need bits into val */
+ val = s->bitbuf;
+ while (s->bitcnt < need) {
+ if (s->left == 0) {
+ s->left = s->infun(s->inhow, &(s->in));
+ if (s->left == 0) longjmp(s->env, 1); /* out of input */
+ }
+ val |= (int)(*(s->in)++) << s->bitcnt; /* load eight bits */
+ s->left--;
+ s->bitcnt += 8;
+ }
+
+ /* drop need bits and update buffer, always zero to seven bits left */
+ s->bitbuf = val >> need;
+ s->bitcnt -= need;
+
+ /* return need bits, zeroing the bits above that */
+ return val & ((1 << need) - 1);
+}
+
+/*
+ * Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of
+ * each length, which for a canonical code are stepped through in order.
+ * symbol[] are the symbol values in canonical order, where the number of
+ * entries is the sum of the counts in count[]. The decoding process can be
+ * seen in the function decode() below.
+ */
+struct huffman {
+ short *count; /* number of symbols of each length */
+ short *symbol; /* canonically ordered symbols */
+};
+
+/*
+ * Decode a code from the stream s using huffman table h. Return the symbol or
+ * a negative value if there is an error. If all of the lengths are zero, i.e.
+ * an empty code, or if the code is incomplete and an invalid code is received,
+ * then -9 is returned after reading MAXBITS bits.
+ *
+ * Format notes:
+ *
+ * - The codes as stored in the compressed data are bit-reversed relative to
+ * a simple integer ordering of codes of the same lengths. Hence below the
+ * bits are pulled from the compressed data one at a time and used to
+ * build the code value reversed from what is in the stream in order to
+ * permit simple integer comparisons for decoding.
+ *
+ * - The first code for the shortest length is all ones. Subsequent codes of
+ * the same length are simply integer decrements of the previous code. When
+ * moving up a length, a one bit is appended to the code. For a complete
+ * code, the last code of the longest length will be all zeros. To support
+ * this ordering, the bits pulled during decoding are inverted to apply the
+ * more "natural" ordering starting with all zeros and incrementing.
+ */
+local int decode(struct state *s, struct huffman *h)
+{
+ int len; /* current number of bits in code */
+ int code; /* len bits being decoded */
+ int first; /* first code of length len */
+ int count; /* number of codes of length len */
+ int index; /* index of first code of length len in symbol table */
+ int bitbuf; /* bits from stream */
+ int left; /* bits left in next or left to process */
+ short *next; /* next number of codes */
+
+ bitbuf = s->bitbuf;
+ left = s->bitcnt;
+ code = first = index = 0;
+ len = 1;
+ next = h->count + 1;
+ while (1) {
+ while (left--) {
+ code |= (bitbuf & 1) ^ 1; /* invert code */
+ bitbuf >>= 1;
+ count = *next++;
+ if (code < first + count) { /* if length len, return symbol */
+ s->bitbuf = bitbuf;
+ s->bitcnt = (s->bitcnt - len) & 7;
+ return h->symbol[index + (code - first)];
+ }
+ index += count; /* else update for next length */
+ first += count;
+ first <<= 1;
+ code <<= 1;
+ len++;
+ }
+ left = (MAXBITS+1) - len;
+ if (left == 0) break;
+ if (s->left == 0) {
+ s->left = s->infun(s->inhow, &(s->in));
+ if (s->left == 0) longjmp(s->env, 1); /* out of input */
+ }
+ bitbuf = *(s->in)++;
+ s->left--;
+ if (left > 8) left = 8;
+ }
+ return -9; /* ran out of codes */
+}
+
+/*
+ * Given a list of repeated code lengths rep[0..n-1], where each byte is a
+ * count (high four bits + 1) and a code length (low four bits), generate the
+ * list of code lengths. This compaction reduces the size of the object code.
+ * Then given the list of code lengths length[0..n-1] representing a canonical
+ * Huffman code for n symbols, construct the tables required to decode those
+ * codes. Those tables are the number of codes of each length, and the symbols
+ * sorted by length, retaining their original order within each length. The
+ * return value is zero for a complete code set, negative for an over-
+ * subscribed code set, and positive for an incomplete code set. The tables
+ * can be used if the return value is zero or positive, but they cannot be used
+ * if the return value is negative. If the return value is zero, it is not
+ * possible for decode() using that table to return an error--any stream of
+ * enough bits will resolve to a symbol. If the return value is positive, then
+ * it is possible for decode() using that table to return an error for received
+ * codes past the end of the incomplete lengths.
+ */
+local int construct(struct huffman *h, const unsigned char *rep, int n)
+{
+ int symbol; /* current symbol when stepping through length[] */
+ int len; /* current length when stepping through h->count[] */
+ int left; /* number of possible codes left of current length */
+ short offs[MAXBITS+1]; /* offsets in symbol table for each length */
+ short length[256]; /* code lengths */
+
+ /* convert compact repeat counts into symbol bit length list */
+ symbol = 0;
+ do {
+ len = *rep++;
+ left = (len >> 4) + 1;
+ len &= 15;
+ do {
+ length[symbol++] = len;
+ } while (--left);
+ } while (--n);
+ n = symbol;
+
+ /* count number of codes of each length */
+ for (len = 0; len <= MAXBITS; len++)
+ h->count[len] = 0;
+ for (symbol = 0; symbol < n; symbol++)
+ (h->count[length[symbol]])++; /* assumes lengths are within bounds */
+ if (h->count[0] == n) /* no codes! */
+ return 0; /* complete, but decode() will fail */
+
+ /* check for an over-subscribed or incomplete set of lengths */
+ left = 1; /* one possible code of zero length */
+ for (len = 1; len <= MAXBITS; len++) {
+ left <<= 1; /* one more bit, double codes left */
+ left -= h->count[len]; /* deduct count from possible codes */
+ if (left < 0) return left; /* over-subscribed--return negative */
+ } /* left > 0 means incomplete */
+
+ /* generate offsets into symbol table for each length for sorting */
+ offs[1] = 0;
+ for (len = 1; len < MAXBITS; len++)
+ offs[len + 1] = offs[len] + h->count[len];
+
+ /*
+ * put symbols in table sorted by length, by symbol order within each
+ * length
+ */
+ for (symbol = 0; symbol < n; symbol++)
+ if (length[symbol] != 0)
+ h->symbol[offs[length[symbol]]++] = symbol;
+
+ /* return zero for complete set, positive for incomplete set */
+ return left;
+}
+
+/*
+ * Decode PKWare Compression Library stream.
+ *
+ * Format notes:
+ *
+ * - First byte is 0 if literals are uncoded or 1 if they are coded. Second
+ * byte is 4, 5, or 6 for the number of extra bits in the distance code.
+ * This is the base-2 logarithm of the dictionary size minus six.
+ *
+ * - Compressed data is a combination of literals and length/distance pairs
+ * terminated by an end code. Literals are either Huffman coded or
+ * uncoded bytes. A length/distance pair is a coded length followed by a
+ * coded distance to represent a string that occurs earlier in the
+ * uncompressed data that occurs again at the current location.
+ *
+ * - A bit preceding a literal or length/distance pair indicates which comes
+ * next, 0 for literals, 1 for length/distance.
+ *
+ * - If literals are uncoded, then the next eight bits are the literal, in the
+ * normal bit order in the stream, i.e. no bit-reversal is needed. Similarly,
+ * no bit reversal is needed for either the length extra bits or the distance
+ * extra bits.
+ *
+ * - Literal bytes are simply written to the output. A length/distance pair is
+ * an instruction to copy previously uncompressed bytes to the output. The
+ * copy is from distance bytes back in the output stream, copying for length
+ * bytes.
+ *
+ * - Distances pointing before the beginning of the output data are not
+ * permitted.
+ *
+ * - Overlapped copies, where the length is greater than the distance, are
+ * allowed and common. For example, a distance of one and a length of 518
+ * simply copies the last byte 518 times. A distance of four and a length of
+ * twelve copies the last four bytes three times. A simple forward copy
+ * ignoring whether the length is greater than the distance or not implements
+ * this correctly.
+ */
+local int decomp(struct state *s)
+{
+ int lit; /* true if literals are coded */
+ int dict; /* log2(dictionary size) - 6 */
+ int symbol; /* decoded symbol, extra bits for distance */
+ int len; /* length for copy */
+ unsigned dist; /* distance for copy */
+ int copy; /* copy counter */
+ unsigned char *from, *to; /* copy pointers */
+ static int virgin = 1; /* build tables once */
+ static short litcnt[MAXBITS+1], litsym[256]; /* litcode memory */
+ static short lencnt[MAXBITS+1], lensym[16]; /* lencode memory */
+ static short distcnt[MAXBITS+1], distsym[64]; /* distcode memory */
+ static struct huffman litcode = {litcnt, litsym}; /* length code */
+ static struct huffman lencode = {lencnt, lensym}; /* length code */
+ static struct huffman distcode = {distcnt, distsym};/* distance code */
+ /* bit lengths of literal codes */
+ static const unsigned char litlen[] = {
+ 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8,
+ 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5,
+ 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12,
+ 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27,
+ 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45,
+ 44, 173};
+ /* bit lengths of length codes 0..15 */
+ static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23};
+ /* bit lengths of distance codes 0..63 */
+ static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248};
+ static const short base[16] = { /* base for length codes */
+ 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264};
+ static const char extra[16] = { /* extra bits for length codes */
+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8};
+
+ /* set up decoding tables (once--might not be thread-safe) */
+ if (virgin) {
+ construct(&litcode, litlen, sizeof(litlen));
+ construct(&lencode, lenlen, sizeof(lenlen));
+ construct(&distcode, distlen, sizeof(distlen));
+ virgin = 0;
+ }
+
+ /* read header */
+ lit = bits(s, 8);
+ if (lit > 1) return -1;
+ dict = bits(s, 8);
+ if (dict < 4 || dict > 6) return -2;
+
+ /* decode literals and length/distance pairs */
+ do {
+ if (bits(s, 1)) {
+ /* get length */
+ symbol = decode(s, &lencode);
+ len = base[symbol] + bits(s, extra[symbol]);
+ if (len == 519) break; /* end code */
+
+ /* get distance */
+ symbol = len == 2 ? 2 : dict;
+ dist = decode(s, &distcode) << symbol;
+ dist += bits(s, symbol);
+ dist++;
+ if (s->first && dist > s->next)
+ return -3; /* distance too far back */
+
+ /* copy length bytes from distance bytes back */
+ do {
+ to = s->out + s->next;
+ from = to - dist;
+ copy = MAXWIN;
+ if (s->next < dist) {
+ from += copy;
+ copy = dist;
+ }
+ copy -= s->next;
+ if (copy > len) copy = len;
+ len -= copy;
+ s->next += copy;
+ do {
+ *to++ = *from++;
+ } while (--copy);
+ if (s->next == MAXWIN) {
+ if (s->outfun(s->outhow, s->out, s->next)) return 1;
+ s->next = 0;
+ s->first = 0;
+ }
+ } while (len != 0);
+ }
+ else {
+ /* get literal and write it */
+ symbol = lit ? decode(s, &litcode) : bits(s, 8);
+ s->out[s->next++] = symbol;
+ if (s->next == MAXWIN) {
+ if (s->outfun(s->outhow, s->out, s->next)) return 1;
+ s->next = 0;
+ s->first = 0;
+ }
+ }
+ } while (1);
+ return 0;
+}
+
+/* See comments in blast.h */
+int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow,
+ unsigned *left, unsigned char **in)
+{
+ struct state s; /* input/output state */
+ int err; /* return value */
+
+ /* initialize input state */
+ s.infun = infun;
+ s.inhow = inhow;
+ if (left != NULL && *left) {
+ s.left = *left;
+ s.in = *in;
+ }
+ else
+ s.left = 0;
+ s.bitbuf = 0;
+ s.bitcnt = 0;
+
+ /* initialize output state */
+ s.outfun = outfun;
+ s.outhow = outhow;
+ s.next = 0;
+ s.first = 1;
+
+ /* return if bits() or decode() tries to read past available input */
+ if (setjmp(s.env) != 0) /* if came back here via longjmp(), */
+ err = 2; /* then skip decomp(), return error */
+ else
+ err = decomp(&s); /* decompress */
+
+ /* return unused input */
+ if (left != NULL)
+ *left = s.left;
+ if (in != NULL)
+ *in = s.left ? s.in : NULL;
+
+ /* write any leftover output and update the error code if needed */
+ if (err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0)
+ err = 1;
+ return err;
+}
+
+#ifdef TEST
+/* Example of how to use blast() */
+#include
+#include
+
+#define CHUNK 16384
+
+local unsigned inf(void *how, unsigned char **buf)
+{
+ static unsigned char hold[CHUNK];
+
+ *buf = hold;
+ return fread(hold, 1, CHUNK, (FILE *)how);
+}
+
+local int outf(void *how, unsigned char *buf, unsigned len)
+{
+ return fwrite(buf, 1, len, (FILE *)how) != len;
+}
+
+/* Decompress a PKWare Compression Library stream from stdin to stdout */
+int main(void)
+{
+ int ret;
+ unsigned left;
+
+ /* decompress to stdout */
+ left = 0;
+ ret = blast(inf, stdin, outf, stdout, &left, NULL);
+ if (ret != 0)
+ fprintf(stderr, "blast error: %d\n", ret);
+
+ /* count any leftover bytes */
+ while (getchar() != EOF)
+ left++;
+ if (left)
+ fprintf(stderr, "blast warning: %u unused bytes of input\n", left);
+
+ /* return blast() error code */
+ return ret;
+}
+#endif
ADDED compat/zlib/contrib/blast/blast.h
Index: compat/zlib/contrib/blast/blast.h
==================================================================
--- compat/zlib/contrib/blast/blast.h
+++ compat/zlib/contrib/blast/blast.h
@@ -0,0 +1,83 @@
+/* blast.h -- interface for blast.c
+ Copyright (C) 2003, 2012, 2013 Mark Adler
+ version 1.3, 24 Aug 2013
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the author be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Mark Adler madler@alumni.caltech.edu
+ */
+
+
+/*
+ * blast() decompresses the PKWare Data Compression Library (DCL) compressed
+ * format. It provides the same functionality as the explode() function in
+ * that library. (Note: PKWare overused the "implode" verb, and the format
+ * used by their library implode() function is completely different and
+ * incompatible with the implode compression method supported by PKZIP.)
+ *
+ * The binary mode for stdio functions should be used to assure that the
+ * compressed data is not corrupted when read or written. For example:
+ * fopen(..., "rb") and fopen(..., "wb").
+ */
+
+
+typedef unsigned (*blast_in)(void *how, unsigned char **buf);
+typedef int (*blast_out)(void *how, unsigned char *buf, unsigned len);
+/* Definitions for input/output functions passed to blast(). See below for
+ * what the provided functions need to do.
+ */
+
+
+int blast(blast_in infun, void *inhow, blast_out outfun, void *outhow,
+ unsigned *left, unsigned char **in);
+/* Decompress input to output using the provided infun() and outfun() calls.
+ * On success, the return value of blast() is zero. If there is an error in
+ * the source data, i.e. it is not in the proper format, then a negative value
+ * is returned. If there is not enough input available or there is not enough
+ * output space, then a positive error is returned.
+ *
+ * The input function is invoked: len = infun(how, &buf), where buf is set by
+ * infun() to point to the input buffer, and infun() returns the number of
+ * available bytes there. If infun() returns zero, then blast() returns with
+ * an input error. (blast() only asks for input if it needs it.) inhow is for
+ * use by the application to pass an input descriptor to infun(), if desired.
+ *
+ * If left and in are not NULL and *left is not zero when blast() is called,
+ * then the *left bytes at *in are consumed for input before infun() is used.
+ *
+ * The output function is invoked: err = outfun(how, buf, len), where the bytes
+ * to be written are buf[0..len-1]. If err is not zero, then blast() returns
+ * with an output error. outfun() is always called with len <= 4096. outhow
+ * is for use by the application to pass an output descriptor to outfun(), if
+ * desired.
+ *
+ * If there is any unused input, *left is set to the number of bytes that were
+ * read and *in points to them. Otherwise *left is set to zero and *in is set
+ * to NULL. If left or in are NULL, then they are not set.
+ *
+ * The return codes are:
+ *
+ * 2: ran out of input before completing decompression
+ * 1: output error before completing decompression
+ * 0: successful decompression
+ * -1: literal flag not zero or one
+ * -2: dictionary size not in 4..6
+ * -3: distance is too far back
+ *
+ * At the bottom of blast.c is an example program that uses blast() that can be
+ * compiled to produce a command-line decompression filter by defining TEST.
+ */
ADDED compat/zlib/contrib/blast/test.pk
Index: compat/zlib/contrib/blast/test.pk
==================================================================
--- compat/zlib/contrib/blast/test.pk
+++ compat/zlib/contrib/blast/test.pk
cannot compute difference between binary files
ADDED compat/zlib/contrib/blast/test.txt
Index: compat/zlib/contrib/blast/test.txt
==================================================================
--- compat/zlib/contrib/blast/test.txt
+++ compat/zlib/contrib/blast/test.txt
@@ -0,0 +1,1 @@
+AIAIAIAIAIAIA
ADDED compat/zlib/contrib/delphi/ZLib.pas
Index: compat/zlib/contrib/delphi/ZLib.pas
==================================================================
--- compat/zlib/contrib/delphi/ZLib.pas
+++ compat/zlib/contrib/delphi/ZLib.pas
@@ -0,0 +1,557 @@
+{*******************************************************}
+{ }
+{ Borland Delphi Supplemental Components }
+{ ZLIB Data Compression Interface Unit }
+{ }
+{ Copyright (c) 1997,99 Borland Corporation }
+{ }
+{*******************************************************}
+
+{ Updated for zlib 1.2.x by Cosmin Truta }
+
+unit ZLib;
+
+interface
+
+uses SysUtils, Classes;
+
+type
+ TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer; cdecl;
+ TFree = procedure (AppData, Block: Pointer); cdecl;
+
+ // Internal structure. Ignore.
+ TZStreamRec = packed record
+ next_in: PChar; // next input byte
+ avail_in: Integer; // number of bytes available at next_in
+ total_in: Longint; // total nb of input bytes read so far
+
+ next_out: PChar; // next output byte should be put here
+ avail_out: Integer; // remaining free space at next_out
+ total_out: Longint; // total nb of bytes output so far
+
+ msg: PChar; // last error message, NULL if no error
+ internal: Pointer; // not visible by applications
+
+ zalloc: TAlloc; // used to allocate the internal state
+ zfree: TFree; // used to free the internal state
+ AppData: Pointer; // private data object passed to zalloc and zfree
+
+ data_type: Integer; // best guess about the data type: ascii or binary
+ adler: Longint; // adler32 value of the uncompressed data
+ reserved: Longint; // reserved for future use
+ end;
+
+ // Abstract ancestor class
+ TCustomZlibStream = class(TStream)
+ private
+ FStrm: TStream;
+ FStrmPos: Integer;
+ FOnProgress: TNotifyEvent;
+ FZRec: TZStreamRec;
+ FBuffer: array [Word] of Char;
+ protected
+ procedure Progress(Sender: TObject); dynamic;
+ property OnProgress: TNotifyEvent read FOnProgress write FOnProgress;
+ constructor Create(Strm: TStream);
+ end;
+
+{ TCompressionStream compresses data on the fly as data is written to it, and
+ stores the compressed data to another stream.
+
+ TCompressionStream is write-only and strictly sequential. Reading from the
+ stream will raise an exception. Using Seek to move the stream pointer
+ will raise an exception.
+
+ Output data is cached internally, written to the output stream only when
+ the internal output buffer is full. All pending output data is flushed
+ when the stream is destroyed.
+
+ The Position property returns the number of uncompressed bytes of
+ data that have been written to the stream so far.
+
+ CompressionRate returns the on-the-fly percentage by which the original
+ data has been compressed: (1 - (CompressedBytes / UncompressedBytes)) * 100
+ If raw data size = 100 and compressed data size = 25, the CompressionRate
+ is 75%
+
+ The OnProgress event is called each time the output buffer is filled and
+ written to the output stream. This is useful for updating a progress
+ indicator when you are writing a large chunk of data to the compression
+ stream in a single call.}
+
+
+ TCompressionLevel = (clNone, clFastest, clDefault, clMax);
+
+ TCompressionStream = class(TCustomZlibStream)
+ private
+ function GetCompressionRate: Single;
+ public
+ constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream);
+ destructor Destroy; override;
+ function Read(var Buffer; Count: Longint): Longint; override;
+ function Write(const Buffer; Count: Longint): Longint; override;
+ function Seek(Offset: Longint; Origin: Word): Longint; override;
+ property CompressionRate: Single read GetCompressionRate;
+ property OnProgress;
+ end;
+
+{ TDecompressionStream decompresses data on the fly as data is read from it.
+
+ Compressed data comes from a separate source stream. TDecompressionStream
+ is read-only and unidirectional; you can seek forward in the stream, but not
+ backwards. The special case of setting the stream position to zero is
+ allowed. Seeking forward decompresses data until the requested position in
+ the uncompressed data has been reached. Seeking backwards, seeking relative
+ to the end of the stream, requesting the size of the stream, and writing to
+ the stream will raise an exception.
+
+ The Position property returns the number of bytes of uncompressed data that
+ have been read from the stream so far.
+
+ The OnProgress event is called each time the internal input buffer of
+ compressed data is exhausted and the next block is read from the input stream.
+ This is useful for updating a progress indicator when you are reading a
+ large chunk of data from the decompression stream in a single call.}
+
+ TDecompressionStream = class(TCustomZlibStream)
+ public
+ constructor Create(Source: TStream);
+ destructor Destroy; override;
+ function Read(var Buffer; Count: Longint): Longint; override;
+ function Write(const Buffer; Count: Longint): Longint; override;
+ function Seek(Offset: Longint; Origin: Word): Longint; override;
+ property OnProgress;
+ end;
+
+
+
+{ CompressBuf compresses data, buffer to buffer, in one call.
+ In: InBuf = ptr to compressed data
+ InBytes = number of bytes in InBuf
+ Out: OutBuf = ptr to newly allocated buffer containing decompressed data
+ OutBytes = number of bytes in OutBuf }
+procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
+ out OutBuf: Pointer; out OutBytes: Integer);
+
+
+{ DecompressBuf decompresses data, buffer to buffer, in one call.
+ In: InBuf = ptr to compressed data
+ InBytes = number of bytes in InBuf
+ OutEstimate = zero, or est. size of the decompressed data
+ Out: OutBuf = ptr to newly allocated buffer containing decompressed data
+ OutBytes = number of bytes in OutBuf }
+procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
+ OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
+
+{ DecompressToUserBuf decompresses data, buffer to buffer, in one call.
+ In: InBuf = ptr to compressed data
+ InBytes = number of bytes in InBuf
+ Out: OutBuf = ptr to user-allocated buffer to contain decompressed data
+ BufSize = number of bytes in OutBuf }
+procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer;
+ const OutBuf: Pointer; BufSize: Integer);
+
+const
+ zlib_version = '1.2.13';
+
+type
+ EZlibError = class(Exception);
+ ECompressionError = class(EZlibError);
+ EDecompressionError = class(EZlibError);
+
+implementation
+
+uses ZLibConst;
+
+const
+ Z_NO_FLUSH = 0;
+ Z_PARTIAL_FLUSH = 1;
+ Z_SYNC_FLUSH = 2;
+ Z_FULL_FLUSH = 3;
+ Z_FINISH = 4;
+
+ Z_OK = 0;
+ Z_STREAM_END = 1;
+ Z_NEED_DICT = 2;
+ Z_ERRNO = (-1);
+ Z_STREAM_ERROR = (-2);
+ Z_DATA_ERROR = (-3);
+ Z_MEM_ERROR = (-4);
+ Z_BUF_ERROR = (-5);
+ Z_VERSION_ERROR = (-6);
+
+ Z_NO_COMPRESSION = 0;
+ Z_BEST_SPEED = 1;
+ Z_BEST_COMPRESSION = 9;
+ Z_DEFAULT_COMPRESSION = (-1);
+
+ Z_FILTERED = 1;
+ Z_HUFFMAN_ONLY = 2;
+ Z_RLE = 3;
+ Z_DEFAULT_STRATEGY = 0;
+
+ Z_BINARY = 0;
+ Z_ASCII = 1;
+ Z_UNKNOWN = 2;
+
+ Z_DEFLATED = 8;
+
+
+{$L adler32.obj}
+{$L compress.obj}
+{$L crc32.obj}
+{$L deflate.obj}
+{$L infback.obj}
+{$L inffast.obj}
+{$L inflate.obj}
+{$L inftrees.obj}
+{$L trees.obj}
+{$L uncompr.obj}
+{$L zutil.obj}
+
+procedure adler32; external;
+procedure compressBound; external;
+procedure crc32; external;
+procedure deflateInit2_; external;
+procedure deflateParams; external;
+
+function _malloc(Size: Integer): Pointer; cdecl;
+begin
+ Result := AllocMem(Size);
+end;
+
+procedure _free(Block: Pointer); cdecl;
+begin
+ FreeMem(Block);
+end;
+
+procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl;
+begin
+ FillChar(P^, count, B);
+end;
+
+procedure _memcpy(dest, source: Pointer; count: Integer); cdecl;
+begin
+ Move(source^, dest^, count);
+end;
+
+
+
+// deflate compresses data
+function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar;
+ recsize: Integer): Integer; external;
+function deflate(var strm: TZStreamRec; flush: Integer): Integer; external;
+function deflateEnd(var strm: TZStreamRec): Integer; external;
+
+// inflate decompresses data
+function inflateInit_(var strm: TZStreamRec; version: PChar;
+ recsize: Integer): Integer; external;
+function inflate(var strm: TZStreamRec; flush: Integer): Integer; external;
+function inflateEnd(var strm: TZStreamRec): Integer; external;
+function inflateReset(var strm: TZStreamRec): Integer; external;
+
+
+function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl;
+begin
+// GetMem(Result, Items*Size);
+ Result := AllocMem(Items * Size);
+end;
+
+procedure zlibFreeMem(AppData, Block: Pointer); cdecl;
+begin
+ FreeMem(Block);
+end;
+
+{function zlibCheck(code: Integer): Integer;
+begin
+ Result := code;
+ if code < 0 then
+ raise EZlibError.Create('error'); //!!
+end;}
+
+function CCheck(code: Integer): Integer;
+begin
+ Result := code;
+ if code < 0 then
+ raise ECompressionError.Create('error'); //!!
+end;
+
+function DCheck(code: Integer): Integer;
+begin
+ Result := code;
+ if code < 0 then
+ raise EDecompressionError.Create('error'); //!!
+end;
+
+procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
+ out OutBuf: Pointer; out OutBytes: Integer);
+var
+ strm: TZStreamRec;
+ P: Pointer;
+begin
+ FillChar(strm, sizeof(strm), 0);
+ strm.zalloc := zlibAllocMem;
+ strm.zfree := zlibFreeMem;
+ OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255;
+ GetMem(OutBuf, OutBytes);
+ try
+ strm.next_in := InBuf;
+ strm.avail_in := InBytes;
+ strm.next_out := OutBuf;
+ strm.avail_out := OutBytes;
+ CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm)));
+ try
+ while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do
+ begin
+ P := OutBuf;
+ Inc(OutBytes, 256);
+ ReallocMem(OutBuf, OutBytes);
+ strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
+ strm.avail_out := 256;
+ end;
+ finally
+ CCheck(deflateEnd(strm));
+ end;
+ ReallocMem(OutBuf, strm.total_out);
+ OutBytes := strm.total_out;
+ except
+ FreeMem(OutBuf);
+ raise
+ end;
+end;
+
+
+procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
+ OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
+var
+ strm: TZStreamRec;
+ P: Pointer;
+ BufInc: Integer;
+begin
+ FillChar(strm, sizeof(strm), 0);
+ strm.zalloc := zlibAllocMem;
+ strm.zfree := zlibFreeMem;
+ BufInc := (InBytes + 255) and not 255;
+ if OutEstimate = 0 then
+ OutBytes := BufInc
+ else
+ OutBytes := OutEstimate;
+ GetMem(OutBuf, OutBytes);
+ try
+ strm.next_in := InBuf;
+ strm.avail_in := InBytes;
+ strm.next_out := OutBuf;
+ strm.avail_out := OutBytes;
+ DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
+ try
+ while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do
+ begin
+ P := OutBuf;
+ Inc(OutBytes, BufInc);
+ ReallocMem(OutBuf, OutBytes);
+ strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
+ strm.avail_out := BufInc;
+ end;
+ finally
+ DCheck(inflateEnd(strm));
+ end;
+ ReallocMem(OutBuf, strm.total_out);
+ OutBytes := strm.total_out;
+ except
+ FreeMem(OutBuf);
+ raise
+ end;
+end;
+
+procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer;
+ const OutBuf: Pointer; BufSize: Integer);
+var
+ strm: TZStreamRec;
+begin
+ FillChar(strm, sizeof(strm), 0);
+ strm.zalloc := zlibAllocMem;
+ strm.zfree := zlibFreeMem;
+ strm.next_in := InBuf;
+ strm.avail_in := InBytes;
+ strm.next_out := OutBuf;
+ strm.avail_out := BufSize;
+ DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
+ try
+ if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then
+ raise EZlibError.CreateRes(@sTargetBufferTooSmall);
+ finally
+ DCheck(inflateEnd(strm));
+ end;
+end;
+
+// TCustomZlibStream
+
+constructor TCustomZLibStream.Create(Strm: TStream);
+begin
+ inherited Create;
+ FStrm := Strm;
+ FStrmPos := Strm.Position;
+ FZRec.zalloc := zlibAllocMem;
+ FZRec.zfree := zlibFreeMem;
+end;
+
+procedure TCustomZLibStream.Progress(Sender: TObject);
+begin
+ if Assigned(FOnProgress) then FOnProgress(Sender);
+end;
+
+
+// TCompressionStream
+
+constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel;
+ Dest: TStream);
+const
+ Levels: array [TCompressionLevel] of ShortInt =
+ (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION);
+begin
+ inherited Create(Dest);
+ FZRec.next_out := FBuffer;
+ FZRec.avail_out := sizeof(FBuffer);
+ CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec)));
+end;
+
+destructor TCompressionStream.Destroy;
+begin
+ FZRec.next_in := nil;
+ FZRec.avail_in := 0;
+ try
+ if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
+ while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END)
+ and (FZRec.avail_out = 0) do
+ begin
+ FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
+ FZRec.next_out := FBuffer;
+ FZRec.avail_out := sizeof(FBuffer);
+ end;
+ if FZRec.avail_out < sizeof(FBuffer) then
+ FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out);
+ finally
+ deflateEnd(FZRec);
+ end;
+ inherited Destroy;
+end;
+
+function TCompressionStream.Read(var Buffer; Count: Longint): Longint;
+begin
+ raise ECompressionError.CreateRes(@sInvalidStreamOp);
+end;
+
+function TCompressionStream.Write(const Buffer; Count: Longint): Longint;
+begin
+ FZRec.next_in := @Buffer;
+ FZRec.avail_in := Count;
+ if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
+ while (FZRec.avail_in > 0) do
+ begin
+ CCheck(deflate(FZRec, 0));
+ if FZRec.avail_out = 0 then
+ begin
+ FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
+ FZRec.next_out := FBuffer;
+ FZRec.avail_out := sizeof(FBuffer);
+ FStrmPos := FStrm.Position;
+ Progress(Self);
+ end;
+ end;
+ Result := Count;
+end;
+
+function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
+begin
+ if (Offset = 0) and (Origin = soFromCurrent) then
+ Result := FZRec.total_in
+ else
+ raise ECompressionError.CreateRes(@sInvalidStreamOp);
+end;
+
+function TCompressionStream.GetCompressionRate: Single;
+begin
+ if FZRec.total_in = 0 then
+ Result := 0
+ else
+ Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0;
+end;
+
+
+// TDecompressionStream
+
+constructor TDecompressionStream.Create(Source: TStream);
+begin
+ inherited Create(Source);
+ FZRec.next_in := FBuffer;
+ FZRec.avail_in := 0;
+ DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec)));
+end;
+
+destructor TDecompressionStream.Destroy;
+begin
+ FStrm.Seek(-FZRec.avail_in, 1);
+ inflateEnd(FZRec);
+ inherited Destroy;
+end;
+
+function TDecompressionStream.Read(var Buffer; Count: Longint): Longint;
+begin
+ FZRec.next_out := @Buffer;
+ FZRec.avail_out := Count;
+ if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
+ while (FZRec.avail_out > 0) do
+ begin
+ if FZRec.avail_in = 0 then
+ begin
+ FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer));
+ if FZRec.avail_in = 0 then
+ begin
+ Result := Count - FZRec.avail_out;
+ Exit;
+ end;
+ FZRec.next_in := FBuffer;
+ FStrmPos := FStrm.Position;
+ Progress(Self);
+ end;
+ CCheck(inflate(FZRec, 0));
+ end;
+ Result := Count;
+end;
+
+function TDecompressionStream.Write(const Buffer; Count: Longint): Longint;
+begin
+ raise EDecompressionError.CreateRes(@sInvalidStreamOp);
+end;
+
+function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
+var
+ I: Integer;
+ Buf: array [0..4095] of Char;
+begin
+ if (Offset = 0) and (Origin = soFromBeginning) then
+ begin
+ DCheck(inflateReset(FZRec));
+ FZRec.next_in := FBuffer;
+ FZRec.avail_in := 0;
+ FStrm.Position := 0;
+ FStrmPos := 0;
+ end
+ else if ( (Offset >= 0) and (Origin = soFromCurrent)) or
+ ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then
+ begin
+ if Origin = soFromBeginning then Dec(Offset, FZRec.total_out);
+ if Offset > 0 then
+ begin
+ for I := 1 to Offset div sizeof(Buf) do
+ ReadBuffer(Buf, sizeof(Buf));
+ ReadBuffer(Buf, Offset mod sizeof(Buf));
+ end;
+ end
+ else
+ raise EDecompressionError.CreateRes(@sInvalidStreamOp);
+ Result := FZRec.total_out;
+end;
+
+
+end.
ADDED compat/zlib/contrib/delphi/ZLibConst.pas
Index: compat/zlib/contrib/delphi/ZLibConst.pas
==================================================================
--- compat/zlib/contrib/delphi/ZLibConst.pas
+++ compat/zlib/contrib/delphi/ZLibConst.pas
@@ -0,0 +1,11 @@
+unit ZLibConst;
+
+interface
+
+resourcestring
+ sTargetBufferTooSmall = 'ZLib error: target buffer may be too small';
+ sInvalidStreamOp = 'Invalid stream operation';
+
+implementation
+
+end.
ADDED compat/zlib/contrib/delphi/readme.txt
Index: compat/zlib/contrib/delphi/readme.txt
==================================================================
--- compat/zlib/contrib/delphi/readme.txt
+++ compat/zlib/contrib/delphi/readme.txt
@@ -0,0 +1,76 @@
+
+Overview
+========
+
+This directory contains an update to the ZLib interface unit,
+distributed by Borland as a Delphi supplemental component.
+
+The original ZLib unit is Copyright (c) 1997,99 Borland Corp.,
+and is based on zlib version 1.0.4. There are a series of bugs
+and security problems associated with that old zlib version, and
+we recommend the users to update their ZLib unit.
+
+
+Summary of modifications
+========================
+
+- Improved makefile, adapted to zlib version 1.2.1.
+
+- Some field types from TZStreamRec are changed from Integer to
+ Longint, for consistency with the zlib.h header, and for 64-bit
+ readiness.
+
+- The zlib_version constant is updated.
+
+- The new Z_RLE strategy has its corresponding symbolic constant.
+
+- The allocation and deallocation functions and function types
+ (TAlloc, TFree, zlibAllocMem and zlibFreeMem) are now cdecl,
+ and _malloc and _free are added as C RTL stubs. As a result,
+ the original C sources of zlib can be compiled out of the box,
+ and linked to the ZLib unit.
+
+
+Suggestions for improvements
+============================
+
+Currently, the ZLib unit provides only a limited wrapper around
+the zlib library, and much of the original zlib functionality is
+missing. Handling compressed file formats like ZIP/GZIP or PNG
+cannot be implemented without having this functionality.
+Applications that handle these formats are either using their own,
+duplicated code, or not using the ZLib unit at all.
+
+Here are a few suggestions:
+
+- Checksum class wrappers around adler32() and crc32(), similar
+ to the Java classes that implement the java.util.zip.Checksum
+ interface.
+
+- The ability to read and write raw deflate streams, without the
+ zlib stream header and trailer. Raw deflate streams are used
+ in the ZIP file format.
+
+- The ability to read and write gzip streams, used in the GZIP
+ file format, and normally produced by the gzip program.
+
+- The ability to select a different compression strategy, useful
+ to PNG and MNG image compression, and to multimedia compression
+ in general. Besides the compression level
+
+ TCompressionLevel = (clNone, clFastest, clDefault, clMax);
+
+ which, in fact, could have used the 'z' prefix and avoided
+ TColor-like symbols
+
+ TCompressionLevel = (zcNone, zcFastest, zcDefault, zcMax);
+
+ there could be a compression strategy
+
+ TCompressionStrategy = (zsDefault, zsFiltered, zsHuffmanOnly, zsRle);
+
+- ZIP and GZIP stream handling via TStreams.
+
+
+--
+Cosmin Truta
ADDED compat/zlib/contrib/delphi/zlibd32.mak
Index: compat/zlib/contrib/delphi/zlibd32.mak
==================================================================
--- compat/zlib/contrib/delphi/zlibd32.mak
+++ compat/zlib/contrib/delphi/zlibd32.mak
@@ -0,0 +1,99 @@
+# Makefile for zlib
+# For use with Delphi and C++ Builder under Win32
+# Updated for zlib 1.2.x by Cosmin Truta
+
+# ------------ Borland C++ ------------
+
+# This project uses the Delphi (fastcall/register) calling convention:
+LOC = -DZEXPORT=__fastcall -DZEXPORTVA=__cdecl
+
+CC = bcc32
+LD = bcc32
+AR = tlib
+# do not use "-pr" in CFLAGS
+CFLAGS = -a -d -k- -O2 $(LOC)
+LDFLAGS =
+
+
+# variables
+ZLIB_LIB = zlib.lib
+
+OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzlib.obj gzread.obj
+OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
+OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzlib.obj+gzread.obj
+OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
+
+
+# targets
+all: $(ZLIB_LIB) example.exe minigzip.exe
+
+.c.obj:
+ $(CC) -c $(CFLAGS) $*.c
+
+adler32.obj: adler32.c zlib.h zconf.h
+
+compress.obj: compress.c zlib.h zconf.h
+
+crc32.obj: crc32.c zlib.h zconf.h crc32.h
+
+deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
+
+gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
+
+gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
+
+gzread.obj: gzread.c zlib.h zconf.h gzguts.h
+
+gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
+
+infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inffast.obj: inffast.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h
+
+inflate.obj: inflate.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
+ inffast.h inffixed.h
+
+inftrees.obj: inftrees.c zutil.h zlib.h zconf.h inftrees.h
+
+trees.obj: trees.c zutil.h zlib.h zconf.h deflate.h trees.h
+
+uncompr.obj: uncompr.c zlib.h zconf.h
+
+zutil.obj: zutil.c zutil.h zlib.h zconf.h
+
+example.obj: test/example.c zlib.h zconf.h
+
+minigzip.obj: test/minigzip.c zlib.h zconf.h
+
+
+# For the sake of the old Borland make,
+# the command line is cut to fit in the MS-DOS 128 byte limit:
+$(ZLIB_LIB): $(OBJ1) $(OBJ2)
+ -del $(ZLIB_LIB)
+ $(AR) $(ZLIB_LIB) $(OBJP1)
+ $(AR) $(ZLIB_LIB) $(OBJP2)
+
+
+# testing
+test: example.exe minigzip.exe
+ example
+ echo hello world | minigzip | minigzip -d
+
+example.exe: example.obj $(ZLIB_LIB)
+ $(LD) $(LDFLAGS) example.obj $(ZLIB_LIB)
+
+minigzip.exe: minigzip.obj $(ZLIB_LIB)
+ $(LD) $(LDFLAGS) minigzip.obj $(ZLIB_LIB)
+
+
+# cleanup
+clean:
+ -del *.obj
+ -del *.exe
+ -del *.lib
+ -del *.tds
+ -del zlib.bak
+ -del foo.gz
+
ADDED compat/zlib/contrib/dotzlib/DotZLib.build
Index: compat/zlib/contrib/dotzlib/DotZLib.build
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib.build
+++ compat/zlib/contrib/dotzlib/DotZLib.build
@@ -0,0 +1,33 @@
+
+
+ A .Net wrapper library around ZLib1.dll
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
ADDED compat/zlib/contrib/dotzlib/DotZLib.chm
Index: compat/zlib/contrib/dotzlib/DotZLib.chm
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib.chm
+++ compat/zlib/contrib/dotzlib/DotZLib.chm
cannot compute difference between binary files
ADDED compat/zlib/contrib/dotzlib/DotZLib.sln
Index: compat/zlib/contrib/dotzlib/DotZLib.sln
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib.sln
+++ compat/zlib/contrib/dotzlib/DotZLib.sln
@@ -0,0 +1,21 @@
+Microsoft Visual Studio Solution File, Format Version 8.00
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotZLib", "DotZLib\DotZLib.csproj", "{BB1EE0B1-1808-46CB-B786-949D91117FC5}"
+ ProjectSection(ProjectDependencies) = postProject
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SolutionConfiguration) = preSolution
+ Debug = Debug
+ Release = Release
+ EndGlobalSection
+ GlobalSection(ProjectConfiguration) = postSolution
+ {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Debug.ActiveCfg = Debug|.NET
+ {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Debug.Build.0 = Debug|.NET
+ {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Release.ActiveCfg = Release|.NET
+ {BB1EE0B1-1808-46CB-B786-949D91117FC5}.Release.Build.0 = Release|.NET
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ EndGlobalSection
+ GlobalSection(ExtensibilityAddIns) = postSolution
+ EndGlobalSection
+EndGlobal
ADDED compat/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/AssemblyInfo.cs
@@ -0,0 +1,58 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+//
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+//
+[assembly: AssemblyTitle("DotZLib")]
+[assembly: AssemblyDescription(".Net bindings for ZLib compression dll 1.2.x")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Henrik Ravn")]
+[assembly: AssemblyProduct("")]
+[assembly: AssemblyCopyright("(c) 2004 by Henrik Ravn")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+//
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Revision and Build Numbers
+// by using the '*' as shown below:
+
+[assembly: AssemblyVersion("1.0.*")]
+
+//
+// In order to sign your assembly you must specify a key to use. Refer to the
+// Microsoft .NET Framework documentation for more information on assembly signing.
+//
+// Use the attributes below to control which key is used for signing.
+//
+// Notes:
+// (*) If no key is specified, the assembly is not signed.
+// (*) KeyName refers to a key that has been installed in the Crypto Service
+// Provider (CSP) on your machine. KeyFile refers to a file which contains
+// a key.
+// (*) If the KeyFile and the KeyName values are both specified, the
+// following processing occurs:
+// (1) If the KeyName can be found in the CSP, that key is used.
+// (2) If the KeyName does not exist and the KeyFile does exist, the key
+// in the KeyFile is installed into the CSP and used.
+// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
+// When specifying the KeyFile, the location of the KeyFile should be
+// relative to the project output directory which is
+// %Project Directory%\obj\. For example, if your KeyFile is
+// located in the project directory, you would specify the AssemblyKeyFile
+// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
+// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
+// documentation for more information on this.
+//
+[assembly: AssemblyDelaySign(false)]
+[assembly: AssemblyKeyFile("")]
+[assembly: AssemblyKeyName("")]
ADDED compat/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs
@@ -0,0 +1,202 @@
+//
+// Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+
+namespace DotZLib
+{
+ #region ChecksumGeneratorBase
+ ///
+ /// Implements the common functionality needed for all s
+ ///
+ ///
+ public abstract class ChecksumGeneratorBase : ChecksumGenerator
+ {
+ ///
+ /// The value of the current checksum
+ ///
+ protected uint _current;
+
+ ///
+ /// Initializes a new instance of the checksum generator base - the current checksum is
+ /// set to zero
+ ///
+ public ChecksumGeneratorBase()
+ {
+ _current = 0;
+ }
+
+ ///
+ /// Initializes a new instance of the checksum generator basewith a specified value
+ ///
+ /// The value to set the current checksum to
+ public ChecksumGeneratorBase(uint initialValue)
+ {
+ _current = initialValue;
+ }
+
+ ///
+ /// Resets the current checksum to zero
+ ///
+ public void Reset() { _current = 0; }
+
+ ///
+ /// Gets the current checksum value
+ ///
+ public uint Value { get { return _current; } }
+
+ ///
+ /// Updates the current checksum with part of an array of bytes
+ ///
+ /// The data to update the checksum with
+ /// Where in data to start updating
+ /// The number of bytes from data to use
+ /// The sum of offset and count is larger than the length of data
+ /// data is a null reference
+ /// Offset or count is negative.
+ /// All the other Update methods are implmeneted in terms of this one.
+ /// This is therefore the only method a derived class has to implement
+ public abstract void Update(byte[] data, int offset, int count);
+
+ ///
+ /// Updates the current checksum with an array of bytes.
+ ///
+ /// The data to update the checksum with
+ public void Update(byte[] data)
+ {
+ Update(data, 0, data.Length);
+ }
+
+ ///
+ /// Updates the current checksum with the data from a string
+ ///
+ /// The string to update the checksum with
+ /// The characters in the string are converted by the UTF-8 encoding
+ public void Update(string data)
+ {
+ Update(Encoding.UTF8.GetBytes(data));
+ }
+
+ ///
+ /// Updates the current checksum with the data from a string, using a specific encoding
+ ///
+ /// The string to update the checksum with
+ /// The encoding to use
+ public void Update(string data, Encoding encoding)
+ {
+ Update(encoding.GetBytes(data));
+ }
+
+ }
+ #endregion
+
+ #region CRC32
+ ///
+ /// Implements a CRC32 checksum generator
+ ///
+ public sealed class CRC32Checksum : ChecksumGeneratorBase
+ {
+ #region DLL imports
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern uint crc32(uint crc, int data, uint length);
+
+ #endregion
+
+ ///
+ /// Initializes a new instance of the CRC32 checksum generator
+ ///
+ public CRC32Checksum() : base() {}
+
+ ///
+ /// Initializes a new instance of the CRC32 checksum generator with a specified value
+ ///
+ /// The value to set the current checksum to
+ public CRC32Checksum(uint initialValue) : base(initialValue) {}
+
+ ///
+ /// Updates the current checksum with part of an array of bytes
+ ///
+ /// The data to update the checksum with
+ /// Where in data to start updating
+ /// The number of bytes from data to use
+ /// The sum of offset and count is larger than the length of data
+ /// data is a null reference
+ /// Offset or count is negative.
+ public override void Update(byte[] data, int offset, int count)
+ {
+ if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
+ if ((offset+count) > data.Length) throw new ArgumentException();
+ GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);
+ try
+ {
+ _current = crc32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);
+ }
+ finally
+ {
+ hData.Free();
+ }
+ }
+
+ }
+ #endregion
+
+ #region Adler
+ ///
+ /// Implements a checksum generator that computes the Adler checksum on data
+ ///
+ public sealed class AdlerChecksum : ChecksumGeneratorBase
+ {
+ #region DLL imports
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern uint adler32(uint adler, int data, uint length);
+
+ #endregion
+
+ ///
+ /// Initializes a new instance of the Adler checksum generator
+ ///
+ public AdlerChecksum() : base() {}
+
+ ///
+ /// Initializes a new instance of the Adler checksum generator with a specified value
+ ///
+ /// The value to set the current checksum to
+ public AdlerChecksum(uint initialValue) : base(initialValue) {}
+
+ ///
+ /// Updates the current checksum with part of an array of bytes
+ ///
+ /// The data to update the checksum with
+ /// Where in data to start updating
+ /// The number of bytes from data to use
+ /// The sum of offset and count is larger than the length of data
+ /// data is a null reference
+ /// Offset or count is negative.
+ public override void Update(byte[] data, int offset, int count)
+ {
+ if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
+ if ((offset+count) > data.Length) throw new ArgumentException();
+ GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);
+ try
+ {
+ _current = adler32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);
+ }
+ finally
+ {
+ hData.Free();
+ }
+ }
+
+ }
+ #endregion
+
+}
ADDED compat/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/CircularBuffer.cs
@@ -0,0 +1,83 @@
+//
+// Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.Diagnostics;
+
+namespace DotZLib
+{
+
+ ///
+ /// This class implements a circular buffer
+ ///
+ internal class CircularBuffer
+ {
+ #region Private data
+ private int _capacity;
+ private int _head;
+ private int _tail;
+ private int _size;
+ private byte[] _buffer;
+ #endregion
+
+ public CircularBuffer(int capacity)
+ {
+ Debug.Assert( capacity > 0 );
+ _buffer = new byte[capacity];
+ _capacity = capacity;
+ _head = 0;
+ _tail = 0;
+ _size = 0;
+ }
+
+ public int Size { get { return _size; } }
+
+ public int Put(byte[] source, int offset, int count)
+ {
+ Debug.Assert( count > 0 );
+ int trueCount = Math.Min(count, _capacity - Size);
+ for (int i = 0; i < trueCount; ++i)
+ _buffer[(_tail+i) % _capacity] = source[offset+i];
+ _tail += trueCount;
+ _tail %= _capacity;
+ _size += trueCount;
+ return trueCount;
+ }
+
+ public bool Put(byte b)
+ {
+ if (Size == _capacity) // no room
+ return false;
+ _buffer[_tail++] = b;
+ _tail %= _capacity;
+ ++_size;
+ return true;
+ }
+
+ public int Get(byte[] destination, int offset, int count)
+ {
+ int trueCount = Math.Min(count,Size);
+ for (int i = 0; i < trueCount; ++i)
+ destination[offset + i] = _buffer[(_head+i) % _capacity];
+ _head += trueCount;
+ _head %= _capacity;
+ _size -= trueCount;
+ return trueCount;
+ }
+
+ public int Get()
+ {
+ if (Size == 0)
+ return -1;
+
+ int result = (int)_buffer[_head++ % _capacity];
+ --_size;
+ return result;
+ }
+
+ }
+}
ADDED compat/zlib/contrib/dotzlib/DotZLib/CodecBase.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/CodecBase.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/CodecBase.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/CodecBase.cs
@@ -0,0 +1,198 @@
+//
+// Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace DotZLib
+{
+ ///
+ /// Implements the common functionality needed for all s
+ ///
+ public abstract class CodecBase : Codec, IDisposable
+ {
+
+ #region Data members
+
+ ///
+ /// Instance of the internal zlib buffer structure that is
+ /// passed to all functions in the zlib dll
+ ///
+ internal ZStream _ztream = new ZStream();
+
+ ///
+ /// True if the object instance has been disposed, false otherwise
+ ///
+ protected bool _isDisposed = false;
+
+ ///
+ /// The size of the internal buffers
+ ///
+ protected const int kBufferSize = 16384;
+
+ private byte[] _outBuffer = new byte[kBufferSize];
+ private byte[] _inBuffer = new byte[kBufferSize];
+
+ private GCHandle _hInput;
+ private GCHandle _hOutput;
+
+ private uint _checksum = 0;
+
+ #endregion
+
+ ///
+ /// Initializes a new instance of the CodeBase class.
+ ///
+ public CodecBase()
+ {
+ try
+ {
+ _hInput = GCHandle.Alloc(_inBuffer, GCHandleType.Pinned);
+ _hOutput = GCHandle.Alloc(_outBuffer, GCHandleType.Pinned);
+ }
+ catch (Exception)
+ {
+ CleanUp(false);
+ throw;
+ }
+ }
+
+
+ #region Codec Members
+
+ ///
+ /// Occurs when more processed data are available.
+ ///
+ public event DataAvailableHandler DataAvailable;
+
+ ///
+ /// Fires the event
+ ///
+ protected void OnDataAvailable()
+ {
+ if (_ztream.total_out > 0)
+ {
+ if (DataAvailable != null)
+ DataAvailable( _outBuffer, 0, (int)_ztream.total_out);
+ resetOutput();
+ }
+ }
+
+ ///
+ /// Adds more data to the codec to be processed.
+ ///
+ /// Byte array containing the data to be added to the codec
+ /// Adding data may, or may not, raise the DataAvailable event
+ public void Add(byte[] data)
+ {
+ Add(data,0,data.Length);
+ }
+
+ ///
+ /// Adds more data to the codec to be processed.
+ ///
+ /// Byte array containing the data to be added to the codec
+ /// The index of the first byte to add from data
+ /// The number of bytes to add
+ /// Adding data may, or may not, raise the DataAvailable event
+ /// This must be implemented by a derived class
+ public abstract void Add(byte[] data, int offset, int count);
+
+ ///
+ /// Finishes up any pending data that needs to be processed and handled.
+ ///
+ /// This must be implemented by a derived class
+ public abstract void Finish();
+
+ ///
+ /// Gets the checksum of the data that has been added so far
+ ///
+ public uint Checksum { get { return _checksum; } }
+
+ #endregion
+
+ #region Destructor & IDisposable stuff
+
+ ///
+ /// Destroys this instance
+ ///
+ ~CodecBase()
+ {
+ CleanUp(false);
+ }
+
+ ///
+ /// Releases any unmanaged resources and calls the method of the derived class
+ ///
+ public void Dispose()
+ {
+ CleanUp(true);
+ }
+
+ ///
+ /// Performs any codec specific cleanup
+ ///
+ /// This must be implemented by a derived class
+ protected abstract void CleanUp();
+
+ // performs the release of the handles and calls the dereived CleanUp()
+ private void CleanUp(bool isDisposing)
+ {
+ if (!_isDisposed)
+ {
+ CleanUp();
+ if (_hInput.IsAllocated)
+ _hInput.Free();
+ if (_hOutput.IsAllocated)
+ _hOutput.Free();
+
+ _isDisposed = true;
+ }
+ }
+
+
+ #endregion
+
+ #region Helper methods
+
+ ///
+ /// Copies a number of bytes to the internal codec buffer - ready for proccesing
+ ///
+ /// The byte array that contains the data to copy
+ /// The index of the first byte to copy
+ /// The number of bytes to copy from data
+ protected void copyInput(byte[] data, int startIndex, int count)
+ {
+ Array.Copy(data, startIndex, _inBuffer,0, count);
+ _ztream.next_in = _hInput.AddrOfPinnedObject();
+ _ztream.total_in = 0;
+ _ztream.avail_in = (uint)count;
+
+ }
+
+ ///
+ /// Resets the internal output buffers to a known state - ready for processing
+ ///
+ protected void resetOutput()
+ {
+ _ztream.total_out = 0;
+ _ztream.avail_out = kBufferSize;
+ _ztream.next_out = _hOutput.AddrOfPinnedObject();
+ }
+
+ ///
+ /// Updates the running checksum property
+ ///
+ /// The new checksum value
+ protected void setChecksum(uint newSum)
+ {
+ _checksum = newSum;
+ }
+ #endregion
+
+ }
+}
ADDED compat/zlib/contrib/dotzlib/DotZLib/Deflater.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/Deflater.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/Deflater.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/Deflater.cs
@@ -0,0 +1,106 @@
+//
+// Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace DotZLib
+{
+
+ ///
+ /// Implements a data compressor, using the deflate algorithm in the ZLib dll
+ ///
+ public sealed class Deflater : CodecBase
+ {
+ #region Dll imports
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
+ private static extern int deflateInit_(ref ZStream sz, int level, string vs, int size);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int deflate(ref ZStream sz, int flush);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int deflateReset(ref ZStream sz);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int deflateEnd(ref ZStream sz);
+ #endregion
+
+ ///
+ /// Constructs an new instance of the Deflater
+ ///
+ /// The compression level to use for this Deflater
+ public Deflater(CompressLevel level) : base()
+ {
+ int retval = deflateInit_(ref _ztream, (int)level, Info.Version, Marshal.SizeOf(_ztream));
+ if (retval != 0)
+ throw new ZLibException(retval, "Could not initialize deflater");
+
+ resetOutput();
+ }
+
+ ///
+ /// Adds more data to the codec to be processed.
+ ///
+ /// Byte array containing the data to be added to the codec
+ /// The index of the first byte to add from data
+ /// The number of bytes to add
+ /// Adding data may, or may not, raise the DataAvailable event
+ public override void Add(byte[] data, int offset, int count)
+ {
+ if (data == null) throw new ArgumentNullException();
+ if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
+ if ((offset+count) > data.Length) throw new ArgumentException();
+
+ int total = count;
+ int inputIndex = offset;
+ int err = 0;
+
+ while (err >= 0 && inputIndex < total)
+ {
+ copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize));
+ while (err >= 0 && _ztream.avail_in > 0)
+ {
+ err = deflate(ref _ztream, (int)FlushTypes.None);
+ if (err == 0)
+ while (_ztream.avail_out == 0)
+ {
+ OnDataAvailable();
+ err = deflate(ref _ztream, (int)FlushTypes.None);
+ }
+ inputIndex += (int)_ztream.total_in;
+ }
+ }
+ setChecksum( _ztream.adler );
+ }
+
+
+ ///
+ /// Finishes up any pending data that needs to be processed and handled.
+ ///
+ public override void Finish()
+ {
+ int err;
+ do
+ {
+ err = deflate(ref _ztream, (int)FlushTypes.Finish);
+ OnDataAvailable();
+ }
+ while (err == 0);
+ setChecksum( _ztream.adler );
+ deflateReset(ref _ztream);
+ resetOutput();
+ }
+
+ ///
+ /// Closes the internal zlib deflate stream
+ ///
+ protected override void CleanUp() { deflateEnd(ref _ztream); }
+
+ }
+}
ADDED compat/zlib/contrib/dotzlib/DotZLib/DotZLib.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/DotZLib.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/DotZLib.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/DotZLib.cs
@@ -0,0 +1,288 @@
+//
+// Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text;
+
+
+namespace DotZLib
+{
+
+ #region Internal types
+
+ ///
+ /// Defines constants for the various flush types used with zlib
+ ///
+ internal enum FlushTypes
+ {
+ None, Partial, Sync, Full, Finish, Block
+ }
+
+ #region ZStream structure
+ // internal mapping of the zlib zstream structure for marshalling
+ [StructLayoutAttribute(LayoutKind.Sequential, Pack=4, Size=0, CharSet=CharSet.Ansi)]
+ internal struct ZStream
+ {
+ public IntPtr next_in;
+ public uint avail_in;
+ public uint total_in;
+
+ public IntPtr next_out;
+ public uint avail_out;
+ public uint total_out;
+
+ [MarshalAs(UnmanagedType.LPStr)]
+ string msg;
+ uint state;
+
+ uint zalloc;
+ uint zfree;
+ uint opaque;
+
+ int data_type;
+ public uint adler;
+ uint reserved;
+ }
+
+ #endregion
+
+ #endregion
+
+ #region Public enums
+ ///
+ /// Defines constants for the available compression levels in zlib
+ ///
+ public enum CompressLevel : int
+ {
+ ///
+ /// The default compression level with a reasonable compromise between compression and speed
+ ///
+ Default = -1,
+ ///
+ /// No compression at all. The data are passed straight through.
+ ///
+ None = 0,
+ ///
+ /// The maximum compression rate available.
+ ///
+ Best = 9,
+ ///
+ /// The fastest available compression level.
+ ///
+ Fastest = 1
+ }
+ #endregion
+
+ #region Exception classes
+ ///
+ /// The exception that is thrown when an error occurs on the zlib dll
+ ///
+ public class ZLibException : ApplicationException
+ {
+ ///
+ /// Initializes a new instance of the class with a specified
+ /// error message and error code
+ ///
+ /// The zlib error code that caused the exception
+ /// A message that (hopefully) describes the error
+ public ZLibException(int errorCode, string msg) : base(String.Format("ZLib error {0} {1}", errorCode, msg))
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class with a specified
+ /// error code
+ ///
+ /// The zlib error code that caused the exception
+ public ZLibException(int errorCode) : base(String.Format("ZLib error {0}", errorCode))
+ {
+ }
+ }
+ #endregion
+
+ #region Interfaces
+
+ ///
+ /// Declares methods and properties that enables a running checksum to be calculated
+ ///
+ public interface ChecksumGenerator
+ {
+ ///
+ /// Gets the current value of the checksum
+ ///
+ uint Value { get; }
+
+ ///
+ /// Clears the current checksum to 0
+ ///
+ void Reset();
+
+ ///
+ /// Updates the current checksum with an array of bytes
+ ///
+ /// The data to update the checksum with
+ void Update(byte[] data);
+
+ ///
+ /// Updates the current checksum with part of an array of bytes
+ ///
+ /// The data to update the checksum with
+ /// Where in data to start updating
+ /// The number of bytes from data to use
+ /// The sum of offset and count is larger than the length of data
+ /// data is a null reference
+ /// Offset or count is negative.
+ void Update(byte[] data, int offset, int count);
+
+ ///
+ /// Updates the current checksum with the data from a string
+ ///
+ /// The string to update the checksum with
+ /// The characters in the string are converted by the UTF-8 encoding
+ void Update(string data);
+
+ ///
+ /// Updates the current checksum with the data from a string, using a specific encoding
+ ///
+ /// The string to update the checksum with
+ /// The encoding to use
+ void Update(string data, Encoding encoding);
+ }
+
+
+ ///
+ /// Represents the method that will be called from a codec when new data
+ /// are available.
+ ///
+ /// The byte array containing the processed data
+ /// The index of the first processed byte in data
+ /// The number of processed bytes available
+ /// On return from this method, the data may be overwritten, so grab it while you can.
+ /// You cannot assume that startIndex will be zero.
+ ///
+ public delegate void DataAvailableHandler(byte[] data, int startIndex, int count);
+
+ ///
+ /// Declares methods and events for implementing compressors/decompressors
+ ///
+ public interface Codec
+ {
+ ///
+ /// Occurs when more processed data are available.
+ ///
+ event DataAvailableHandler DataAvailable;
+
+ ///
+ /// Adds more data to the codec to be processed.
+ ///
+ /// Byte array containing the data to be added to the codec
+ /// Adding data may, or may not, raise the DataAvailable event
+ void Add(byte[] data);
+
+ ///
+ /// Adds more data to the codec to be processed.
+ ///
+ /// Byte array containing the data to be added to the codec
+ /// The index of the first byte to add from data
+ /// The number of bytes to add
+ /// Adding data may, or may not, raise the DataAvailable event
+ void Add(byte[] data, int offset, int count);
+
+ ///
+ /// Finishes up any pending data that needs to be processed and handled.
+ ///
+ void Finish();
+
+ ///
+ /// Gets the checksum of the data that has been added so far
+ ///
+ uint Checksum { get; }
+
+
+ }
+
+ #endregion
+
+ #region Classes
+ ///
+ /// Encapsulates general information about the ZLib library
+ ///
+ public class Info
+ {
+ #region DLL imports
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern uint zlibCompileFlags();
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern string zlibVersion();
+ #endregion
+
+ #region Private stuff
+ private uint _flags;
+
+ // helper function that unpacks a bitsize mask
+ private static int bitSize(uint bits)
+ {
+ switch (bits)
+ {
+ case 0: return 16;
+ case 1: return 32;
+ case 2: return 64;
+ }
+ return -1;
+ }
+ #endregion
+
+ ///
+ /// Constructs an instance of the Info class.
+ ///
+ public Info()
+ {
+ _flags = zlibCompileFlags();
+ }
+
+ ///
+ /// True if the library is compiled with debug info
+ ///
+ public bool HasDebugInfo { get { return 0 != (_flags & 0x100); } }
+
+ ///
+ /// True if the library is compiled with assembly optimizations
+ ///
+ public bool UsesAssemblyCode { get { return 0 != (_flags & 0x200); } }
+
+ ///
+ /// Gets the size of the unsigned int that was compiled into Zlib
+ ///
+ public int SizeOfUInt { get { return bitSize(_flags & 3); } }
+
+ ///
+ /// Gets the size of the unsigned long that was compiled into Zlib
+ ///
+ public int SizeOfULong { get { return bitSize((_flags >> 2) & 3); } }
+
+ ///
+ /// Gets the size of the pointers that were compiled into Zlib
+ ///
+ public int SizeOfPointer { get { return bitSize((_flags >> 4) & 3); } }
+
+ ///
+ /// Gets the size of the z_off_t type that was compiled into Zlib
+ ///
+ public int SizeOfOffset { get { return bitSize((_flags >> 6) & 3); } }
+
+ ///
+ /// Gets the version of ZLib as a string, e.g. "1.2.1"
+ ///
+ public static string Version { get { return zlibVersion(); } }
+ }
+
+ #endregion
+
+}
ADDED compat/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj
Index: compat/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj
+++ compat/zlib/contrib/dotzlib/DotZLib/DotZLib.csproj
@@ -0,0 +1,141 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
ADDED compat/zlib/contrib/dotzlib/DotZLib/GZipStream.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/GZipStream.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/GZipStream.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/GZipStream.cs
@@ -0,0 +1,301 @@
+//
+// Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+
+namespace DotZLib
+{
+ ///
+ /// Implements a compressed , in GZip (.gz) format.
+ ///
+ public class GZipStream : Stream, IDisposable
+ {
+ #region Dll Imports
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
+ private static extern IntPtr gzopen(string name, string mode);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int gzclose(IntPtr gzFile);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int gzwrite(IntPtr gzFile, int data, int length);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int gzread(IntPtr gzFile, int data, int length);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int gzgetc(IntPtr gzFile);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int gzputc(IntPtr gzFile, int c);
+
+ #endregion
+
+ #region Private data
+ private IntPtr _gzFile;
+ private bool _isDisposed = false;
+ private bool _isWriting;
+ #endregion
+
+ #region Constructors
+ ///
+ /// Creates a new file as a writeable GZipStream
+ ///
+ /// The name of the compressed file to create
+ /// The compression level to use when adding data
+ /// If an error occurred in the internal zlib function
+ public GZipStream(string fileName, CompressLevel level)
+ {
+ _isWriting = true;
+ _gzFile = gzopen(fileName, String.Format("wb{0}", (int)level));
+ if (_gzFile == IntPtr.Zero)
+ throw new ZLibException(-1, "Could not open " + fileName);
+ }
+
+ ///
+ /// Opens an existing file as a readable GZipStream
+ ///
+ /// The name of the file to open
+ /// If an error occurred in the internal zlib function
+ public GZipStream(string fileName)
+ {
+ _isWriting = false;
+ _gzFile = gzopen(fileName, "rb");
+ if (_gzFile == IntPtr.Zero)
+ throw new ZLibException(-1, "Could not open " + fileName);
+
+ }
+ #endregion
+
+ #region Access properties
+ ///
+ /// Returns true of this stream can be read from, false otherwise
+ ///
+ public override bool CanRead
+ {
+ get
+ {
+ return !_isWriting;
+ }
+ }
+
+
+ ///
+ /// Returns false.
+ ///
+ public override bool CanSeek
+ {
+ get
+ {
+ return false;
+ }
+ }
+
+ ///
+ /// Returns true if this tsream is writeable, false otherwise
+ ///
+ public override bool CanWrite
+ {
+ get
+ {
+ return _isWriting;
+ }
+ }
+ #endregion
+
+ #region Destructor & IDispose stuff
+
+ ///
+ /// Destroys this instance
+ ///
+ ~GZipStream()
+ {
+ cleanUp(false);
+ }
+
+ ///
+ /// Closes the external file handle
+ ///
+ public void Dispose()
+ {
+ cleanUp(true);
+ }
+
+ // Does the actual closing of the file handle.
+ private void cleanUp(bool isDisposing)
+ {
+ if (!_isDisposed)
+ {
+ gzclose(_gzFile);
+ _isDisposed = true;
+ }
+ }
+ #endregion
+
+ #region Basic reading and writing
+ ///
+ /// Attempts to read a number of bytes from the stream.
+ ///
+ /// The destination data buffer
+ /// The index of the first destination byte in buffer
+ /// The number of bytes requested
+ /// The number of bytes read
+ /// If buffer is null
+ /// If count or offset are negative
+ /// If offset + count is > buffer.Length
+ /// If this stream is not readable.
+ /// If this stream has been disposed.
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ if (!CanRead) throw new NotSupportedException();
+ if (buffer == null) throw new ArgumentNullException();
+ if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
+ if ((offset+count) > buffer.Length) throw new ArgumentException();
+ if (_isDisposed) throw new ObjectDisposedException("GZipStream");
+
+ GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);
+ int result;
+ try
+ {
+ result = gzread(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count);
+ if (result < 0)
+ throw new IOException();
+ }
+ finally
+ {
+ h.Free();
+ }
+ return result;
+ }
+
+ ///
+ /// Attempts to read a single byte from the stream.
+ ///
+ /// The byte that was read, or -1 in case of error or End-Of-File
+ public override int ReadByte()
+ {
+ if (!CanRead) throw new NotSupportedException();
+ if (_isDisposed) throw new ObjectDisposedException("GZipStream");
+ return gzgetc(_gzFile);
+ }
+
+ ///
+ /// Writes a number of bytes to the stream
+ ///
+ ///
+ ///
+ ///
+ /// If buffer is null
+ /// If count or offset are negative
+ /// If offset + count is > buffer.Length
+ /// If this stream is not writeable.
+ /// If this stream has been disposed.
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (!CanWrite) throw new NotSupportedException();
+ if (buffer == null) throw new ArgumentNullException();
+ if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
+ if ((offset+count) > buffer.Length) throw new ArgumentException();
+ if (_isDisposed) throw new ObjectDisposedException("GZipStream");
+
+ GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);
+ try
+ {
+ int result = gzwrite(_gzFile, h.AddrOfPinnedObject().ToInt32() + offset, count);
+ if (result < 0)
+ throw new IOException();
+ }
+ finally
+ {
+ h.Free();
+ }
+ }
+
+ ///
+ /// Writes a single byte to the stream
+ ///
+ /// The byte to add to the stream.
+ /// If this stream is not writeable.
+ /// If this stream has been disposed.
+ public override void WriteByte(byte value)
+ {
+ if (!CanWrite) throw new NotSupportedException();
+ if (_isDisposed) throw new ObjectDisposedException("GZipStream");
+
+ int result = gzputc(_gzFile, (int)value);
+ if (result < 0)
+ throw new IOException();
+ }
+ #endregion
+
+ #region Position & length stuff
+ ///
+ /// Not supported.
+ ///
+ ///
+ /// Always thrown
+ public override void SetLength(long value)
+ {
+ throw new NotSupportedException();
+ }
+
+ ///
+ /// Not suppported.
+ ///
+ ///
+ ///
+ ///
+ /// Always thrown
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ throw new NotSupportedException();
+ }
+
+ ///
+ /// Flushes the GZipStream.
+ ///
+ /// In this implementation, this method does nothing. This is because excessive
+ /// flushing may degrade the achievable compression rates.
+ public override void Flush()
+ {
+ // left empty on purpose
+ }
+
+ ///
+ /// Gets/sets the current position in the GZipStream. Not suppported.
+ ///
+ /// In this implementation this property is not supported
+ /// Always thrown
+ public override long Position
+ {
+ get
+ {
+ throw new NotSupportedException();
+ }
+ set
+ {
+ throw new NotSupportedException();
+ }
+ }
+
+ ///
+ /// Gets the size of the stream. Not suppported.
+ ///
+ /// In this implementation this property is not supported
+ /// Always thrown
+ public override long Length
+ {
+ get
+ {
+ throw new NotSupportedException();
+ }
+ }
+ #endregion
+ }
+}
ADDED compat/zlib/contrib/dotzlib/DotZLib/Inflater.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/Inflater.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/Inflater.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/Inflater.cs
@@ -0,0 +1,105 @@
+//
+// Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace DotZLib
+{
+
+ ///
+ /// Implements a data decompressor, using the inflate algorithm in the ZLib dll
+ ///
+ public class Inflater : CodecBase
+ {
+ #region Dll imports
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
+ private static extern int inflateInit_(ref ZStream sz, string vs, int size);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int inflate(ref ZStream sz, int flush);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int inflateReset(ref ZStream sz);
+
+ [DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
+ private static extern int inflateEnd(ref ZStream sz);
+ #endregion
+
+ ///
+ /// Constructs an new instance of the Inflater
+ ///
+ public Inflater() : base()
+ {
+ int retval = inflateInit_(ref _ztream, Info.Version, Marshal.SizeOf(_ztream));
+ if (retval != 0)
+ throw new ZLibException(retval, "Could not initialize inflater");
+
+ resetOutput();
+ }
+
+
+ ///
+ /// Adds more data to the codec to be processed.
+ ///
+ /// Byte array containing the data to be added to the codec
+ /// The index of the first byte to add from data
+ /// The number of bytes to add
+ /// Adding data may, or may not, raise the DataAvailable event
+ public override void Add(byte[] data, int offset, int count)
+ {
+ if (data == null) throw new ArgumentNullException();
+ if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
+ if ((offset+count) > data.Length) throw new ArgumentException();
+
+ int total = count;
+ int inputIndex = offset;
+ int err = 0;
+
+ while (err >= 0 && inputIndex < total)
+ {
+ copyInput(data, inputIndex, Math.Min(total - inputIndex, kBufferSize));
+ err = inflate(ref _ztream, (int)FlushTypes.None);
+ if (err == 0)
+ while (_ztream.avail_out == 0)
+ {
+ OnDataAvailable();
+ err = inflate(ref _ztream, (int)FlushTypes.None);
+ }
+
+ inputIndex += (int)_ztream.total_in;
+ }
+ setChecksum( _ztream.adler );
+ }
+
+
+ ///
+ /// Finishes up any pending data that needs to be processed and handled.
+ ///
+ public override void Finish()
+ {
+ int err;
+ do
+ {
+ err = inflate(ref _ztream, (int)FlushTypes.Finish);
+ OnDataAvailable();
+ }
+ while (err == 0);
+ setChecksum( _ztream.adler );
+ inflateReset(ref _ztream);
+ resetOutput();
+ }
+
+ ///
+ /// Closes the internal zlib inflate stream
+ ///
+ protected override void CleanUp() { inflateEnd(ref _ztream); }
+
+
+ }
+}
ADDED compat/zlib/contrib/dotzlib/DotZLib/UnitTests.cs
Index: compat/zlib/contrib/dotzlib/DotZLib/UnitTests.cs
==================================================================
--- compat/zlib/contrib/dotzlib/DotZLib/UnitTests.cs
+++ compat/zlib/contrib/dotzlib/DotZLib/UnitTests.cs
@@ -0,0 +1,274 @@
+//
+// © Copyright Henrik Ravn 2004
+//
+// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+
+using System;
+using System.Collections;
+using System.IO;
+
+// uncomment the define below to include unit tests
+//#define nunit
+#if nunit
+using NUnit.Framework;
+
+// Unit tests for the DotZLib class library
+// ----------------------------------------
+//
+// Use this with NUnit 2 from http://www.nunit.org
+//
+
+namespace DotZLibTests
+{
+ using DotZLib;
+
+ // helper methods
+ internal class Utils
+ {
+ public static bool byteArrEqual( byte[] lhs, byte[] rhs )
+ {
+ if (lhs.Length != rhs.Length)
+ return false;
+ for (int i = lhs.Length-1; i >= 0; --i)
+ if (lhs[i] != rhs[i])
+ return false;
+ return true;
+ }
+
+ }
+
+
+ [TestFixture]
+ public class CircBufferTests
+ {
+ #region Circular buffer tests
+ [Test]
+ public void SinglePutGet()
+ {
+ CircularBuffer buf = new CircularBuffer(10);
+ Assert.AreEqual( 0, buf.Size );
+ Assert.AreEqual( -1, buf.Get() );
+
+ Assert.IsTrue(buf.Put( 1 ));
+ Assert.AreEqual( 1, buf.Size );
+ Assert.AreEqual( 1, buf.Get() );
+ Assert.AreEqual( 0, buf.Size );
+ Assert.AreEqual( -1, buf.Get() );
+ }
+
+ [Test]
+ public void BlockPutGet()
+ {
+ CircularBuffer buf = new CircularBuffer(10);
+ byte[] arr = {1,2,3,4,5,6,7,8,9,10};
+ Assert.AreEqual( 10, buf.Put(arr,0,10) );
+ Assert.AreEqual( 10, buf.Size );
+ Assert.IsFalse( buf.Put(11) );
+ Assert.AreEqual( 1, buf.Get() );
+ Assert.IsTrue( buf.Put(11) );
+
+ byte[] arr2 = (byte[])arr.Clone();
+ Assert.AreEqual( 9, buf.Get(arr2,1,9) );
+ Assert.IsTrue( Utils.byteArrEqual(arr,arr2) );
+ }
+
+ #endregion
+ }
+
+ [TestFixture]
+ public class ChecksumTests
+ {
+ #region CRC32 Tests
+ [Test]
+ public void CRC32_Null()
+ {
+ CRC32Checksum crc32 = new CRC32Checksum();
+ Assert.AreEqual( 0, crc32.Value );
+
+ crc32 = new CRC32Checksum(1);
+ Assert.AreEqual( 1, crc32.Value );
+
+ crc32 = new CRC32Checksum(556);
+ Assert.AreEqual( 556, crc32.Value );
+ }
+
+ [Test]
+ public void CRC32_Data()
+ {
+ CRC32Checksum crc32 = new CRC32Checksum();
+ byte[] data = { 1,2,3,4,5,6,7 };
+ crc32.Update(data);
+ Assert.AreEqual( 0x70e46888, crc32.Value );
+
+ crc32 = new CRC32Checksum();
+ crc32.Update("penguin");
+ Assert.AreEqual( 0x0e5c1a120, crc32.Value );
+
+ crc32 = new CRC32Checksum(1);
+ crc32.Update("penguin");
+ Assert.AreEqual(0x43b6aa94, crc32.Value);
+
+ }
+ #endregion
+
+ #region Adler tests
+
+ [Test]
+ public void Adler_Null()
+ {
+ AdlerChecksum adler = new AdlerChecksum();
+ Assert.AreEqual(0, adler.Value);
+
+ adler = new AdlerChecksum(1);
+ Assert.AreEqual( 1, adler.Value );
+
+ adler = new AdlerChecksum(556);
+ Assert.AreEqual( 556, adler.Value );
+ }
+
+ [Test]
+ public void Adler_Data()
+ {
+ AdlerChecksum adler = new AdlerChecksum(1);
+ byte[] data = { 1,2,3,4,5,6,7 };
+ adler.Update(data);
+ Assert.AreEqual( 0x5b001d, adler.Value );
+
+ adler = new AdlerChecksum();
+ adler.Update("penguin");
+ Assert.AreEqual(0x0bcf02f6, adler.Value );
+
+ adler = new AdlerChecksum(1);
+ adler.Update("penguin");
+ Assert.AreEqual(0x0bd602f7, adler.Value);
+
+ }
+ #endregion
+ }
+
+ [TestFixture]
+ public class InfoTests
+ {
+ #region Info tests
+ [Test]
+ public void Info_Version()
+ {
+ Info info = new Info();
+ Assert.AreEqual("1.2.13", Info.Version);
+ Assert.AreEqual(32, info.SizeOfUInt);
+ Assert.AreEqual(32, info.SizeOfULong);
+ Assert.AreEqual(32, info.SizeOfPointer);
+ Assert.AreEqual(32, info.SizeOfOffset);
+ }
+ #endregion
+ }
+
+ [TestFixture]
+ public class DeflateInflateTests
+ {
+ #region Deflate tests
+ [Test]
+ public void Deflate_Init()
+ {
+ using (Deflater def = new Deflater(CompressLevel.Default))
+ {
+ }
+ }
+
+ private ArrayList compressedData = new ArrayList();
+ private uint adler1;
+
+ private ArrayList uncompressedData = new ArrayList();
+ private uint adler2;
+
+ public void CDataAvail(byte[] data, int startIndex, int count)
+ {
+ for (int i = 0; i < count; ++i)
+ compressedData.Add(data[i+startIndex]);
+ }
+
+ [Test]
+ public void Deflate_Compress()
+ {
+ compressedData.Clear();
+
+ byte[] testData = new byte[35000];
+ for (int i = 0; i < testData.Length; ++i)
+ testData[i] = 5;
+
+ using (Deflater def = new Deflater((CompressLevel)5))
+ {
+ def.DataAvailable += new DataAvailableHandler(CDataAvail);
+ def.Add(testData);
+ def.Finish();
+ adler1 = def.Checksum;
+ }
+ }
+ #endregion
+
+ #region Inflate tests
+ [Test]
+ public void Inflate_Init()
+ {
+ using (Inflater inf = new Inflater())
+ {
+ }
+ }
+
+ private void DDataAvail(byte[] data, int startIndex, int count)
+ {
+ for (int i = 0; i < count; ++i)
+ uncompressedData.Add(data[i+startIndex]);
+ }
+
+ [Test]
+ public void Inflate_Expand()
+ {
+ uncompressedData.Clear();
+
+ using (Inflater inf = new Inflater())
+ {
+ inf.DataAvailable += new DataAvailableHandler(DDataAvail);
+ inf.Add((byte[])compressedData.ToArray(typeof(byte)));
+ inf.Finish();
+ adler2 = inf.Checksum;
+ }
+ Assert.AreEqual( adler1, adler2 );
+ }
+ #endregion
+ }
+
+ [TestFixture]
+ public class GZipStreamTests
+ {
+ #region GZipStream test
+ [Test]
+ public void GZipStream_WriteRead()
+ {
+ using (GZipStream gzOut = new GZipStream("gzstream.gz", CompressLevel.Best))
+ {
+ BinaryWriter writer = new BinaryWriter(gzOut);
+ writer.Write("hi there");
+ writer.Write(Math.PI);
+ writer.Write(42);
+ }
+
+ using (GZipStream gzIn = new GZipStream("gzstream.gz"))
+ {
+ BinaryReader reader = new BinaryReader(gzIn);
+ string s = reader.ReadString();
+ Assert.AreEqual("hi there",s);
+ double d = reader.ReadDouble();
+ Assert.AreEqual(Math.PI, d);
+ int i = reader.ReadInt32();
+ Assert.AreEqual(42,i);
+ }
+
+ }
+ #endregion
+ }
+}
+
+#endif
ADDED compat/zlib/contrib/dotzlib/LICENSE_1_0.txt
Index: compat/zlib/contrib/dotzlib/LICENSE_1_0.txt
==================================================================
--- compat/zlib/contrib/dotzlib/LICENSE_1_0.txt
+++ compat/zlib/contrib/dotzlib/LICENSE_1_0.txt
@@ -0,0 +1,23 @@
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
ADDED compat/zlib/contrib/dotzlib/readme.txt
Index: compat/zlib/contrib/dotzlib/readme.txt
==================================================================
--- compat/zlib/contrib/dotzlib/readme.txt
+++ compat/zlib/contrib/dotzlib/readme.txt
@@ -0,0 +1,58 @@
+This directory contains a .Net wrapper class library for the ZLib1.dll
+
+The wrapper includes support for inflating/deflating memory buffers,
+.Net streaming wrappers for the gz streams part of zlib, and wrappers
+for the checksum parts of zlib. See DotZLib/UnitTests.cs for examples.
+
+Directory structure:
+--------------------
+
+LICENSE_1_0.txt - License file.
+readme.txt - This file.
+DotZLib.chm - Class library documentation
+DotZLib.build - NAnt build file
+DotZLib.sln - Microsoft Visual Studio 2003 solution file
+
+DotZLib\*.cs - Source files for the class library
+
+Unit tests:
+-----------
+The file DotZLib/UnitTests.cs contains unit tests for use with NUnit 2.1 or higher.
+To include unit tests in the build, define nunit before building.
+
+
+Build instructions:
+-------------------
+
+1. Using Visual Studio.Net 2003:
+ Open DotZLib.sln in VS.Net and build from there. Output file (DotZLib.dll)
+ will be found ./DotZLib/bin/release or ./DotZLib/bin/debug, depending on
+ you are building the release or debug version of the library. Check
+ DotZLib/UnitTests.cs for instructions on how to include unit tests in the
+ build.
+
+2. Using NAnt:
+ Open a command prompt with access to the build environment and run nant
+ in the same directory as the DotZLib.build file.
+ You can define 2 properties on the nant command-line to control the build:
+ debug={true|false} to toggle between release/debug builds (default=true).
+ nunit={true|false} to include or esclude unit tests (default=true).
+ Also the target clean will remove binaries.
+ Output file (DotZLib.dll) will be found in either ./DotZLib/bin/release
+ or ./DotZLib/bin/debug, depending on whether you are building the release
+ or debug version of the library.
+
+ Examples:
+ nant -D:debug=false -D:nunit=false
+ will build a release mode version of the library without unit tests.
+ nant
+ will build a debug version of the library with unit tests
+ nant clean
+ will remove all previously built files.
+
+
+---------------------------------
+Copyright (c) Henrik Ravn 2004
+
+Use, modification and distribution are subject to the Boost Software License, Version 1.0.
+(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
ADDED compat/zlib/contrib/gcc_gvmat64/gvmat64.S
Index: compat/zlib/contrib/gcc_gvmat64/gvmat64.S
==================================================================
--- compat/zlib/contrib/gcc_gvmat64/gvmat64.S
+++ compat/zlib/contrib/gcc_gvmat64/gvmat64.S
@@ -0,0 +1,574 @@
+/*
+;uInt longest_match_x64(
+; deflate_state *s,
+; IPos cur_match); // current match
+
+; gvmat64.S -- Asm portion of the optimized longest_match for 32 bits x86_64
+; (AMD64 on Athlon 64, Opteron, Phenom
+; and Intel EM64T on Pentium 4 with EM64T, Pentium D, Core 2 Duo, Core I5/I7)
+; this file is translation from gvmat64.asm to GCC 4.x (for Linux, Mac XCode)
+; Copyright (C) 1995-2010 Jean-loup Gailly, Brian Raiter and Gilles Vollant.
+;
+; File written by Gilles Vollant, by converting to assembly the longest_match
+; from Jean-loup Gailly in deflate.c of zLib and infoZip zip.
+; and by taking inspiration on asm686 with masm, optimised assembly code
+; from Brian Raiter, written 1998
+;
+; This software is provided 'as-is', without any express or implied
+; warranty. In no event will the authors be held liable for any damages
+; arising from the use of this software.
+;
+; Permission is granted to anyone to use this software for any purpose,
+; including commercial applications, and to alter it and redistribute it
+; freely, subject to the following restrictions:
+;
+; 1. The origin of this software must not be misrepresented; you must not
+; claim that you wrote the original software. If you use this software
+; in a product, an acknowledgment in the product documentation would be
+; appreciated but is not required.
+; 2. Altered source versions must be plainly marked as such, and must not be
+; misrepresented as being the original software
+; 3. This notice may not be removed or altered from any source distribution.
+;
+; http://www.zlib.net
+; http://www.winimage.com/zLibDll
+; http://www.muppetlabs.com/~breadbox/software/assembly.html
+;
+; to compile this file for zLib, I use option:
+; gcc -c -arch x86_64 gvmat64.S
+
+
+;uInt longest_match(s, cur_match)
+; deflate_state *s;
+; IPos cur_match; // current match /
+;
+; with XCode for Mac, I had strange error with some jump on intel syntax
+; this is why BEFORE_JMP and AFTER_JMP are used
+ */
+
+
+#define BEFORE_JMP .att_syntax
+#define AFTER_JMP .intel_syntax noprefix
+
+#ifndef NO_UNDERLINE
+# define match_init _match_init
+# define longest_match _longest_match
+#endif
+
+.intel_syntax noprefix
+
+.globl match_init, longest_match
+.text
+longest_match:
+
+
+
+#define LocalVarsSize 96
+/*
+; register used : rax,rbx,rcx,rdx,rsi,rdi,r8,r9,r10,r11,r12
+; free register : r14,r15
+; register can be saved : rsp
+*/
+
+#define chainlenwmask (rsp + 8 - LocalVarsSize)
+#define nicematch (rsp + 16 - LocalVarsSize)
+
+#define save_rdi (rsp + 24 - LocalVarsSize)
+#define save_rsi (rsp + 32 - LocalVarsSize)
+#define save_rbx (rsp + 40 - LocalVarsSize)
+#define save_rbp (rsp + 48 - LocalVarsSize)
+#define save_r12 (rsp + 56 - LocalVarsSize)
+#define save_r13 (rsp + 64 - LocalVarsSize)
+#define save_r14 (rsp + 72 - LocalVarsSize)
+#define save_r15 (rsp + 80 - LocalVarsSize)
+
+
+/*
+; all the +4 offsets are due to the addition of pending_buf_size (in zlib
+; in the deflate_state structure since the asm code was first written
+; (if you compile with zlib 1.0.4 or older, remove the +4).
+; Note : these value are good with a 8 bytes boundary pack structure
+*/
+
+#define MAX_MATCH 258
+#define MIN_MATCH 3
+#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
+
+/*
+;;; Offsets for fields in the deflate_state structure. These numbers
+;;; are calculated from the definition of deflate_state, with the
+;;; assumption that the compiler will dword-align the fields. (Thus,
+;;; changing the definition of deflate_state could easily cause this
+;;; program to crash horribly, without so much as a warning at
+;;; compile time. Sigh.)
+
+; all the +zlib1222add offsets are due to the addition of fields
+; in zlib in the deflate_state structure since the asm code was first written
+; (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").
+; (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").
+; if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").
+*/
+
+
+
+/* you can check the structure offset by running
+
+#include
+#include
+#include "deflate.h"
+
+void print_depl()
+{
+deflate_state ds;
+deflate_state *s=&ds;
+printf("size pointer=%u\n",(int)sizeof(void*));
+
+printf("#define dsWSize %u\n",(int)(((char*)&(s->w_size))-((char*)s)));
+printf("#define dsWMask %u\n",(int)(((char*)&(s->w_mask))-((char*)s)));
+printf("#define dsWindow %u\n",(int)(((char*)&(s->window))-((char*)s)));
+printf("#define dsPrev %u\n",(int)(((char*)&(s->prev))-((char*)s)));
+printf("#define dsMatchLen %u\n",(int)(((char*)&(s->match_length))-((char*)s)));
+printf("#define dsPrevMatch %u\n",(int)(((char*)&(s->prev_match))-((char*)s)));
+printf("#define dsStrStart %u\n",(int)(((char*)&(s->strstart))-((char*)s)));
+printf("#define dsMatchStart %u\n",(int)(((char*)&(s->match_start))-((char*)s)));
+printf("#define dsLookahead %u\n",(int)(((char*)&(s->lookahead))-((char*)s)));
+printf("#define dsPrevLen %u\n",(int)(((char*)&(s->prev_length))-((char*)s)));
+printf("#define dsMaxChainLen %u\n",(int)(((char*)&(s->max_chain_length))-((char*)s)));
+printf("#define dsGoodMatch %u\n",(int)(((char*)&(s->good_match))-((char*)s)));
+printf("#define dsNiceMatch %u\n",(int)(((char*)&(s->nice_match))-((char*)s)));
+}
+*/
+
+#define dsWSize 68
+#define dsWMask 76
+#define dsWindow 80
+#define dsPrev 96
+#define dsMatchLen 144
+#define dsPrevMatch 148
+#define dsStrStart 156
+#define dsMatchStart 160
+#define dsLookahead 164
+#define dsPrevLen 168
+#define dsMaxChainLen 172
+#define dsGoodMatch 188
+#define dsNiceMatch 192
+
+#define window_size [ rcx + dsWSize]
+#define WMask [ rcx + dsWMask]
+#define window_ad [ rcx + dsWindow]
+#define prev_ad [ rcx + dsPrev]
+#define strstart [ rcx + dsStrStart]
+#define match_start [ rcx + dsMatchStart]
+#define Lookahead [ rcx + dsLookahead] //; 0ffffffffh on infozip
+#define prev_length [ rcx + dsPrevLen]
+#define max_chain_length [ rcx + dsMaxChainLen]
+#define good_match [ rcx + dsGoodMatch]
+#define nice_match [ rcx + dsNiceMatch]
+
+/*
+; windows:
+; parameter 1 in rcx(deflate state s), param 2 in rdx (cur match)
+
+; see http://weblogs.asp.net/oldnewthing/archive/2004/01/14/58579.aspx and
+; http://msdn.microsoft.com/library/en-us/kmarch/hh/kmarch/64bitAMD_8e951dd2-ee77-4728-8702-55ce4b5dd24a.xml.asp
+;
+; All registers must be preserved across the call, except for
+; rax, rcx, rdx, r8, r9, r10, and r11, which are scratch.
+
+;
+; gcc on macosx-linux:
+; see http://www.x86-64.org/documentation/abi-0.99.pdf
+; param 1 in rdi, param 2 in rsi
+; rbx, rsp, rbp, r12 to r15 must be preserved
+
+;;; Save registers that the compiler may be using, and adjust esp to
+;;; make room for our stack frame.
+
+
+;;; Retrieve the function arguments. r8d will hold cur_match
+;;; throughout the entire function. edx will hold the pointer to the
+;;; deflate_state structure during the function's setup (before
+;;; entering the main loop.
+
+; ms: parameter 1 in rcx (deflate_state* s), param 2 in edx -> r8 (cur match)
+; mac: param 1 in rdi, param 2 rsi
+; this clear high 32 bits of r8, which can be garbage in both r8 and rdx
+*/
+ mov [save_rbx],rbx
+ mov [save_rbp],rbp
+
+
+ mov rcx,rdi
+
+ mov r8d,esi
+
+
+ mov [save_r12],r12
+ mov [save_r13],r13
+ mov [save_r14],r14
+ mov [save_r15],r15
+
+
+//;;; uInt wmask = s->w_mask;
+//;;; unsigned chain_length = s->max_chain_length;
+//;;; if (s->prev_length >= s->good_match) {
+//;;; chain_length >>= 2;
+//;;; }
+
+
+ mov edi, prev_length
+ mov esi, good_match
+ mov eax, WMask
+ mov ebx, max_chain_length
+ cmp edi, esi
+ jl LastMatchGood
+ shr ebx, 2
+LastMatchGood:
+
+//;;; chainlen is decremented once beforehand so that the function can
+//;;; use the sign flag instead of the zero flag for the exit test.
+//;;; It is then shifted into the high word, to make room for the wmask
+//;;; value, which it will always accompany.
+
+ dec ebx
+ shl ebx, 16
+ or ebx, eax
+
+//;;; on zlib only
+//;;; if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
+
+
+
+ mov eax, nice_match
+ mov [chainlenwmask], ebx
+ mov r10d, Lookahead
+ cmp r10d, eax
+ cmovnl r10d, eax
+ mov [nicematch],r10d
+
+
+
+//;;; register Bytef *scan = s->window + s->strstart;
+ mov r10, window_ad
+ mov ebp, strstart
+ lea r13, [r10 + rbp]
+
+//;;; Determine how many bytes the scan ptr is off from being
+//;;; dword-aligned.
+
+ mov r9,r13
+ neg r13
+ and r13,3
+
+//;;; IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
+//;;; s->strstart - (IPos)MAX_DIST(s) : NIL;
+
+
+ mov eax, window_size
+ sub eax, MIN_LOOKAHEAD
+
+
+ xor edi,edi
+ sub ebp, eax
+
+ mov r11d, prev_length
+
+ cmovng ebp,edi
+
+//;;; int best_len = s->prev_length;
+
+
+//;;; Store the sum of s->window + best_len in esi locally, and in esi.
+
+ lea rsi,[r10+r11]
+
+//;;; register ush scan_start = *(ushf*)scan;
+//;;; register ush scan_end = *(ushf*)(scan+best_len-1);
+//;;; Posf *prev = s->prev;
+
+ movzx r12d,word ptr [r9]
+ movzx ebx, word ptr [r9 + r11 - 1]
+
+ mov rdi, prev_ad
+
+//;;; Jump into the main loop.
+
+ mov edx, [chainlenwmask]
+
+ cmp bx,word ptr [rsi + r8 - 1]
+ jz LookupLoopIsZero
+
+
+
+LookupLoop1:
+ and r8d, edx
+
+ movzx r8d, word ptr [rdi + r8*2]
+ cmp r8d, ebp
+ jbe LeaveNow
+
+
+
+ sub edx, 0x00010000
+ BEFORE_JMP
+ js LeaveNow
+ AFTER_JMP
+
+LoopEntry1:
+ cmp bx,word ptr [rsi + r8 - 1]
+ BEFORE_JMP
+ jz LookupLoopIsZero
+ AFTER_JMP
+
+LookupLoop2:
+ and r8d, edx
+
+ movzx r8d, word ptr [rdi + r8*2]
+ cmp r8d, ebp
+ BEFORE_JMP
+ jbe LeaveNow
+ AFTER_JMP
+ sub edx, 0x00010000
+ BEFORE_JMP
+ js LeaveNow
+ AFTER_JMP
+
+LoopEntry2:
+ cmp bx,word ptr [rsi + r8 - 1]
+ BEFORE_JMP
+ jz LookupLoopIsZero
+ AFTER_JMP
+
+LookupLoop4:
+ and r8d, edx
+
+ movzx r8d, word ptr [rdi + r8*2]
+ cmp r8d, ebp
+ BEFORE_JMP
+ jbe LeaveNow
+ AFTER_JMP
+ sub edx, 0x00010000
+ BEFORE_JMP
+ js LeaveNow
+ AFTER_JMP
+
+LoopEntry4:
+
+ cmp bx,word ptr [rsi + r8 - 1]
+ BEFORE_JMP
+ jnz LookupLoop1
+ jmp LookupLoopIsZero
+ AFTER_JMP
+/*
+;;; do {
+;;; match = s->window + cur_match;
+;;; if (*(ushf*)(match+best_len-1) != scan_end ||
+;;; *(ushf*)match != scan_start) continue;
+;;; [...]
+;;; } while ((cur_match = prev[cur_match & wmask]) > limit
+;;; && --chain_length != 0);
+;;;
+;;; Here is the inner loop of the function. The function will spend the
+;;; majority of its time in this loop, and majority of that time will
+;;; be spent in the first ten instructions.
+;;;
+;;; Within this loop:
+;;; ebx = scanend
+;;; r8d = curmatch
+;;; edx = chainlenwmask - i.e., ((chainlen << 16) | wmask)
+;;; esi = windowbestlen - i.e., (window + bestlen)
+;;; edi = prev
+;;; ebp = limit
+*/
+.balign 16
+LookupLoop:
+ and r8d, edx
+
+ movzx r8d, word ptr [rdi + r8*2]
+ cmp r8d, ebp
+ BEFORE_JMP
+ jbe LeaveNow
+ AFTER_JMP
+ sub edx, 0x00010000
+ BEFORE_JMP
+ js LeaveNow
+ AFTER_JMP
+
+LoopEntry:
+
+ cmp bx,word ptr [rsi + r8 - 1]
+ BEFORE_JMP
+ jnz LookupLoop1
+ AFTER_JMP
+LookupLoopIsZero:
+ cmp r12w, word ptr [r10 + r8]
+ BEFORE_JMP
+ jnz LookupLoop1
+ AFTER_JMP
+
+
+//;;; Store the current value of chainlen.
+ mov [chainlenwmask], edx
+/*
+;;; Point edi to the string under scrutiny, and esi to the string we
+;;; are hoping to match it up with. In actuality, esi and edi are
+;;; both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and edx is
+;;; initialized to -(MAX_MATCH_8 - scanalign).
+*/
+ lea rsi,[r8+r10]
+ mov rdx, 0xfffffffffffffef8 //; -(MAX_MATCH_8)
+ lea rsi, [rsi + r13 + 0x0108] //;MAX_MATCH_8]
+ lea rdi, [r9 + r13 + 0x0108] //;MAX_MATCH_8]
+
+ prefetcht1 [rsi+rdx]
+ prefetcht1 [rdi+rdx]
+
+/*
+;;; Test the strings for equality, 8 bytes at a time. At the end,
+;;; adjust rdx so that it is offset to the exact byte that mismatched.
+;;;
+;;; We already know at this point that the first three bytes of the
+;;; strings match each other, and they can be safely passed over before
+;;; starting the compare loop. So what this code does is skip over 0-3
+;;; bytes, as much as necessary in order to dword-align the edi
+;;; pointer. (rsi will still be misaligned three times out of four.)
+;;;
+;;; It should be confessed that this loop usually does not represent
+;;; much of the total running time. Replacing it with a more
+;;; straightforward "rep cmpsb" would not drastically degrade
+;;; performance.
+*/
+
+LoopCmps:
+ mov rax, [rsi + rdx]
+ xor rax, [rdi + rdx]
+ jnz LeaveLoopCmps
+
+ mov rax, [rsi + rdx + 8]
+ xor rax, [rdi + rdx + 8]
+ jnz LeaveLoopCmps8
+
+
+ mov rax, [rsi + rdx + 8+8]
+ xor rax, [rdi + rdx + 8+8]
+ jnz LeaveLoopCmps16
+
+ add rdx,8+8+8
+
+ BEFORE_JMP
+ jnz LoopCmps
+ jmp LenMaximum
+ AFTER_JMP
+
+LeaveLoopCmps16: add rdx,8
+LeaveLoopCmps8: add rdx,8
+LeaveLoopCmps:
+
+ test eax, 0x0000FFFF
+ jnz LenLower
+
+ test eax,0xffffffff
+
+ jnz LenLower32
+
+ add rdx,4
+ shr rax,32
+ or ax,ax
+ BEFORE_JMP
+ jnz LenLower
+ AFTER_JMP
+
+LenLower32:
+ shr eax,16
+ add rdx,2
+
+LenLower:
+ sub al, 1
+ adc rdx, 0
+//;;; Calculate the length of the match. If it is longer than MAX_MATCH,
+//;;; then automatically accept it as the best possible match and leave.
+
+ lea rax, [rdi + rdx]
+ sub rax, r9
+ cmp eax, MAX_MATCH
+ BEFORE_JMP
+ jge LenMaximum
+ AFTER_JMP
+/*
+;;; If the length of the match is not longer than the best match we
+;;; have so far, then forget it and return to the lookup loop.
+;///////////////////////////////////
+*/
+ cmp eax, r11d
+ jg LongerMatch
+
+ lea rsi,[r10+r11]
+
+ mov rdi, prev_ad
+ mov edx, [chainlenwmask]
+ BEFORE_JMP
+ jmp LookupLoop
+ AFTER_JMP
+/*
+;;; s->match_start = cur_match;
+;;; best_len = len;
+;;; if (len >= nice_match) break;
+;;; scan_end = *(ushf*)(scan+best_len-1);
+*/
+LongerMatch:
+ mov r11d, eax
+ mov match_start, r8d
+ cmp eax, [nicematch]
+ BEFORE_JMP
+ jge LeaveNow
+ AFTER_JMP
+
+ lea rsi,[r10+rax]
+
+ movzx ebx, word ptr [r9 + rax - 1]
+ mov rdi, prev_ad
+ mov edx, [chainlenwmask]
+ BEFORE_JMP
+ jmp LookupLoop
+ AFTER_JMP
+
+//;;; Accept the current string, with the maximum possible length.
+
+LenMaximum:
+ mov r11d,MAX_MATCH
+ mov match_start, r8d
+
+//;;; if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
+//;;; return s->lookahead;
+
+LeaveNow:
+ mov eax, Lookahead
+ cmp r11d, eax
+ cmovng eax, r11d
+
+
+
+//;;; Restore the stack and return from whence we came.
+
+
+// mov rsi,[save_rsi]
+// mov rdi,[save_rdi]
+ mov rbx,[save_rbx]
+ mov rbp,[save_rbp]
+ mov r12,[save_r12]
+ mov r13,[save_r13]
+ mov r14,[save_r14]
+ mov r15,[save_r15]
+
+
+ ret 0
+//; please don't remove this string !
+//; Your can freely use gvmat64 in any free or commercial app
+//; but it is far better don't remove the string in the binary!
+ // db 0dh,0ah,"asm686 with masm, optimised assembly code from Brian Raiter, written 1998, converted to amd 64 by Gilles Vollant 2005",0dh,0ah,0
+
+
+match_init:
+ ret 0
+
+
ADDED compat/zlib/contrib/infback9/README
Index: compat/zlib/contrib/infback9/README
==================================================================
--- compat/zlib/contrib/infback9/README
+++ compat/zlib/contrib/infback9/README
@@ -0,0 +1,1 @@
+See infback9.h for what this is and how to use it.
ADDED compat/zlib/contrib/infback9/infback9.c
Index: compat/zlib/contrib/infback9/infback9.c
==================================================================
--- compat/zlib/contrib/infback9/infback9.c
+++ compat/zlib/contrib/infback9/infback9.c
@@ -0,0 +1,615 @@
+/* infback9.c -- inflate deflate64 data using a call-back interface
+ * Copyright (C) 1995-2008 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "infback9.h"
+#include "inftree9.h"
+#include "inflate9.h"
+
+#define WSIZE 65536UL
+
+/*
+ strm provides memory allocation functions in zalloc and zfree, or
+ Z_NULL to use the library memory allocation functions.
+
+ window is a user-supplied window and output buffer that is 64K bytes.
+ */
+int ZEXPORT inflateBack9Init_(strm, window, version, stream_size)
+z_stream FAR *strm;
+unsigned char FAR *window;
+const char *version;
+int stream_size;
+{
+ struct inflate_state FAR *state;
+
+ if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+ stream_size != (int)(sizeof(z_stream)))
+ return Z_VERSION_ERROR;
+ if (strm == Z_NULL || window == Z_NULL)
+ return Z_STREAM_ERROR;
+ strm->msg = Z_NULL; /* in case we return an error */
+ if (strm->zalloc == (alloc_func)0) {
+ strm->zalloc = zcalloc;
+ strm->opaque = (voidpf)0;
+ }
+ if (strm->zfree == (free_func)0) strm->zfree = zcfree;
+ state = (struct inflate_state FAR *)ZALLOC(strm, 1,
+ sizeof(struct inflate_state));
+ if (state == Z_NULL) return Z_MEM_ERROR;
+ Tracev((stderr, "inflate: allocated\n"));
+ strm->state = (voidpf)state;
+ state->window = window;
+ return Z_OK;
+}
+
+/*
+ Build and output length and distance decoding tables for fixed code
+ decoding.
+ */
+#ifdef MAKEFIXED
+#include
+
+void makefixed9(void)
+{
+ unsigned sym, bits, low, size;
+ code *next, *lenfix, *distfix;
+ struct inflate_state state;
+ code fixed[544];
+
+ /* literal/length table */
+ sym = 0;
+ while (sym < 144) state.lens[sym++] = 8;
+ while (sym < 256) state.lens[sym++] = 9;
+ while (sym < 280) state.lens[sym++] = 7;
+ while (sym < 288) state.lens[sym++] = 8;
+ next = fixed;
+ lenfix = next;
+ bits = 9;
+ inflate_table9(LENS, state.lens, 288, &(next), &(bits), state.work);
+
+ /* distance table */
+ sym = 0;
+ while (sym < 32) state.lens[sym++] = 5;
+ distfix = next;
+ bits = 5;
+ inflate_table9(DISTS, state.lens, 32, &(next), &(bits), state.work);
+
+ /* write tables */
+ puts(" /* inffix9.h -- table for decoding deflate64 fixed codes");
+ puts(" * Generated automatically by makefixed9().");
+ puts(" */");
+ puts("");
+ puts(" /* WARNING: this file should *not* be used by applications.");
+ puts(" It is part of the implementation of this library and is");
+ puts(" subject to change. Applications should only use zlib.h.");
+ puts(" */");
+ puts("");
+ size = 1U << 9;
+ printf(" static const code lenfix[%u] = {", size);
+ low = 0;
+ for (;;) {
+ if ((low % 6) == 0) printf("\n ");
+ printf("{%u,%u,%d}", lenfix[low].op, lenfix[low].bits,
+ lenfix[low].val);
+ if (++low == size) break;
+ putchar(',');
+ }
+ puts("\n };");
+ size = 1U << 5;
+ printf("\n static const code distfix[%u] = {", size);
+ low = 0;
+ for (;;) {
+ if ((low % 5) == 0) printf("\n ");
+ printf("{%u,%u,%d}", distfix[low].op, distfix[low].bits,
+ distfix[low].val);
+ if (++low == size) break;
+ putchar(',');
+ }
+ puts("\n };");
+}
+#endif /* MAKEFIXED */
+
+/* Macros for inflateBack(): */
+
+/* Clear the input bit accumulator */
+#define INITBITS() \
+ do { \
+ hold = 0; \
+ bits = 0; \
+ } while (0)
+
+/* Assure that some input is available. If input is requested, but denied,
+ then return a Z_BUF_ERROR from inflateBack(). */
+#define PULL() \
+ do { \
+ if (have == 0) { \
+ have = in(in_desc, &next); \
+ if (have == 0) { \
+ next = Z_NULL; \
+ ret = Z_BUF_ERROR; \
+ goto inf_leave; \
+ } \
+ } \
+ } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflateBack()
+ with an error if there is no input available. */
+#define PULLBYTE() \
+ do { \
+ PULL(); \
+ have--; \
+ hold += (unsigned long)(*next++) << bits; \
+ bits += 8; \
+ } while (0)
+
+/* Assure that there are at least n bits in the bit accumulator. If there is
+ not enough available input to do that, then return from inflateBack() with
+ an error. */
+#define NEEDBITS(n) \
+ do { \
+ while (bits < (unsigned)(n)) \
+ PULLBYTE(); \
+ } while (0)
+
+/* Return the low n bits of the bit accumulator (n <= 16) */
+#define BITS(n) \
+ ((unsigned)hold & ((1U << (n)) - 1))
+
+/* Remove n bits from the bit accumulator */
+#define DROPBITS(n) \
+ do { \
+ hold >>= (n); \
+ bits -= (unsigned)(n); \
+ } while (0)
+
+/* Remove zero to seven bits as needed to go to a byte boundary */
+#define BYTEBITS() \
+ do { \
+ hold >>= bits & 7; \
+ bits -= bits & 7; \
+ } while (0)
+
+/* Assure that some output space is available, by writing out the window
+ if it's full. If the write fails, return from inflateBack() with a
+ Z_BUF_ERROR. */
+#define ROOM() \
+ do { \
+ if (left == 0) { \
+ put = window; \
+ left = WSIZE; \
+ wrap = 1; \
+ if (out(out_desc, put, (unsigned)left)) { \
+ ret = Z_BUF_ERROR; \
+ goto inf_leave; \
+ } \
+ } \
+ } while (0)
+
+/*
+ strm provides the memory allocation functions and window buffer on input,
+ and provides information on the unused input on return. For Z_DATA_ERROR
+ returns, strm will also provide an error message.
+
+ in() and out() are the call-back input and output functions. When
+ inflateBack() needs more input, it calls in(). When inflateBack() has
+ filled the window with output, or when it completes with data in the
+ window, it calls out() to write out the data. The application must not
+ change the provided input until in() is called again or inflateBack()
+ returns. The application must not change the window/output buffer until
+ inflateBack() returns.
+
+ in() and out() are called with a descriptor parameter provided in the
+ inflateBack() call. This parameter can be a structure that provides the
+ information required to do the read or write, as well as accumulated
+ information on the input and output such as totals and check values.
+
+ in() should return zero on failure. out() should return non-zero on
+ failure. If either in() or out() fails, than inflateBack() returns a
+ Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
+ was in() or out() that caused in the error. Otherwise, inflateBack()
+ returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
+ error, or Z_MEM_ERROR if it could not allocate memory for the state.
+ inflateBack() can also return Z_STREAM_ERROR if the input parameters
+ are not correct, i.e. strm is Z_NULL or the state was not initialized.
+ */
+int ZEXPORT inflateBack9(strm, in, in_desc, out, out_desc)
+z_stream FAR *strm;
+in_func in;
+void FAR *in_desc;
+out_func out;
+void FAR *out_desc;
+{
+ struct inflate_state FAR *state;
+ z_const unsigned char FAR *next; /* next input */
+ unsigned char FAR *put; /* next output */
+ unsigned have; /* available input */
+ unsigned long left; /* available output */
+ inflate_mode mode; /* current inflate mode */
+ int lastblock; /* true if processing last block */
+ int wrap; /* true if the window has wrapped */
+ unsigned char FAR *window; /* allocated sliding window, if needed */
+ unsigned long hold; /* bit buffer */
+ unsigned bits; /* bits in bit buffer */
+ unsigned extra; /* extra bits needed */
+ unsigned long length; /* literal or length of data to copy */
+ unsigned long offset; /* distance back to copy string from */
+ unsigned long copy; /* number of stored or match bytes to copy */
+ unsigned char FAR *from; /* where to copy match bytes from */
+ code const FAR *lencode; /* starting table for length/literal codes */
+ code const FAR *distcode; /* starting table for distance codes */
+ unsigned lenbits; /* index bits for lencode */
+ unsigned distbits; /* index bits for distcode */
+ code here; /* current decoding table entry */
+ code last; /* parent table entry */
+ unsigned len; /* length to copy for repeats, bits to drop */
+ int ret; /* return code */
+ static const unsigned short order[19] = /* permutation of code lengths */
+ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+#include "inffix9.h"
+
+ /* Check that the strm exists and that the state was initialized */
+ if (strm == Z_NULL || strm->state == Z_NULL)
+ return Z_STREAM_ERROR;
+ state = (struct inflate_state FAR *)strm->state;
+
+ /* Reset the state */
+ strm->msg = Z_NULL;
+ mode = TYPE;
+ lastblock = 0;
+ wrap = 0;
+ window = state->window;
+ next = strm->next_in;
+ have = next != Z_NULL ? strm->avail_in : 0;
+ hold = 0;
+ bits = 0;
+ put = window;
+ left = WSIZE;
+ lencode = Z_NULL;
+ distcode = Z_NULL;
+
+ /* Inflate until end of block marked as last */
+ for (;;)
+ switch (mode) {
+ case TYPE:
+ /* determine and dispatch block type */
+ if (lastblock) {
+ BYTEBITS();
+ mode = DONE;
+ break;
+ }
+ NEEDBITS(3);
+ lastblock = BITS(1);
+ DROPBITS(1);
+ switch (BITS(2)) {
+ case 0: /* stored block */
+ Tracev((stderr, "inflate: stored block%s\n",
+ lastblock ? " (last)" : ""));
+ mode = STORED;
+ break;
+ case 1: /* fixed block */
+ lencode = lenfix;
+ lenbits = 9;
+ distcode = distfix;
+ distbits = 5;
+ Tracev((stderr, "inflate: fixed codes block%s\n",
+ lastblock ? " (last)" : ""));
+ mode = LEN; /* decode codes */
+ break;
+ case 2: /* dynamic block */
+ Tracev((stderr, "inflate: dynamic codes block%s\n",
+ lastblock ? " (last)" : ""));
+ mode = TABLE;
+ break;
+ case 3:
+ strm->msg = (char *)"invalid block type";
+ mode = BAD;
+ }
+ DROPBITS(2);
+ break;
+
+ case STORED:
+ /* get and verify stored block length */
+ BYTEBITS(); /* go to byte boundary */
+ NEEDBITS(32);
+ if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
+ strm->msg = (char *)"invalid stored block lengths";
+ mode = BAD;
+ break;
+ }
+ length = (unsigned)hold & 0xffff;
+ Tracev((stderr, "inflate: stored length %lu\n",
+ length));
+ INITBITS();
+
+ /* copy stored block from input to output */
+ while (length != 0) {
+ copy = length;
+ PULL();
+ ROOM();
+ if (copy > have) copy = have;
+ if (copy > left) copy = left;
+ zmemcpy(put, next, copy);
+ have -= copy;
+ next += copy;
+ left -= copy;
+ put += copy;
+ length -= copy;
+ }
+ Tracev((stderr, "inflate: stored end\n"));
+ mode = TYPE;
+ break;
+
+ case TABLE:
+ /* get dynamic table entries descriptor */
+ NEEDBITS(14);
+ state->nlen = BITS(5) + 257;
+ DROPBITS(5);
+ state->ndist = BITS(5) + 1;
+ DROPBITS(5);
+ state->ncode = BITS(4) + 4;
+ DROPBITS(4);
+ if (state->nlen > 286) {
+ strm->msg = (char *)"too many length symbols";
+ mode = BAD;
+ break;
+ }
+ Tracev((stderr, "inflate: table sizes ok\n"));
+
+ /* get code length code lengths (not a typo) */
+ state->have = 0;
+ while (state->have < state->ncode) {
+ NEEDBITS(3);
+ state->lens[order[state->have++]] = (unsigned short)BITS(3);
+ DROPBITS(3);
+ }
+ while (state->have < 19)
+ state->lens[order[state->have++]] = 0;
+ state->next = state->codes;
+ lencode = (code const FAR *)(state->next);
+ lenbits = 7;
+ ret = inflate_table9(CODES, state->lens, 19, &(state->next),
+ &(lenbits), state->work);
+ if (ret) {
+ strm->msg = (char *)"invalid code lengths set";
+ mode = BAD;
+ break;
+ }
+ Tracev((stderr, "inflate: code lengths ok\n"));
+
+ /* get length and distance code code lengths */
+ state->have = 0;
+ while (state->have < state->nlen + state->ndist) {
+ for (;;) {
+ here = lencode[BITS(lenbits)];
+ if ((unsigned)(here.bits) <= bits) break;
+ PULLBYTE();
+ }
+ if (here.val < 16) {
+ NEEDBITS(here.bits);
+ DROPBITS(here.bits);
+ state->lens[state->have++] = here.val;
+ }
+ else {
+ if (here.val == 16) {
+ NEEDBITS(here.bits + 2);
+ DROPBITS(here.bits);
+ if (state->have == 0) {
+ strm->msg = (char *)"invalid bit length repeat";
+ mode = BAD;
+ break;
+ }
+ len = (unsigned)(state->lens[state->have - 1]);
+ copy = 3 + BITS(2);
+ DROPBITS(2);
+ }
+ else if (here.val == 17) {
+ NEEDBITS(here.bits + 3);
+ DROPBITS(here.bits);
+ len = 0;
+ copy = 3 + BITS(3);
+ DROPBITS(3);
+ }
+ else {
+ NEEDBITS(here.bits + 7);
+ DROPBITS(here.bits);
+ len = 0;
+ copy = 11 + BITS(7);
+ DROPBITS(7);
+ }
+ if (state->have + copy > state->nlen + state->ndist) {
+ strm->msg = (char *)"invalid bit length repeat";
+ mode = BAD;
+ break;
+ }
+ while (copy--)
+ state->lens[state->have++] = (unsigned short)len;
+ }
+ }
+
+ /* handle error breaks in while */
+ if (mode == BAD) break;
+
+ /* check for end-of-block code (better have one) */
+ if (state->lens[256] == 0) {
+ strm->msg = (char *)"invalid code -- missing end-of-block";
+ mode = BAD;
+ break;
+ }
+
+ /* build code tables -- note: do not change the lenbits or distbits
+ values here (9 and 6) without reading the comments in inftree9.h
+ concerning the ENOUGH constants, which depend on those values */
+ state->next = state->codes;
+ lencode = (code const FAR *)(state->next);
+ lenbits = 9;
+ ret = inflate_table9(LENS, state->lens, state->nlen,
+ &(state->next), &(lenbits), state->work);
+ if (ret) {
+ strm->msg = (char *)"invalid literal/lengths set";
+ mode = BAD;
+ break;
+ }
+ distcode = (code const FAR *)(state->next);
+ distbits = 6;
+ ret = inflate_table9(DISTS, state->lens + state->nlen,
+ state->ndist, &(state->next), &(distbits),
+ state->work);
+ if (ret) {
+ strm->msg = (char *)"invalid distances set";
+ mode = BAD;
+ break;
+ }
+ Tracev((stderr, "inflate: codes ok\n"));
+ mode = LEN;
+
+ case LEN:
+ /* get a literal, length, or end-of-block code */
+ for (;;) {
+ here = lencode[BITS(lenbits)];
+ if ((unsigned)(here.bits) <= bits) break;
+ PULLBYTE();
+ }
+ if (here.op && (here.op & 0xf0) == 0) {
+ last = here;
+ for (;;) {
+ here = lencode[last.val +
+ (BITS(last.bits + last.op) >> last.bits)];
+ if ((unsigned)(last.bits + here.bits) <= bits) break;
+ PULLBYTE();
+ }
+ DROPBITS(last.bits);
+ }
+ DROPBITS(here.bits);
+ length = (unsigned)here.val;
+
+ /* process literal */
+ if (here.op == 0) {
+ Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+ "inflate: literal '%c'\n" :
+ "inflate: literal 0x%02x\n", here.val));
+ ROOM();
+ *put++ = (unsigned char)(length);
+ left--;
+ mode = LEN;
+ break;
+ }
+
+ /* process end of block */
+ if (here.op & 32) {
+ Tracevv((stderr, "inflate: end of block\n"));
+ mode = TYPE;
+ break;
+ }
+
+ /* invalid code */
+ if (here.op & 64) {
+ strm->msg = (char *)"invalid literal/length code";
+ mode = BAD;
+ break;
+ }
+
+ /* length code -- get extra bits, if any */
+ extra = (unsigned)(here.op) & 31;
+ if (extra != 0) {
+ NEEDBITS(extra);
+ length += BITS(extra);
+ DROPBITS(extra);
+ }
+ Tracevv((stderr, "inflate: length %lu\n", length));
+
+ /* get distance code */
+ for (;;) {
+ here = distcode[BITS(distbits)];
+ if ((unsigned)(here.bits) <= bits) break;
+ PULLBYTE();
+ }
+ if ((here.op & 0xf0) == 0) {
+ last = here;
+ for (;;) {
+ here = distcode[last.val +
+ (BITS(last.bits + last.op) >> last.bits)];
+ if ((unsigned)(last.bits + here.bits) <= bits) break;
+ PULLBYTE();
+ }
+ DROPBITS(last.bits);
+ }
+ DROPBITS(here.bits);
+ if (here.op & 64) {
+ strm->msg = (char *)"invalid distance code";
+ mode = BAD;
+ break;
+ }
+ offset = (unsigned)here.val;
+
+ /* get distance extra bits, if any */
+ extra = (unsigned)(here.op) & 15;
+ if (extra != 0) {
+ NEEDBITS(extra);
+ offset += BITS(extra);
+ DROPBITS(extra);
+ }
+ if (offset > WSIZE - (wrap ? 0: left)) {
+ strm->msg = (char *)"invalid distance too far back";
+ mode = BAD;
+ break;
+ }
+ Tracevv((stderr, "inflate: distance %lu\n", offset));
+
+ /* copy match from window to output */
+ do {
+ ROOM();
+ copy = WSIZE - offset;
+ if (copy < left) {
+ from = put + copy;
+ copy = left - copy;
+ }
+ else {
+ from = put - offset;
+ copy = left;
+ }
+ if (copy > length) copy = length;
+ length -= copy;
+ left -= copy;
+ do {
+ *put++ = *from++;
+ } while (--copy);
+ } while (length != 0);
+ break;
+
+ case DONE:
+ /* inflate stream terminated properly -- write leftover output */
+ ret = Z_STREAM_END;
+ if (left < WSIZE) {
+ if (out(out_desc, window, (unsigned)(WSIZE - left)))
+ ret = Z_BUF_ERROR;
+ }
+ goto inf_leave;
+
+ case BAD:
+ ret = Z_DATA_ERROR;
+ goto inf_leave;
+
+ default: /* can't happen, but makes compilers happy */
+ ret = Z_STREAM_ERROR;
+ goto inf_leave;
+ }
+
+ /* Return unused input */
+ inf_leave:
+ strm->next_in = next;
+ strm->avail_in = have;
+ return ret;
+}
+
+int ZEXPORT inflateBack9End(strm)
+z_stream FAR *strm;
+{
+ if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
+ return Z_STREAM_ERROR;
+ ZFREE(strm, strm->state);
+ strm->state = Z_NULL;
+ Tracev((stderr, "inflate: end\n"));
+ return Z_OK;
+}
ADDED compat/zlib/contrib/infback9/infback9.h
Index: compat/zlib/contrib/infback9/infback9.h
==================================================================
--- compat/zlib/contrib/infback9/infback9.h
+++ compat/zlib/contrib/infback9/infback9.h
@@ -0,0 +1,37 @@
+/* infback9.h -- header for using inflateBack9 functions
+ * Copyright (C) 2003 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ * This header file and associated patches provide a decoder for PKWare's
+ * undocumented deflate64 compression method (method 9). Use with infback9.c,
+ * inftree9.h, inftree9.c, and inffix9.h. These patches are not supported.
+ * This should be compiled with zlib, since it uses zutil.h and zutil.o.
+ * This code has not yet been tested on 16-bit architectures. See the
+ * comments in zlib.h for inflateBack() usage. These functions are used
+ * identically, except that there is no windowBits parameter, and a 64K
+ * window must be provided. Also if int's are 16 bits, then a zero for
+ * the third parameter of the "out" function actually means 65536UL.
+ * zlib.h must be included before this header file.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ZEXTERN int ZEXPORT inflateBack9 OF((z_stream FAR *strm,
+ in_func in, void FAR *in_desc,
+ out_func out, void FAR *out_desc));
+ZEXTERN int ZEXPORT inflateBack9End OF((z_stream FAR *strm));
+ZEXTERN int ZEXPORT inflateBack9Init_ OF((z_stream FAR *strm,
+ unsigned char FAR *window,
+ const char *version,
+ int stream_size));
+#define inflateBack9Init(strm, window) \
+ inflateBack9Init_((strm), (window), \
+ ZLIB_VERSION, sizeof(z_stream))
+
+#ifdef __cplusplus
+}
+#endif
ADDED compat/zlib/contrib/infback9/inffix9.h
Index: compat/zlib/contrib/infback9/inffix9.h
==================================================================
--- compat/zlib/contrib/infback9/inffix9.h
+++ compat/zlib/contrib/infback9/inffix9.h
@@ -0,0 +1,107 @@
+ /* inffix9.h -- table for decoding deflate64 fixed codes
+ * Generated automatically by makefixed9().
+ */
+
+ /* WARNING: this file should *not* be used by applications.
+ It is part of the implementation of this library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+ static const code lenfix[512] = {
+ {96,7,0},{0,8,80},{0,8,16},{132,8,115},{130,7,31},{0,8,112},
+ {0,8,48},{0,9,192},{128,7,10},{0,8,96},{0,8,32},{0,9,160},
+ {0,8,0},{0,8,128},{0,8,64},{0,9,224},{128,7,6},{0,8,88},
+ {0,8,24},{0,9,144},{131,7,59},{0,8,120},{0,8,56},{0,9,208},
+ {129,7,17},{0,8,104},{0,8,40},{0,9,176},{0,8,8},{0,8,136},
+ {0,8,72},{0,9,240},{128,7,4},{0,8,84},{0,8,20},{133,8,227},
+ {131,7,43},{0,8,116},{0,8,52},{0,9,200},{129,7,13},{0,8,100},
+ {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},
+ {128,7,8},{0,8,92},{0,8,28},{0,9,152},{132,7,83},{0,8,124},
+ {0,8,60},{0,9,216},{130,7,23},{0,8,108},{0,8,44},{0,9,184},
+ {0,8,12},{0,8,140},{0,8,76},{0,9,248},{128,7,3},{0,8,82},
+ {0,8,18},{133,8,163},{131,7,35},{0,8,114},{0,8,50},{0,9,196},
+ {129,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},{0,8,130},
+ {0,8,66},{0,9,228},{128,7,7},{0,8,90},{0,8,26},{0,9,148},
+ {132,7,67},{0,8,122},{0,8,58},{0,9,212},{130,7,19},{0,8,106},
+ {0,8,42},{0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},
+ {128,7,5},{0,8,86},{0,8,22},{65,8,0},{131,7,51},{0,8,118},
+ {0,8,54},{0,9,204},{129,7,15},{0,8,102},{0,8,38},{0,9,172},
+ {0,8,6},{0,8,134},{0,8,70},{0,9,236},{128,7,9},{0,8,94},
+ {0,8,30},{0,9,156},{132,7,99},{0,8,126},{0,8,62},{0,9,220},
+ {130,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
+ {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{133,8,131},
+ {130,7,31},{0,8,113},{0,8,49},{0,9,194},{128,7,10},{0,8,97},
+ {0,8,33},{0,9,162},{0,8,1},{0,8,129},{0,8,65},{0,9,226},
+ {128,7,6},{0,8,89},{0,8,25},{0,9,146},{131,7,59},{0,8,121},
+ {0,8,57},{0,9,210},{129,7,17},{0,8,105},{0,8,41},{0,9,178},
+ {0,8,9},{0,8,137},{0,8,73},{0,9,242},{128,7,4},{0,8,85},
+ {0,8,21},{144,8,3},{131,7,43},{0,8,117},{0,8,53},{0,9,202},
+ {129,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},
+ {0,8,69},{0,9,234},{128,7,8},{0,8,93},{0,8,29},{0,9,154},
+ {132,7,83},{0,8,125},{0,8,61},{0,9,218},{130,7,23},{0,8,109},
+ {0,8,45},{0,9,186},{0,8,13},{0,8,141},{0,8,77},{0,9,250},
+ {128,7,3},{0,8,83},{0,8,19},{133,8,195},{131,7,35},{0,8,115},
+ {0,8,51},{0,9,198},{129,7,11},{0,8,99},{0,8,35},{0,9,166},
+ {0,8,3},{0,8,131},{0,8,67},{0,9,230},{128,7,7},{0,8,91},
+ {0,8,27},{0,9,150},{132,7,67},{0,8,123},{0,8,59},{0,9,214},
+ {130,7,19},{0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},
+ {0,8,75},{0,9,246},{128,7,5},{0,8,87},{0,8,23},{77,8,0},
+ {131,7,51},{0,8,119},{0,8,55},{0,9,206},{129,7,15},{0,8,103},
+ {0,8,39},{0,9,174},{0,8,7},{0,8,135},{0,8,71},{0,9,238},
+ {128,7,9},{0,8,95},{0,8,31},{0,9,158},{132,7,99},{0,8,127},
+ {0,8,63},{0,9,222},{130,7,27},{0,8,111},{0,8,47},{0,9,190},
+ {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},
+ {0,8,16},{132,8,115},{130,7,31},{0,8,112},{0,8,48},{0,9,193},
+ {128,7,10},{0,8,96},{0,8,32},{0,9,161},{0,8,0},{0,8,128},
+ {0,8,64},{0,9,225},{128,7,6},{0,8,88},{0,8,24},{0,9,145},
+ {131,7,59},{0,8,120},{0,8,56},{0,9,209},{129,7,17},{0,8,104},
+ {0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},{0,9,241},
+ {128,7,4},{0,8,84},{0,8,20},{133,8,227},{131,7,43},{0,8,116},
+ {0,8,52},{0,9,201},{129,7,13},{0,8,100},{0,8,36},{0,9,169},
+ {0,8,4},{0,8,132},{0,8,68},{0,9,233},{128,7,8},{0,8,92},
+ {0,8,28},{0,9,153},{132,7,83},{0,8,124},{0,8,60},{0,9,217},
+ {130,7,23},{0,8,108},{0,8,44},{0,9,185},{0,8,12},{0,8,140},
+ {0,8,76},{0,9,249},{128,7,3},{0,8,82},{0,8,18},{133,8,163},
+ {131,7,35},{0,8,114},{0,8,50},{0,9,197},{129,7,11},{0,8,98},
+ {0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
+ {128,7,7},{0,8,90},{0,8,26},{0,9,149},{132,7,67},{0,8,122},
+ {0,8,58},{0,9,213},{130,7,19},{0,8,106},{0,8,42},{0,9,181},
+ {0,8,10},{0,8,138},{0,8,74},{0,9,245},{128,7,5},{0,8,86},
+ {0,8,22},{65,8,0},{131,7,51},{0,8,118},{0,8,54},{0,9,205},
+ {129,7,15},{0,8,102},{0,8,38},{0,9,173},{0,8,6},{0,8,134},
+ {0,8,70},{0,9,237},{128,7,9},{0,8,94},{0,8,30},{0,9,157},
+ {132,7,99},{0,8,126},{0,8,62},{0,9,221},{130,7,27},{0,8,110},
+ {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},
+ {96,7,0},{0,8,81},{0,8,17},{133,8,131},{130,7,31},{0,8,113},
+ {0,8,49},{0,9,195},{128,7,10},{0,8,97},{0,8,33},{0,9,163},
+ {0,8,1},{0,8,129},{0,8,65},{0,9,227},{128,7,6},{0,8,89},
+ {0,8,25},{0,9,147},{131,7,59},{0,8,121},{0,8,57},{0,9,211},
+ {129,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},{0,8,137},
+ {0,8,73},{0,9,243},{128,7,4},{0,8,85},{0,8,21},{144,8,3},
+ {131,7,43},{0,8,117},{0,8,53},{0,9,203},{129,7,13},{0,8,101},
+ {0,8,37},{0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},
+ {128,7,8},{0,8,93},{0,8,29},{0,9,155},{132,7,83},{0,8,125},
+ {0,8,61},{0,9,219},{130,7,23},{0,8,109},{0,8,45},{0,9,187},
+ {0,8,13},{0,8,141},{0,8,77},{0,9,251},{128,7,3},{0,8,83},
+ {0,8,19},{133,8,195},{131,7,35},{0,8,115},{0,8,51},{0,9,199},
+ {129,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
+ {0,8,67},{0,9,231},{128,7,7},{0,8,91},{0,8,27},{0,9,151},
+ {132,7,67},{0,8,123},{0,8,59},{0,9,215},{130,7,19},{0,8,107},
+ {0,8,43},{0,9,183},{0,8,11},{0,8,139},{0,8,75},{0,9,247},
+ {128,7,5},{0,8,87},{0,8,23},{77,8,0},{131,7,51},{0,8,119},
+ {0,8,55},{0,9,207},{129,7,15},{0,8,103},{0,8,39},{0,9,175},
+ {0,8,7},{0,8,135},{0,8,71},{0,9,239},{128,7,9},{0,8,95},
+ {0,8,31},{0,9,159},{132,7,99},{0,8,127},{0,8,63},{0,9,223},
+ {130,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},
+ {0,8,79},{0,9,255}
+ };
+
+ static const code distfix[32] = {
+ {128,5,1},{135,5,257},{131,5,17},{139,5,4097},{129,5,5},
+ {137,5,1025},{133,5,65},{141,5,16385},{128,5,3},{136,5,513},
+ {132,5,33},{140,5,8193},{130,5,9},{138,5,2049},{134,5,129},
+ {142,5,32769},{128,5,2},{135,5,385},{131,5,25},{139,5,6145},
+ {129,5,7},{137,5,1537},{133,5,97},{141,5,24577},{128,5,4},
+ {136,5,769},{132,5,49},{140,5,12289},{130,5,13},{138,5,3073},
+ {134,5,193},{142,5,49153}
+ };
ADDED compat/zlib/contrib/infback9/inflate9.h
Index: compat/zlib/contrib/infback9/inflate9.h
==================================================================
--- compat/zlib/contrib/infback9/inflate9.h
+++ compat/zlib/contrib/infback9/inflate9.h
@@ -0,0 +1,47 @@
+/* inflate9.h -- internal inflate state definition
+ * Copyright (C) 1995-2003 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+/* Possible inflate modes between inflate() calls */
+typedef enum {
+ TYPE, /* i: waiting for type bits, including last-flag bit */
+ STORED, /* i: waiting for stored size (length and complement) */
+ TABLE, /* i: waiting for dynamic block table lengths */
+ LEN, /* i: waiting for length/lit code */
+ DONE, /* finished check, done -- remain here until reset */
+ BAD /* got a data error -- remain here until reset */
+} inflate_mode;
+
+/*
+ State transitions between above modes -
+
+ (most modes can go to the BAD mode -- not shown for clarity)
+
+ Read deflate blocks:
+ TYPE -> STORED or TABLE or LEN or DONE
+ STORED -> TYPE
+ TABLE -> LENLENS -> CODELENS -> LEN
+ Read deflate codes:
+ LEN -> LEN or TYPE
+ */
+
+/* state maintained between inflate() calls. Approximately 7K bytes. */
+struct inflate_state {
+ /* sliding window */
+ unsigned char FAR *window; /* allocated sliding window, if needed */
+ /* dynamic table building */
+ unsigned ncode; /* number of code length code lengths */
+ unsigned nlen; /* number of length code lengths */
+ unsigned ndist; /* number of distance code lengths */
+ unsigned have; /* number of code lengths in lens[] */
+ code FAR *next; /* next available space in codes[] */
+ unsigned short lens[320]; /* temporary storage for code lengths */
+ unsigned short work[288]; /* work area for code table building */
+ code codes[ENOUGH]; /* space for code tables */
+};
ADDED compat/zlib/contrib/infback9/inftree9.c
Index: compat/zlib/contrib/infback9/inftree9.c
==================================================================
--- compat/zlib/contrib/infback9/inftree9.c
+++ compat/zlib/contrib/infback9/inftree9.c
@@ -0,0 +1,324 @@
+/* inftree9.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-2022 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftree9.h"
+
+#define MAXBITS 15
+
+const char inflate9_copyright[] =
+ " inflate9 1.2.13 Copyright 1995-2022 Mark Adler ";
+/*
+ If you use the zlib library in a product, an acknowledgment is welcome
+ in the documentation of your product. If for some reason you cannot
+ include such an acknowledgment, I would appreciate that you keep this
+ copyright string in the executable of your product.
+ */
+
+/*
+ Build a set of tables to decode the provided canonical Huffman code.
+ The code lengths are lens[0..codes-1]. The result starts at *table,
+ whose indices are 0..2^bits-1. work is a writable array of at least
+ lens shorts, which is used as a work area. type is the type of code
+ to be generated, CODES, LENS, or DISTS. On return, zero is success,
+ -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
+ on return points to the next available entry's address. bits is the
+ requested root table index bits, and on return it is the actual root
+ table index bits. It will differ if the request is greater than the
+ longest code or if it is less than the shortest code.
+ */
+int inflate_table9(type, lens, codes, table, bits, work)
+codetype type;
+unsigned short FAR *lens;
+unsigned codes;
+code FAR * FAR *table;
+unsigned FAR *bits;
+unsigned short FAR *work;
+{
+ unsigned len; /* a code's length in bits */
+ unsigned sym; /* index of code symbols */
+ unsigned min, max; /* minimum and maximum code lengths */
+ unsigned root; /* number of index bits for root table */
+ unsigned curr; /* number of index bits for current table */
+ unsigned drop; /* code bits to drop for sub-table */
+ int left; /* number of prefix codes available */
+ unsigned used; /* code entries in table used */
+ unsigned huff; /* Huffman code */
+ unsigned incr; /* for incrementing code, index */
+ unsigned fill; /* index for replicating entries */
+ unsigned low; /* low bits for current root entry */
+ unsigned mask; /* mask for low root bits */
+ code this; /* table entry for duplication */
+ code FAR *next; /* next available space in table */
+ const unsigned short FAR *base; /* base value table to use */
+ const unsigned short FAR *extra; /* extra bits table to use */
+ int end; /* use base and extra for symbol > end */
+ unsigned short count[MAXBITS+1]; /* number of codes of each length */
+ unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
+ static const unsigned short lbase[31] = { /* Length codes 257..285 base */
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17,
+ 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
+ 131, 163, 195, 227, 3, 0, 0};
+ static const unsigned short lext[31] = { /* Length codes 257..285 extra */
+ 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129,
+ 130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132,
+ 133, 133, 133, 133, 144, 194, 65};
+ static const unsigned short dbase[32] = { /* Distance codes 0..31 base */
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49,
+ 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073,
+ 4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153};
+ static const unsigned short dext[32] = { /* Distance codes 0..31 extra */
+ 128, 128, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132,
+ 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138,
+ 139, 139, 140, 140, 141, 141, 142, 142};
+
+ /*
+ Process a set of code lengths to create a canonical Huffman code. The
+ code lengths are lens[0..codes-1]. Each length corresponds to the
+ symbols 0..codes-1. The Huffman code is generated by first sorting the
+ symbols by length from short to long, and retaining the symbol order
+ for codes with equal lengths. Then the code starts with all zero bits
+ for the first code of the shortest length, and the codes are integer
+ increments for the same length, and zeros are appended as the length
+ increases. For the deflate format, these bits are stored backwards
+ from their more natural integer increment ordering, and so when the
+ decoding tables are built in the large loop below, the integer codes
+ are incremented backwards.
+
+ This routine assumes, but does not check, that all of the entries in
+ lens[] are in the range 0..MAXBITS. The caller must assure this.
+ 1..MAXBITS is interpreted as that code length. zero means that that
+ symbol does not occur in this code.
+
+ The codes are sorted by computing a count of codes for each length,
+ creating from that a table of starting indices for each length in the
+ sorted table, and then entering the symbols in order in the sorted
+ table. The sorted table is work[], with that space being provided by
+ the caller.
+
+ The length counts are used for other purposes as well, i.e. finding
+ the minimum and maximum length codes, determining if there are any
+ codes at all, checking for a valid set of lengths, and looking ahead
+ at length counts to determine sub-table sizes when building the
+ decoding tables.
+ */
+
+ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
+ for (len = 0; len <= MAXBITS; len++)
+ count[len] = 0;
+ for (sym = 0; sym < codes; sym++)
+ count[lens[sym]]++;
+
+ /* bound code lengths, force root to be within code lengths */
+ root = *bits;
+ for (max = MAXBITS; max >= 1; max--)
+ if (count[max] != 0) break;
+ if (root > max) root = max;
+ if (max == 0) return -1; /* no codes! */
+ for (min = 1; min <= MAXBITS; min++)
+ if (count[min] != 0) break;
+ if (root < min) root = min;
+
+ /* check for an over-subscribed or incomplete set of lengths */
+ left = 1;
+ for (len = 1; len <= MAXBITS; len++) {
+ left <<= 1;
+ left -= count[len];
+ if (left < 0) return -1; /* over-subscribed */
+ }
+ if (left > 0 && (type == CODES || max != 1))
+ return -1; /* incomplete set */
+
+ /* generate offsets into symbol table for each length for sorting */
+ offs[1] = 0;
+ for (len = 1; len < MAXBITS; len++)
+ offs[len + 1] = offs[len] + count[len];
+
+ /* sort symbols by length, by symbol order within each length */
+ for (sym = 0; sym < codes; sym++)
+ if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
+
+ /*
+ Create and fill in decoding tables. In this loop, the table being
+ filled is at next and has curr index bits. The code being used is huff
+ with length len. That code is converted to an index by dropping drop
+ bits off of the bottom. For codes where len is less than drop + curr,
+ those top drop + curr - len bits are incremented through all values to
+ fill the table with replicated entries.
+
+ root is the number of index bits for the root table. When len exceeds
+ root, sub-tables are created pointed to by the root entry with an index
+ of the low root bits of huff. This is saved in low to check for when a
+ new sub-table should be started. drop is zero when the root table is
+ being filled, and drop is root when sub-tables are being filled.
+
+ When a new sub-table is needed, it is necessary to look ahead in the
+ code lengths to determine what size sub-table is needed. The length
+ counts are used for this, and so count[] is decremented as codes are
+ entered in the tables.
+
+ used keeps track of how many table entries have been allocated from the
+ provided *table space. It is checked for LENS and DIST tables against
+ the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+ the initial root table size constants. See the comments in inftree9.h
+ for more information.
+
+ sym increments through all symbols, and the loop terminates when
+ all codes of length max, i.e. all codes, have been processed. This
+ routine permits incomplete codes, so another loop after this one fills
+ in the rest of the decoding tables with invalid code markers.
+ */
+
+ /* set up for code type */
+ switch (type) {
+ case CODES:
+ base = extra = work; /* dummy value--not used */
+ end = 19;
+ break;
+ case LENS:
+ base = lbase;
+ base -= 257;
+ extra = lext;
+ extra -= 257;
+ end = 256;
+ break;
+ default: /* DISTS */
+ base = dbase;
+ extra = dext;
+ end = -1;
+ }
+
+ /* initialize state for loop */
+ huff = 0; /* starting code */
+ sym = 0; /* starting code symbol */
+ len = min; /* starting code length */
+ next = *table; /* current table to fill in */
+ curr = root; /* current table index bits */
+ drop = 0; /* current bits to drop from code for index */
+ low = (unsigned)(-1); /* trigger new sub-table when len > root */
+ used = 1U << root; /* use root table entries */
+ mask = used - 1; /* mask for comparing low */
+
+ /* check available table space */
+ if ((type == LENS && used >= ENOUGH_LENS) ||
+ (type == DISTS && used >= ENOUGH_DISTS))
+ return 1;
+
+ /* process all codes and make table entries */
+ for (;;) {
+ /* create table entry */
+ this.bits = (unsigned char)(len - drop);
+ if ((int)(work[sym]) < end) {
+ this.op = (unsigned char)0;
+ this.val = work[sym];
+ }
+ else if ((int)(work[sym]) > end) {
+ this.op = (unsigned char)(extra[work[sym]]);
+ this.val = base[work[sym]];
+ }
+ else {
+ this.op = (unsigned char)(32 + 64); /* end of block */
+ this.val = 0;
+ }
+
+ /* replicate for those indices with low len bits equal to huff */
+ incr = 1U << (len - drop);
+ fill = 1U << curr;
+ do {
+ fill -= incr;
+ next[(huff >> drop) + fill] = this;
+ } while (fill != 0);
+
+ /* backwards increment the len-bit code huff */
+ incr = 1U << (len - 1);
+ while (huff & incr)
+ incr >>= 1;
+ if (incr != 0) {
+ huff &= incr - 1;
+ huff += incr;
+ }
+ else
+ huff = 0;
+
+ /* go to next symbol, update count, len */
+ sym++;
+ if (--(count[len]) == 0) {
+ if (len == max) break;
+ len = lens[work[sym]];
+ }
+
+ /* create new sub-table if needed */
+ if (len > root && (huff & mask) != low) {
+ /* if first time, transition to sub-tables */
+ if (drop == 0)
+ drop = root;
+
+ /* increment past last table */
+ next += 1U << curr;
+
+ /* determine length of next table */
+ curr = len - drop;
+ left = (int)(1 << curr);
+ while (curr + drop < max) {
+ left -= count[curr + drop];
+ if (left <= 0) break;
+ curr++;
+ left <<= 1;
+ }
+
+ /* check for enough space */
+ used += 1U << curr;
+ if ((type == LENS && used >= ENOUGH_LENS) ||
+ (type == DISTS && used >= ENOUGH_DISTS))
+ return 1;
+
+ /* point entry in root table to sub-table */
+ low = huff & mask;
+ (*table)[low].op = (unsigned char)curr;
+ (*table)[low].bits = (unsigned char)root;
+ (*table)[low].val = (unsigned short)(next - *table);
+ }
+ }
+
+ /*
+ Fill in rest of table for incomplete codes. This loop is similar to the
+ loop above in incrementing huff for table indices. It is assumed that
+ len is equal to curr + drop, so there is no loop needed to increment
+ through high index bits. When the current sub-table is filled, the loop
+ drops back to the root table to fill in any remaining entries there.
+ */
+ this.op = (unsigned char)64; /* invalid code marker */
+ this.bits = (unsigned char)(len - drop);
+ this.val = (unsigned short)0;
+ while (huff != 0) {
+ /* when done with sub-table, drop back to root table */
+ if (drop != 0 && (huff & mask) != low) {
+ drop = 0;
+ len = root;
+ next = *table;
+ curr = root;
+ this.bits = (unsigned char)len;
+ }
+
+ /* put invalid code marker in table */
+ next[huff >> drop] = this;
+
+ /* backwards increment the len-bit code huff */
+ incr = 1U << (len - 1);
+ while (huff & incr)
+ incr >>= 1;
+ if (incr != 0) {
+ huff &= incr - 1;
+ huff += incr;
+ }
+ else
+ huff = 0;
+ }
+
+ /* set return parameters */
+ *table += used;
+ *bits = root;
+ return 0;
+}
ADDED compat/zlib/contrib/infback9/inftree9.h
Index: compat/zlib/contrib/infback9/inftree9.h
==================================================================
--- compat/zlib/contrib/infback9/inftree9.h
+++ compat/zlib/contrib/infback9/inftree9.h
@@ -0,0 +1,61 @@
+/* inftree9.h -- header to use inftree9.c
+ * Copyright (C) 1995-2008 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+ part of the implementation of the compression library and is
+ subject to change. Applications should only use zlib.h.
+ */
+
+/* Structure for decoding tables. Each entry provides either the
+ information needed to do the operation requested by the code that
+ indexed that table entry, or it provides a pointer to another
+ table that indexes more bits of the code. op indicates whether
+ the entry is a pointer to another table, a literal, a length or
+ distance, an end-of-block, or an invalid code. For a table
+ pointer, the low four bits of op is the number of index bits of
+ that table. For a length or distance, the low four bits of op
+ is the number of extra bits to get after the code. bits is
+ the number of bits in this code or part of the code to drop off
+ of the bit buffer. val is the actual byte to output in the case
+ of a literal, the base length or distance, or the offset from
+ the current table to the next table. Each entry is four bytes. */
+typedef struct {
+ unsigned char op; /* operation, extra bits, table bits */
+ unsigned char bits; /* bits in this part of the code */
+ unsigned short val; /* offset in table or code value */
+} code;
+
+/* op values as set by inflate_table():
+ 00000000 - literal
+ 0000tttt - table link, tttt != 0 is the number of table index bits
+ 100eeeee - length or distance, eeee is the number of extra bits
+ 01100000 - end of block
+ 01000000 - invalid code
+ */
+
+/* Maximum size of the dynamic table. The maximum number of code structures is
+ 1446, which is the sum of 852 for literal/length codes and 594 for distance
+ codes. These values were found by exhaustive searches using the program
+ examples/enough.c found in the zlib distribution. The arguments to that
+ program are the number of symbols, the initial root table size, and the
+ maximum bit length of a code. "enough 286 9 15" for literal/length codes
+ returns returns 852, and "enough 32 6 15" for distance codes returns 594.
+ The initial root table size (9 or 6) is found in the fifth argument of the
+ inflate_table() calls in infback9.c. If the root table size is changed,
+ then these maximum sizes would be need to be recalculated and updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 594
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
+
+/* Type of code to build for inflate_table9() */
+typedef enum {
+ CODES,
+ LENS,
+ DISTS
+} codetype;
+
+extern int inflate_table9 OF((codetype type, unsigned short FAR *lens,
+ unsigned codes, code FAR * FAR *table,
+ unsigned FAR *bits, unsigned short FAR *work));
ADDED compat/zlib/contrib/iostream/test.cpp
Index: compat/zlib/contrib/iostream/test.cpp
==================================================================
--- compat/zlib/contrib/iostream/test.cpp
+++ compat/zlib/contrib/iostream/test.cpp
@@ -0,0 +1,24 @@
+
+#include "zfstream.h"
+
+int main() {
+
+ // Construct a stream object with this filebuffer. Anything sent
+ // to this stream will go to standard out.
+ gzofstream os( 1, ios::out );
+
+ // This text is getting compressed and sent to stdout.
+ // To prove this, run 'test | zcat'.
+ os << "Hello, Mommy" << endl;
+
+ os << setcompressionlevel( Z_NO_COMPRESSION );
+ os << "hello, hello, hi, ho!" << endl;
+
+ setcompressionlevel( os, Z_DEFAULT_COMPRESSION )
+ << "I'm compressing again" << endl;
+
+ os.close();
+
+ return 0;
+
+}
ADDED compat/zlib/contrib/iostream/zfstream.cpp
Index: compat/zlib/contrib/iostream/zfstream.cpp
==================================================================
--- compat/zlib/contrib/iostream/zfstream.cpp
+++ compat/zlib/contrib/iostream/zfstream.cpp
@@ -0,0 +1,329 @@
+
+#include "zfstream.h"
+
+gzfilebuf::gzfilebuf() :
+ file(NULL),
+ mode(0),
+ own_file_descriptor(0)
+{ }
+
+gzfilebuf::~gzfilebuf() {
+
+ sync();
+ if ( own_file_descriptor )
+ close();
+
+}
+
+gzfilebuf *gzfilebuf::open( const char *name,
+ int io_mode ) {
+
+ if ( is_open() )
+ return NULL;
+
+ char char_mode[10];
+ char *p = char_mode;
+
+ if ( io_mode & ios::in ) {
+ mode = ios::in;
+ *p++ = 'r';
+ } else if ( io_mode & ios::app ) {
+ mode = ios::app;
+ *p++ = 'a';
+ } else {
+ mode = ios::out;
+ *p++ = 'w';
+ }
+
+ if ( io_mode & ios::binary ) {
+ mode |= ios::binary;
+ *p++ = 'b';
+ }
+
+ // Hard code the compression level
+ if ( io_mode & (ios::out|ios::app )) {
+ *p++ = '9';
+ }
+
+ // Put the end-of-string indicator
+ *p = '\0';
+
+ if ( (file = gzopen(name, char_mode)) == NULL )
+ return NULL;
+
+ own_file_descriptor = 1;
+
+ return this;
+
+}
+
+gzfilebuf *gzfilebuf::attach( int file_descriptor,
+ int io_mode ) {
+
+ if ( is_open() )
+ return NULL;
+
+ char char_mode[10];
+ char *p = char_mode;
+
+ if ( io_mode & ios::in ) {
+ mode = ios::in;
+ *p++ = 'r';
+ } else if ( io_mode & ios::app ) {
+ mode = ios::app;
+ *p++ = 'a';
+ } else {
+ mode = ios::out;
+ *p++ = 'w';
+ }
+
+ if ( io_mode & ios::binary ) {
+ mode |= ios::binary;
+ *p++ = 'b';
+ }
+
+ // Hard code the compression level
+ if ( io_mode & (ios::out|ios::app )) {
+ *p++ = '9';
+ }
+
+ // Put the end-of-string indicator
+ *p = '\0';
+
+ if ( (file = gzdopen(file_descriptor, char_mode)) == NULL )
+ return NULL;
+
+ own_file_descriptor = 0;
+
+ return this;
+
+}
+
+gzfilebuf *gzfilebuf::close() {
+
+ if ( is_open() ) {
+
+ sync();
+ gzclose( file );
+ file = NULL;
+
+ }
+
+ return this;
+
+}
+
+int gzfilebuf::setcompressionlevel( int comp_level ) {
+
+ return gzsetparams(file, comp_level, -2);
+
+}
+
+int gzfilebuf::setcompressionstrategy( int comp_strategy ) {
+
+ return gzsetparams(file, -2, comp_strategy);
+
+}
+
+
+streampos gzfilebuf::seekoff( streamoff off, ios::seek_dir dir, int which ) {
+
+ return streampos(EOF);
+
+}
+
+int gzfilebuf::underflow() {
+
+ // If the file hasn't been opened for reading, error.
+ if ( !is_open() || !(mode & ios::in) )
+ return EOF;
+
+ // if a buffer doesn't exists, allocate one.
+ if ( !base() ) {
+
+ if ( (allocate()) == EOF )
+ return EOF;
+ setp(0,0);
+
+ } else {
+
+ if ( in_avail() )
+ return (unsigned char) *gptr();
+
+ if ( out_waiting() ) {
+ if ( flushbuf() == EOF )
+ return EOF;
+ }
+
+ }
+
+ // Attempt to fill the buffer.
+
+ int result = fillbuf();
+ if ( result == EOF ) {
+ // disable get area
+ setg(0,0,0);
+ return EOF;
+ }
+
+ return (unsigned char) *gptr();
+
+}
+
+int gzfilebuf::overflow( int c ) {
+
+ if ( !is_open() || !(mode & ios::out) )
+ return EOF;
+
+ if ( !base() ) {
+ if ( allocate() == EOF )
+ return EOF;
+ setg(0,0,0);
+ } else {
+ if (in_avail()) {
+ return EOF;
+ }
+ if (out_waiting()) {
+ if (flushbuf() == EOF)
+ return EOF;
+ }
+ }
+
+ int bl = blen();
+ setp( base(), base() + bl);
+
+ if ( c != EOF ) {
+
+ *pptr() = c;
+ pbump(1);
+
+ }
+
+ return 0;
+
+}
+
+int gzfilebuf::sync() {
+
+ if ( !is_open() )
+ return EOF;
+
+ if ( out_waiting() )
+ return flushbuf();
+
+ return 0;
+
+}
+
+int gzfilebuf::flushbuf() {
+
+ int n;
+ char *q;
+
+ q = pbase();
+ n = pptr() - q;
+
+ if ( gzwrite( file, q, n) < n )
+ return EOF;
+
+ setp(0,0);
+
+ return 0;
+
+}
+
+int gzfilebuf::fillbuf() {
+
+ int required;
+ char *p;
+
+ p = base();
+
+ required = blen();
+
+ int t = gzread( file, p, required );
+
+ if ( t <= 0) return EOF;
+
+ setg( base(), base(), base()+t);
+
+ return t;
+
+}
+
+gzfilestream_common::gzfilestream_common() :
+ ios( gzfilestream_common::rdbuf() )
+{ }
+
+gzfilestream_common::~gzfilestream_common()
+{ }
+
+void gzfilestream_common::attach( int fd, int io_mode ) {
+
+ if ( !buffer.attach( fd, io_mode) )
+ clear( ios::failbit | ios::badbit );
+ else
+ clear();
+
+}
+
+void gzfilestream_common::open( const char *name, int io_mode ) {
+
+ if ( !buffer.open( name, io_mode ) )
+ clear( ios::failbit | ios::badbit );
+ else
+ clear();
+
+}
+
+void gzfilestream_common::close() {
+
+ if ( !buffer.close() )
+ clear( ios::failbit | ios::badbit );
+
+}
+
+gzfilebuf *gzfilestream_common::rdbuf()
+{
+ return &buffer;
+}
+
+gzifstream::gzifstream() :
+ ios( gzfilestream_common::rdbuf() )
+{
+ clear( ios::badbit );
+}
+
+gzifstream::gzifstream( const char *name, int io_mode ) :
+ ios( gzfilestream_common::rdbuf() )
+{
+ gzfilestream_common::open( name, io_mode );
+}
+
+gzifstream::gzifstream( int fd, int io_mode ) :
+ ios( gzfilestream_common::rdbuf() )
+{
+ gzfilestream_common::attach( fd, io_mode );
+}
+
+gzifstream::~gzifstream() { }
+
+gzofstream::gzofstream() :
+ ios( gzfilestream_common::rdbuf() )
+{
+ clear( ios::badbit );
+}
+
+gzofstream::gzofstream( const char *name, int io_mode ) :
+ ios( gzfilestream_common::rdbuf() )
+{
+ gzfilestream_common::open( name, io_mode );
+}
+
+gzofstream::gzofstream( int fd, int io_mode ) :
+ ios( gzfilestream_common::rdbuf() )
+{
+ gzfilestream_common::attach( fd, io_mode );
+}
+
+gzofstream::~gzofstream() { }
ADDED compat/zlib/contrib/iostream/zfstream.h
Index: compat/zlib/contrib/iostream/zfstream.h
==================================================================
--- compat/zlib/contrib/iostream/zfstream.h
+++ compat/zlib/contrib/iostream/zfstream.h
@@ -0,0 +1,128 @@
+
+#ifndef zfstream_h
+#define zfstream_h
+
+#include
+#include "zlib.h"
+
+class gzfilebuf : public streambuf {
+
+public:
+
+ gzfilebuf( );
+ virtual ~gzfilebuf();
+
+ gzfilebuf *open( const char *name, int io_mode );
+ gzfilebuf *attach( int file_descriptor, int io_mode );
+ gzfilebuf *close();
+
+ int setcompressionlevel( int comp_level );
+ int setcompressionstrategy( int comp_strategy );
+
+ inline int is_open() const { return (file !=NULL); }
+
+ virtual streampos seekoff( streamoff, ios::seek_dir, int );
+
+ virtual int sync();
+
+protected:
+
+ virtual int underflow();
+ virtual int overflow( int = EOF );
+
+private:
+
+ gzFile file;
+ short mode;
+ short own_file_descriptor;
+
+ int flushbuf();
+ int fillbuf();
+
+};
+
+class gzfilestream_common : virtual public ios {
+
+ friend class gzifstream;
+ friend class gzofstream;
+ friend gzofstream &setcompressionlevel( gzofstream &, int );
+ friend gzofstream &setcompressionstrategy( gzofstream &, int );
+
+public:
+ virtual ~gzfilestream_common();
+
+ void attach( int fd, int io_mode );
+ void open( const char *name, int io_mode );
+ void close();
+
+protected:
+ gzfilestream_common();
+
+private:
+ gzfilebuf *rdbuf();
+
+ gzfilebuf buffer;
+
+};
+
+class gzifstream : public gzfilestream_common, public istream {
+
+public:
+
+ gzifstream();
+ gzifstream( const char *name, int io_mode = ios::in );
+ gzifstream( int fd, int io_mode = ios::in );
+
+ virtual ~gzifstream();
+
+};
+
+class gzofstream : public gzfilestream_common, public ostream {
+
+public:
+
+ gzofstream();
+ gzofstream( const char *name, int io_mode = ios::out );
+ gzofstream( int fd, int io_mode = ios::out );
+
+ virtual ~gzofstream();
+
+};
+
+template class gzomanip {
+ friend gzofstream &operator<<(gzofstream &, const gzomanip &);
+public:
+ gzomanip(gzofstream &(*f)(gzofstream &, T), T v) : func(f), val(v) { }
+private:
+ gzofstream &(*func)(gzofstream &, T);
+ T val;
+};
+
+template gzofstream &operator<<(gzofstream &s, const gzomanip &m)
+{
+ return (*m.func)(s, m.val);
+}
+
+inline gzofstream &setcompressionlevel( gzofstream &s, int l )
+{
+ (s.rdbuf())->setcompressionlevel(l);
+ return s;
+}
+
+inline gzofstream &setcompressionstrategy( gzofstream &s, int l )
+{
+ (s.rdbuf())->setcompressionstrategy(l);
+ return s;
+}
+
+inline gzomanip setcompressionlevel(int l)
+{
+ return gzomanip(&setcompressionlevel,l);
+}
+
+inline gzomanip setcompressionstrategy(int l)
+{
+ return gzomanip(&setcompressionstrategy,l);
+}
+
+#endif
ADDED compat/zlib/contrib/iostream2/zstream.h
Index: compat/zlib/contrib/iostream2/zstream.h
==================================================================
--- compat/zlib/contrib/iostream2/zstream.h
+++ compat/zlib/contrib/iostream2/zstream.h
@@ -0,0 +1,307 @@
+/*
+ *
+ * Copyright (c) 1997
+ * Christian Michelsen Research AS
+ * Advanced Computing
+ * Fantoftvegen 38, 5036 BERGEN, Norway
+ * http://www.cmr.no
+ *
+ * Permission to use, copy, modify, distribute and sell this software
+ * and its documentation for any purpose is hereby granted without fee,
+ * provided that the above copyright notice appear in all copies and
+ * that both that copyright notice and this permission notice appear
+ * in supporting documentation. Christian Michelsen Research AS makes no
+ * representations about the suitability of this software for any
+ * purpose. It is provided "as is" without express or implied warranty.
+ *
+ */
+
+#ifndef ZSTREAM__H
+#define ZSTREAM__H
+
+/*
+ * zstream.h - C++ interface to the 'zlib' general purpose compression library
+ * $Id: zstream.h 1.1 1997-06-25 12:00:56+02 tyge Exp tyge $
+ */
+
+#include
+#include
+#include
+#include "zlib.h"
+
+#if defined(_WIN32)
+# include
+# include
+# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+#else
+# define SET_BINARY_MODE(file)
+#endif
+
+class zstringlen {
+public:
+ zstringlen(class izstream&);
+ zstringlen(class ozstream&, const char*);
+ size_t value() const { return val.word; }
+private:
+ struct Val { unsigned char byte; size_t word; } val;
+};
+
+// ----------------------------- izstream -----------------------------
+
+class izstream
+{
+ public:
+ izstream() : m_fp(0) {}
+ izstream(FILE* fp) : m_fp(0) { open(fp); }
+ izstream(const char* name) : m_fp(0) { open(name); }
+ ~izstream() { close(); }
+
+ /* Opens a gzip (.gz) file for reading.
+ * open() can be used to read a file which is not in gzip format;
+ * in this case read() will directly read from the file without
+ * decompression. errno can be checked to distinguish two error
+ * cases (if errno is zero, the zlib error is Z_MEM_ERROR).
+ */
+ void open(const char* name) {
+ if (m_fp) close();
+ m_fp = ::gzopen(name, "rb");
+ }
+
+ void open(FILE* fp) {
+ SET_BINARY_MODE(fp);
+ if (m_fp) close();
+ m_fp = ::gzdopen(fileno(fp), "rb");
+ }
+
+ /* Flushes all pending input if necessary, closes the compressed file
+ * and deallocates all the (de)compression state. The return value is
+ * the zlib error number (see function error() below).
+ */
+ int close() {
+ int r = ::gzclose(m_fp);
+ m_fp = 0; return r;
+ }
+
+ /* Binary read the given number of bytes from the compressed file.
+ */
+ int read(void* buf, size_t len) {
+ return ::gzread(m_fp, buf, len);
+ }
+
+ /* Returns the error message for the last error which occurred on the
+ * given compressed file. errnum is set to zlib error number. If an
+ * error occurred in the file system and not in the compression library,
+ * errnum is set to Z_ERRNO and the application may consult errno
+ * to get the exact error code.
+ */
+ const char* error(int* errnum) {
+ return ::gzerror(m_fp, errnum);
+ }
+
+ gzFile fp() { return m_fp; }
+
+ private:
+ gzFile m_fp;
+};
+
+/*
+ * Binary read the given (array of) object(s) from the compressed file.
+ * If the input file was not in gzip format, read() copies the objects number
+ * of bytes into the buffer.
+ * returns the number of uncompressed bytes actually read
+ * (0 for end of file, -1 for error).
+ */
+template
+inline int read(izstream& zs, T* x, Items items) {
+ return ::gzread(zs.fp(), x, items*sizeof(T));
+}
+
+/*
+ * Binary input with the '>' operator.
+ */
+template
+inline izstream& operator>(izstream& zs, T& x) {
+ ::gzread(zs.fp(), &x, sizeof(T));
+ return zs;
+}
+
+
+inline zstringlen::zstringlen(izstream& zs) {
+ zs > val.byte;
+ if (val.byte == 255) zs > val.word;
+ else val.word = val.byte;
+}
+
+/*
+ * Read length of string + the string with the '>' operator.
+ */
+inline izstream& operator>(izstream& zs, char* x) {
+ zstringlen len(zs);
+ ::gzread(zs.fp(), x, len.value());
+ x[len.value()] = '\0';
+ return zs;
+}
+
+inline char* read_string(izstream& zs) {
+ zstringlen len(zs);
+ char* x = new char[len.value()+1];
+ ::gzread(zs.fp(), x, len.value());
+ x[len.value()] = '\0';
+ return x;
+}
+
+// ----------------------------- ozstream -----------------------------
+
+class ozstream
+{
+ public:
+ ozstream() : m_fp(0), m_os(0) {
+ }
+ ozstream(FILE* fp, int level = Z_DEFAULT_COMPRESSION)
+ : m_fp(0), m_os(0) {
+ open(fp, level);
+ }
+ ozstream(const char* name, int level = Z_DEFAULT_COMPRESSION)
+ : m_fp(0), m_os(0) {
+ open(name, level);
+ }
+ ~ozstream() {
+ close();
+ }
+
+ /* Opens a gzip (.gz) file for writing.
+ * The compression level parameter should be in 0..9
+ * errno can be checked to distinguish two error cases
+ * (if errno is zero, the zlib error is Z_MEM_ERROR).
+ */
+ void open(const char* name, int level = Z_DEFAULT_COMPRESSION) {
+ char mode[4] = "wb\0";
+ if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level;
+ if (m_fp) close();
+ m_fp = ::gzopen(name, mode);
+ }
+
+ /* open from a FILE pointer.
+ */
+ void open(FILE* fp, int level = Z_DEFAULT_COMPRESSION) {
+ SET_BINARY_MODE(fp);
+ char mode[4] = "wb\0";
+ if (level != Z_DEFAULT_COMPRESSION) mode[2] = '0'+level;
+ if (m_fp) close();
+ m_fp = ::gzdopen(fileno(fp), mode);
+ }
+
+ /* Flushes all pending output if necessary, closes the compressed file
+ * and deallocates all the (de)compression state. The return value is
+ * the zlib error number (see function error() below).
+ */
+ int close() {
+ if (m_os) {
+ ::gzwrite(m_fp, m_os->str(), m_os->pcount());
+ delete[] m_os->str(); delete m_os; m_os = 0;
+ }
+ int r = ::gzclose(m_fp); m_fp = 0; return r;
+ }
+
+ /* Binary write the given number of bytes into the compressed file.
+ */
+ int write(const void* buf, size_t len) {
+ return ::gzwrite(m_fp, (voidp) buf, len);
+ }
+
+ /* Flushes all pending output into the compressed file. The parameter
+ * _flush is as in the deflate() function. The return value is the zlib
+ * error number (see function gzerror below). flush() returns Z_OK if
+ * the flush_ parameter is Z_FINISH and all output could be flushed.
+ * flush() should be called only when strictly necessary because it can
+ * degrade compression.
+ */
+ int flush(int _flush) {
+ os_flush();
+ return ::gzflush(m_fp, _flush);
+ }
+
+ /* Returns the error message for the last error which occurred on the
+ * given compressed file. errnum is set to zlib error number. If an
+ * error occurred in the file system and not in the compression library,
+ * errnum is set to Z_ERRNO and the application may consult errno
+ * to get the exact error code.
+ */
+ const char* error(int* errnum) {
+ return ::gzerror(m_fp, errnum);
+ }
+
+ gzFile fp() { return m_fp; }
+
+ ostream& os() {
+ if (m_os == 0) m_os = new ostrstream;
+ return *m_os;
+ }
+
+ void os_flush() {
+ if (m_os && m_os->pcount()>0) {
+ ostrstream* oss = new ostrstream;
+ oss->fill(m_os->fill());
+ oss->flags(m_os->flags());
+ oss->precision(m_os->precision());
+ oss->width(m_os->width());
+ ::gzwrite(m_fp, m_os->str(), m_os->pcount());
+ delete[] m_os->str(); delete m_os; m_os = oss;
+ }
+ }
+
+ private:
+ gzFile m_fp;
+ ostrstream* m_os;
+};
+
+/*
+ * Binary write the given (array of) object(s) into the compressed file.
+ * returns the number of uncompressed bytes actually written
+ * (0 in case of error).
+ */
+template
+inline int write(ozstream& zs, const T* x, Items items) {
+ return ::gzwrite(zs.fp(), (voidp) x, items*sizeof(T));
+}
+
+/*
+ * Binary output with the '<' operator.
+ */
+template
+inline ozstream& operator<(ozstream& zs, const T& x) {
+ ::gzwrite(zs.fp(), (voidp) &x, sizeof(T));
+ return zs;
+}
+
+inline zstringlen::zstringlen(ozstream& zs, const char* x) {
+ val.byte = 255; val.word = ::strlen(x);
+ if (val.word < 255) zs < (val.byte = val.word);
+ else zs < val;
+}
+
+/*
+ * Write length of string + the string with the '<' operator.
+ */
+inline ozstream& operator<(ozstream& zs, const char* x) {
+ zstringlen len(zs, x);
+ ::gzwrite(zs.fp(), (voidp) x, len.value());
+ return zs;
+}
+
+#ifdef _MSC_VER
+inline ozstream& operator<(ozstream& zs, char* const& x) {
+ return zs < (const char*) x;
+}
+#endif
+
+/*
+ * Ascii write with the << operator;
+ */
+template
+inline ostream& operator<<(ozstream& zs, const T& x) {
+ zs.os_flush();
+ return zs.os() << x;
+}
+
+#endif
ADDED compat/zlib/contrib/iostream2/zstream_test.cpp
Index: compat/zlib/contrib/iostream2/zstream_test.cpp
==================================================================
--- compat/zlib/contrib/iostream2/zstream_test.cpp
+++ compat/zlib/contrib/iostream2/zstream_test.cpp
@@ -0,0 +1,25 @@
+#include "zstream.h"
+#include
+#include
+#include
+
+void main() {
+ char h[256] = "Hello";
+ char* g = "Goodbye";
+ ozstream out("temp.gz");
+ out < "This works well" < h < g;
+ out.close();
+
+ izstream in("temp.gz"); // read it back
+ char *x = read_string(in), *y = new char[256], z[256];
+ in > y > z;
+ in.close();
+ cout << x << endl << y << endl << z << endl;
+
+ out.open("temp.gz"); // try ascii output; zcat temp.gz to see the results
+ out << setw(50) << setfill('#') << setprecision(20) << x << endl << y << endl << z << endl;
+ out << z << endl << y << endl << x << endl;
+ out << 1.1234567890123456789 << endl;
+
+ delete[] x; delete[] y;
+}
ADDED compat/zlib/contrib/iostream3/README
Index: compat/zlib/contrib/iostream3/README
==================================================================
--- compat/zlib/contrib/iostream3/README
+++ compat/zlib/contrib/iostream3/README
@@ -0,0 +1,35 @@
+These classes provide a C++ stream interface to the zlib library. It allows you
+to do things like:
+
+ gzofstream outf("blah.gz");
+ outf << "These go into the gzip file " << 123 << endl;
+
+It does this by deriving a specialized stream buffer for gzipped files, which is
+the way Stroustrup would have done it. :->
+
+The gzifstream and gzofstream classes were originally written by Kevin Ruland
+and made available in the zlib contrib/iostream directory. The older version still
+compiles under gcc 2.xx, but not under gcc 3.xx, which sparked the development of
+this version.
+
+The new classes are as standard-compliant as possible, closely following the
+approach of the standard library's fstream classes. It compiles under gcc versions
+3.2 and 3.3, but not under gcc 2.xx. This is mainly due to changes in the standard
+library naming scheme. The new version of gzifstream/gzofstream/gzfilebuf differs
+from the previous one in the following respects:
+- added showmanyc
+- added setbuf, with support for unbuffered output via setbuf(0,0)
+- a few bug fixes of stream behavior
+- gzipped output file opened with default compression level instead of maximum level
+- setcompressionlevel()/strategy() members replaced by single setcompression()
+
+The code is provided "as is", with the permission to use, copy, modify, distribute
+and sell it for any purpose without fee.
+
+Ludwig Schwardt
+
+
+DSP Lab
+Electrical & Electronic Engineering Department
+University of Stellenbosch
+South Africa
ADDED compat/zlib/contrib/iostream3/TODO
Index: compat/zlib/contrib/iostream3/TODO
==================================================================
--- compat/zlib/contrib/iostream3/TODO
+++ compat/zlib/contrib/iostream3/TODO
@@ -0,0 +1,17 @@
+Possible upgrades to gzfilebuf:
+
+- The ability to do putback (e.g. putbackfail)
+
+- The ability to seek (zlib supports this, but could be slow/tricky)
+
+- Simultaneous read/write access (does it make sense?)
+
+- Support for ios_base::ate open mode
+
+- Locale support?
+
+- Check public interface to see which calls give problems
+ (due to dependence on library internals)
+
+- Override operator<<(ostream&, gzfilebuf*) to allow direct copying
+ of stream buffer to stream ( i.e. os << is.rdbuf(); )
ADDED compat/zlib/contrib/iostream3/test.cc
Index: compat/zlib/contrib/iostream3/test.cc
==================================================================
--- compat/zlib/contrib/iostream3/test.cc
+++ compat/zlib/contrib/iostream3/test.cc
@@ -0,0 +1,50 @@
+/*
+ * Test program for gzifstream and gzofstream
+ *
+ * by Ludwig Schwardt
+ * original version by Kevin Ruland
+ */
+
+#include "zfstream.h"
+#include // for cout
+
+int main() {
+
+ gzofstream outf;
+ gzifstream inf;
+ char buf[80];
+
+ outf.open("test1.txt.gz");
+ outf << "The quick brown fox sidestepped the lazy canine\n"
+ << 1.3 << "\nPlan " << 9 << std::endl;
+ outf.close();
+ std::cout << "Wrote the following message to 'test1.txt.gz' (check with zcat or zless):\n"
+ << "The quick brown fox sidestepped the lazy canine\n"
+ << 1.3 << "\nPlan " << 9 << std::endl;
+
+ std::cout << "\nReading 'test1.txt.gz' (buffered) produces:\n";
+ inf.open("test1.txt.gz");
+ while (inf.getline(buf,80,'\n')) {
+ std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n";
+ }
+ inf.close();
+
+ outf.rdbuf()->pubsetbuf(0,0);
+ outf.open("test2.txt.gz");
+ outf << setcompression(Z_NO_COMPRESSION)
+ << "The quick brown fox sidestepped the lazy canine\n"
+ << 1.3 << "\nPlan " << 9 << std::endl;
+ outf.close();
+ std::cout << "\nWrote the same message to 'test2.txt.gz' in uncompressed form";
+
+ std::cout << "\nReading 'test2.txt.gz' (unbuffered) produces:\n";
+ inf.rdbuf()->pubsetbuf(0,0);
+ inf.open("test2.txt.gz");
+ while (inf.getline(buf,80,'\n')) {
+ std::cout << buf << "\t(" << inf.rdbuf()->in_avail() << " chars left in buffer)\n";
+ }
+ inf.close();
+
+ return 0;
+
+}
ADDED compat/zlib/contrib/iostream3/zfstream.cc
Index: compat/zlib/contrib/iostream3/zfstream.cc
==================================================================
--- compat/zlib/contrib/iostream3/zfstream.cc
+++ compat/zlib/contrib/iostream3/zfstream.cc
@@ -0,0 +1,479 @@
+/*
+ * A C++ I/O streams interface to the zlib gz* functions
+ *
+ * by Ludwig Schwardt
+ * original version by Kevin Ruland
+ *
+ * This version is standard-compliant and compatible with gcc 3.x.
+ */
+
+#include "zfstream.h"
+#include // for strcpy, strcat, strlen (mode strings)
+#include // for BUFSIZ
+
+// Internal buffer sizes (default and "unbuffered" versions)
+#define BIGBUFSIZE BUFSIZ
+#define SMALLBUFSIZE 1
+
+/*****************************************************************************/
+
+// Default constructor
+gzfilebuf::gzfilebuf()
+: file(NULL), io_mode(std::ios_base::openmode(0)), own_fd(false),
+ buffer(NULL), buffer_size(BIGBUFSIZE), own_buffer(true)
+{
+ // No buffers to start with
+ this->disable_buffer();
+}
+
+// Destructor
+gzfilebuf::~gzfilebuf()
+{
+ // Sync output buffer and close only if responsible for file
+ // (i.e. attached streams should be left open at this stage)
+ this->sync();
+ if (own_fd)
+ this->close();
+ // Make sure internal buffer is deallocated
+ this->disable_buffer();
+}
+
+// Set compression level and strategy
+int
+gzfilebuf::setcompression(int comp_level,
+ int comp_strategy)
+{
+ return gzsetparams(file, comp_level, comp_strategy);
+}
+
+// Open gzipped file
+gzfilebuf*
+gzfilebuf::open(const char *name,
+ std::ios_base::openmode mode)
+{
+ // Fail if file already open
+ if (this->is_open())
+ return NULL;
+ // Don't support simultaneous read/write access (yet)
+ if ((mode & std::ios_base::in) && (mode & std::ios_base::out))
+ return NULL;
+
+ // Build mode string for gzopen and check it [27.8.1.3.2]
+ char char_mode[6] = "\0\0\0\0\0";
+ if (!this->open_mode(mode, char_mode))
+ return NULL;
+
+ // Attempt to open file
+ if ((file = gzopen(name, char_mode)) == NULL)
+ return NULL;
+
+ // On success, allocate internal buffer and set flags
+ this->enable_buffer();
+ io_mode = mode;
+ own_fd = true;
+ return this;
+}
+
+// Attach to gzipped file
+gzfilebuf*
+gzfilebuf::attach(int fd,
+ std::ios_base::openmode mode)
+{
+ // Fail if file already open
+ if (this->is_open())
+ return NULL;
+ // Don't support simultaneous read/write access (yet)
+ if ((mode & std::ios_base::in) && (mode & std::ios_base::out))
+ return NULL;
+
+ // Build mode string for gzdopen and check it [27.8.1.3.2]
+ char char_mode[6] = "\0\0\0\0\0";
+ if (!this->open_mode(mode, char_mode))
+ return NULL;
+
+ // Attempt to attach to file
+ if ((file = gzdopen(fd, char_mode)) == NULL)
+ return NULL;
+
+ // On success, allocate internal buffer and set flags
+ this->enable_buffer();
+ io_mode = mode;
+ own_fd = false;
+ return this;
+}
+
+// Close gzipped file
+gzfilebuf*
+gzfilebuf::close()
+{
+ // Fail immediately if no file is open
+ if (!this->is_open())
+ return NULL;
+ // Assume success
+ gzfilebuf* retval = this;
+ // Attempt to sync and close gzipped file
+ if (this->sync() == -1)
+ retval = NULL;
+ if (gzclose(file) < 0)
+ retval = NULL;
+ // File is now gone anyway (postcondition [27.8.1.3.8])
+ file = NULL;
+ own_fd = false;
+ // Destroy internal buffer if it exists
+ this->disable_buffer();
+ return retval;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+// Convert int open mode to mode string
+bool
+gzfilebuf::open_mode(std::ios_base::openmode mode,
+ char* c_mode) const
+{
+ bool testb = mode & std::ios_base::binary;
+ bool testi = mode & std::ios_base::in;
+ bool testo = mode & std::ios_base::out;
+ bool testt = mode & std::ios_base::trunc;
+ bool testa = mode & std::ios_base::app;
+
+ // Check for valid flag combinations - see [27.8.1.3.2] (Table 92)
+ // Original zfstream hardcoded the compression level to maximum here...
+ // Double the time for less than 1% size improvement seems
+ // excessive though - keeping it at the default level
+ // To change back, just append "9" to the next three mode strings
+ if (!testi && testo && !testt && !testa)
+ strcpy(c_mode, "w");
+ if (!testi && testo && !testt && testa)
+ strcpy(c_mode, "a");
+ if (!testi && testo && testt && !testa)
+ strcpy(c_mode, "w");
+ if (testi && !testo && !testt && !testa)
+ strcpy(c_mode, "r");
+ // No read/write mode yet
+// if (testi && testo && !testt && !testa)
+// strcpy(c_mode, "r+");
+// if (testi && testo && testt && !testa)
+// strcpy(c_mode, "w+");
+
+ // Mode string should be empty for invalid combination of flags
+ if (strlen(c_mode) == 0)
+ return false;
+ if (testb)
+ strcat(c_mode, "b");
+ return true;
+}
+
+// Determine number of characters in internal get buffer
+std::streamsize
+gzfilebuf::showmanyc()
+{
+ // Calls to underflow will fail if file not opened for reading
+ if (!this->is_open() || !(io_mode & std::ios_base::in))
+ return -1;
+ // Make sure get area is in use
+ if (this->gptr() && (this->gptr() < this->egptr()))
+ return std::streamsize(this->egptr() - this->gptr());
+ else
+ return 0;
+}
+
+// Fill get area from gzipped file
+gzfilebuf::int_type
+gzfilebuf::underflow()
+{
+ // If something is left in the get area by chance, return it
+ // (this shouldn't normally happen, as underflow is only supposed
+ // to be called when gptr >= egptr, but it serves as error check)
+ if (this->gptr() && (this->gptr() < this->egptr()))
+ return traits_type::to_int_type(*(this->gptr()));
+
+ // If the file hasn't been opened for reading, produce error
+ if (!this->is_open() || !(io_mode & std::ios_base::in))
+ return traits_type::eof();
+
+ // Attempt to fill internal buffer from gzipped file
+ // (buffer must be guaranteed to exist...)
+ int bytes_read = gzread(file, buffer, buffer_size);
+ // Indicates error or EOF
+ if (bytes_read <= 0)
+ {
+ // Reset get area
+ this->setg(buffer, buffer, buffer);
+ return traits_type::eof();
+ }
+ // Make all bytes read from file available as get area
+ this->setg(buffer, buffer, buffer + bytes_read);
+
+ // Return next character in get area
+ return traits_type::to_int_type(*(this->gptr()));
+}
+
+// Write put area to gzipped file
+gzfilebuf::int_type
+gzfilebuf::overflow(int_type c)
+{
+ // Determine whether put area is in use
+ if (this->pbase())
+ {
+ // Double-check pointer range
+ if (this->pptr() > this->epptr() || this->pptr() < this->pbase())
+ return traits_type::eof();
+ // Add extra character to buffer if not EOF
+ if (!traits_type::eq_int_type(c, traits_type::eof()))
+ {
+ *(this->pptr()) = traits_type::to_char_type(c);
+ this->pbump(1);
+ }
+ // Number of characters to write to file
+ int bytes_to_write = this->pptr() - this->pbase();
+ // Overflow doesn't fail if nothing is to be written
+ if (bytes_to_write > 0)
+ {
+ // If the file hasn't been opened for writing, produce error
+ if (!this->is_open() || !(io_mode & std::ios_base::out))
+ return traits_type::eof();
+ // If gzipped file won't accept all bytes written to it, fail
+ if (gzwrite(file, this->pbase(), bytes_to_write) != bytes_to_write)
+ return traits_type::eof();
+ // Reset next pointer to point to pbase on success
+ this->pbump(-bytes_to_write);
+ }
+ }
+ // Write extra character to file if not EOF
+ else if (!traits_type::eq_int_type(c, traits_type::eof()))
+ {
+ // If the file hasn't been opened for writing, produce error
+ if (!this->is_open() || !(io_mode & std::ios_base::out))
+ return traits_type::eof();
+ // Impromptu char buffer (allows "unbuffered" output)
+ char_type last_char = traits_type::to_char_type(c);
+ // If gzipped file won't accept this character, fail
+ if (gzwrite(file, &last_char, 1) != 1)
+ return traits_type::eof();
+ }
+
+ // If you got here, you have succeeded (even if c was EOF)
+ // The return value should therefore be non-EOF
+ if (traits_type::eq_int_type(c, traits_type::eof()))
+ return traits_type::not_eof(c);
+ else
+ return c;
+}
+
+// Assign new buffer
+std::streambuf*
+gzfilebuf::setbuf(char_type* p,
+ std::streamsize n)
+{
+ // First make sure stuff is sync'ed, for safety
+ if (this->sync() == -1)
+ return NULL;
+ // If buffering is turned off on purpose via setbuf(0,0), still allocate one...
+ // "Unbuffered" only really refers to put [27.8.1.4.10], while get needs at
+ // least a buffer of size 1 (very inefficient though, therefore make it bigger?)
+ // This follows from [27.5.2.4.3]/12 (gptr needs to point at something, it seems)
+ if (!p || !n)
+ {
+ // Replace existing buffer (if any) with small internal buffer
+ this->disable_buffer();
+ buffer = NULL;
+ buffer_size = 0;
+ own_buffer = true;
+ this->enable_buffer();
+ }
+ else
+ {
+ // Replace existing buffer (if any) with external buffer
+ this->disable_buffer();
+ buffer = p;
+ buffer_size = n;
+ own_buffer = false;
+ this->enable_buffer();
+ }
+ return this;
+}
+
+// Write put area to gzipped file (i.e. ensures that put area is empty)
+int
+gzfilebuf::sync()
+{
+ return traits_type::eq_int_type(this->overflow(), traits_type::eof()) ? -1 : 0;
+}
+
+/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
+
+// Allocate internal buffer
+void
+gzfilebuf::enable_buffer()
+{
+ // If internal buffer required, allocate one
+ if (own_buffer && !buffer)
+ {
+ // Check for buffered vs. "unbuffered"
+ if (buffer_size > 0)
+ {
+ // Allocate internal buffer
+ buffer = new char_type[buffer_size];
+ // Get area starts empty and will be expanded by underflow as need arises
+ this->setg(buffer, buffer, buffer);
+ // Setup entire internal buffer as put area.
+ // The one-past-end pointer actually points to the last element of the buffer,
+ // so that overflow(c) can safely add the extra character c to the sequence.
+ // These pointers remain in place for the duration of the buffer
+ this->setp(buffer, buffer + buffer_size - 1);
+ }
+ else
+ {
+ // Even in "unbuffered" case, (small?) get buffer is still required
+ buffer_size = SMALLBUFSIZE;
+ buffer = new char_type[buffer_size];
+ this->setg(buffer, buffer, buffer);
+ // "Unbuffered" means no put buffer
+ this->setp(0, 0);
+ }
+ }
+ else
+ {
+ // If buffer already allocated, reset buffer pointers just to make sure no
+ // stale chars are lying around
+ this->setg(buffer, buffer, buffer);
+ this->setp(buffer, buffer + buffer_size - 1);
+ }
+}
+
+// Destroy internal buffer
+void
+gzfilebuf::disable_buffer()
+{
+ // If internal buffer exists, deallocate it
+ if (own_buffer && buffer)
+ {
+ // Preserve unbuffered status by zeroing size
+ if (!this->pbase())
+ buffer_size = 0;
+ delete[] buffer;
+ buffer = NULL;
+ this->setg(0, 0, 0);
+ this->setp(0, 0);
+ }
+ else
+ {
+ // Reset buffer pointers to initial state if external buffer exists
+ this->setg(buffer, buffer, buffer);
+ if (buffer)
+ this->setp(buffer, buffer + buffer_size - 1);
+ else
+ this->setp(0, 0);
+ }
+}
+
+/*****************************************************************************/
+
+// Default constructor initializes stream buffer
+gzifstream::gzifstream()
+: std::istream(NULL), sb()
+{ this->init(&sb); }
+
+// Initialize stream buffer and open file
+gzifstream::gzifstream(const char* name,
+ std::ios_base::openmode mode)
+: std::istream(NULL), sb()
+{
+ this->init(&sb);
+ this->open(name, mode);
+}
+
+// Initialize stream buffer and attach to file
+gzifstream::gzifstream(int fd,
+ std::ios_base::openmode mode)
+: std::istream(NULL), sb()
+{
+ this->init(&sb);
+ this->attach(fd, mode);
+}
+
+// Open file and go into fail() state if unsuccessful
+void
+gzifstream::open(const char* name,
+ std::ios_base::openmode mode)
+{
+ if (!sb.open(name, mode | std::ios_base::in))
+ this->setstate(std::ios_base::failbit);
+ else
+ this->clear();
+}
+
+// Attach to file and go into fail() state if unsuccessful
+void
+gzifstream::attach(int fd,
+ std::ios_base::openmode mode)
+{
+ if (!sb.attach(fd, mode | std::ios_base::in))
+ this->setstate(std::ios_base::failbit);
+ else
+ this->clear();
+}
+
+// Close file
+void
+gzifstream::close()
+{
+ if (!sb.close())
+ this->setstate(std::ios_base::failbit);
+}
+
+/*****************************************************************************/
+
+// Default constructor initializes stream buffer
+gzofstream::gzofstream()
+: std::ostream(NULL), sb()
+{ this->init(&sb); }
+
+// Initialize stream buffer and open file
+gzofstream::gzofstream(const char* name,
+ std::ios_base::openmode mode)
+: std::ostream(NULL), sb()
+{
+ this->init(&sb);
+ this->open(name, mode);
+}
+
+// Initialize stream buffer and attach to file
+gzofstream::gzofstream(int fd,
+ std::ios_base::openmode mode)
+: std::ostream(NULL), sb()
+{
+ this->init(&sb);
+ this->attach(fd, mode);
+}
+
+// Open file and go into fail() state if unsuccessful
+void
+gzofstream::open(const char* name,
+ std::ios_base::openmode mode)
+{
+ if (!sb.open(name, mode | std::ios_base::out))
+ this->setstate(std::ios_base::failbit);
+ else
+ this->clear();
+}
+
+// Attach to file and go into fail() state if unsuccessful
+void
+gzofstream::attach(int fd,
+ std::ios_base::openmode mode)
+{
+ if (!sb.attach(fd, mode | std::ios_base::out))
+ this->setstate(std::ios_base::failbit);
+ else
+ this->clear();
+}
+
+// Close file
+void
+gzofstream::close()
+{
+ if (!sb.close())
+ this->setstate(std::ios_base::failbit);
+}
ADDED compat/zlib/contrib/iostream3/zfstream.h
Index: compat/zlib/contrib/iostream3/zfstream.h
==================================================================
--- compat/zlib/contrib/iostream3/zfstream.h
+++ compat/zlib/contrib/iostream3/zfstream.h
@@ -0,0 +1,466 @@
+/*
+ * A C++ I/O streams interface to the zlib gz* functions
+ *
+ * by Ludwig Schwardt
+ * original version by Kevin Ruland
+ *
+ * This version is standard-compliant and compatible with gcc 3.x.
+ */
+
+#ifndef ZFSTREAM_H
+#define ZFSTREAM_H
+
+#include // not iostream, since we don't need cin/cout
+#include
+#include "zlib.h"
+
+/*****************************************************************************/
+
+/**
+ * @brief Gzipped file stream buffer class.
+ *
+ * This class implements basic_filebuf for gzipped files. It doesn't yet support
+ * seeking (allowed by zlib but slow/limited), putback and read/write access
+ * (tricky). Otherwise, it attempts to be a drop-in replacement for the standard
+ * file streambuf.
+*/
+class gzfilebuf : public std::streambuf
+{
+public:
+ // Default constructor.
+ gzfilebuf();
+
+ // Destructor.
+ virtual
+ ~gzfilebuf();
+
+ /**
+ * @brief Set compression level and strategy on the fly.
+ * @param comp_level Compression level (see zlib.h for allowed values)
+ * @param comp_strategy Compression strategy (see zlib.h for allowed values)
+ * @return Z_OK on success, Z_STREAM_ERROR otherwise.
+ *
+ * Unfortunately, these parameters cannot be modified separately, as the
+ * previous zfstream version assumed. Since the strategy is seldom changed,
+ * it can default and setcompression(level) then becomes like the old
+ * setcompressionlevel(level).
+ */
+ int
+ setcompression(int comp_level,
+ int comp_strategy = Z_DEFAULT_STRATEGY);
+
+ /**
+ * @brief Check if file is open.
+ * @return True if file is open.
+ */
+ bool
+ is_open() const { return (file != NULL); }
+
+ /**
+ * @brief Open gzipped file.
+ * @param name File name.
+ * @param mode Open mode flags.
+ * @return @c this on success, NULL on failure.
+ */
+ gzfilebuf*
+ open(const char* name,
+ std::ios_base::openmode mode);
+
+ /**
+ * @brief Attach to already open gzipped file.
+ * @param fd File descriptor.
+ * @param mode Open mode flags.
+ * @return @c this on success, NULL on failure.
+ */
+ gzfilebuf*
+ attach(int fd,
+ std::ios_base::openmode mode);
+
+ /**
+ * @brief Close gzipped file.
+ * @return @c this on success, NULL on failure.
+ */
+ gzfilebuf*
+ close();
+
+protected:
+ /**
+ * @brief Convert ios open mode int to mode string used by zlib.
+ * @return True if valid mode flag combination.
+ */
+ bool
+ open_mode(std::ios_base::openmode mode,
+ char* c_mode) const;
+
+ /**
+ * @brief Number of characters available in stream buffer.
+ * @return Number of characters.
+ *
+ * This indicates number of characters in get area of stream buffer.
+ * These characters can be read without accessing the gzipped file.
+ */
+ virtual std::streamsize
+ showmanyc();
+
+ /**
+ * @brief Fill get area from gzipped file.
+ * @return First character in get area on success, EOF on error.
+ *
+ * This actually reads characters from gzipped file to stream
+ * buffer. Always buffered.
+ */
+ virtual int_type
+ underflow();
+
+ /**
+ * @brief Write put area to gzipped file.
+ * @param c Extra character to add to buffer contents.
+ * @return Non-EOF on success, EOF on error.
+ *
+ * This actually writes characters in stream buffer to
+ * gzipped file. With unbuffered output this is done one
+ * character at a time.
+ */
+ virtual int_type
+ overflow(int_type c = traits_type::eof());
+
+ /**
+ * @brief Installs external stream buffer.
+ * @param p Pointer to char buffer.
+ * @param n Size of external buffer.
+ * @return @c this on success, NULL on failure.
+ *
+ * Call setbuf(0,0) to enable unbuffered output.
+ */
+ virtual std::streambuf*
+ setbuf(char_type* p,
+ std::streamsize n);
+
+ /**
+ * @brief Flush stream buffer to file.
+ * @return 0 on success, -1 on error.
+ *
+ * This calls underflow(EOF) to do the job.
+ */
+ virtual int
+ sync();
+
+//
+// Some future enhancements
+//
+// virtual int_type uflow();
+// virtual int_type pbackfail(int_type c = traits_type::eof());
+// virtual pos_type
+// seekoff(off_type off,
+// std::ios_base::seekdir way,
+// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out);
+// virtual pos_type
+// seekpos(pos_type sp,
+// std::ios_base::openmode mode = std::ios_base::in|std::ios_base::out);
+
+private:
+ /**
+ * @brief Allocate internal buffer.
+ *
+ * This function is safe to call multiple times. It will ensure
+ * that a proper internal buffer exists if it is required. If the
+ * buffer already exists or is external, the buffer pointers will be
+ * reset to their original state.
+ */
+ void
+ enable_buffer();
+
+ /**
+ * @brief Destroy internal buffer.
+ *
+ * This function is safe to call multiple times. It will ensure
+ * that the internal buffer is deallocated if it exists. In any
+ * case, it will also reset the buffer pointers.
+ */
+ void
+ disable_buffer();
+
+ /**
+ * Underlying file pointer.
+ */
+ gzFile file;
+
+ /**
+ * Mode in which file was opened.
+ */
+ std::ios_base::openmode io_mode;
+
+ /**
+ * @brief True if this object owns file descriptor.
+ *
+ * This makes the class responsible for closing the file
+ * upon destruction.
+ */
+ bool own_fd;
+
+ /**
+ * @brief Stream buffer.
+ *
+ * For simplicity this remains allocated on the free store for the
+ * entire life span of the gzfilebuf object, unless replaced by setbuf.
+ */
+ char_type* buffer;
+
+ /**
+ * @brief Stream buffer size.
+ *
+ * Defaults to system default buffer size (typically 8192 bytes).
+ * Modified by setbuf.
+ */
+ std::streamsize buffer_size;
+
+ /**
+ * @brief True if this object owns stream buffer.
+ *
+ * This makes the class responsible for deleting the buffer
+ * upon destruction.
+ */
+ bool own_buffer;
+};
+
+/*****************************************************************************/
+
+/**
+ * @brief Gzipped file input stream class.
+ *
+ * This class implements ifstream for gzipped files. Seeking and putback
+ * is not supported yet.
+*/
+class gzifstream : public std::istream
+{
+public:
+ // Default constructor
+ gzifstream();
+
+ /**
+ * @brief Construct stream on gzipped file to be opened.
+ * @param name File name.
+ * @param mode Open mode flags (forced to contain ios::in).
+ */
+ explicit
+ gzifstream(const char* name,
+ std::ios_base::openmode mode = std::ios_base::in);
+
+ /**
+ * @brief Construct stream on already open gzipped file.
+ * @param fd File descriptor.
+ * @param mode Open mode flags (forced to contain ios::in).
+ */
+ explicit
+ gzifstream(int fd,
+ std::ios_base::openmode mode = std::ios_base::in);
+
+ /**
+ * Obtain underlying stream buffer.
+ */
+ gzfilebuf*
+ rdbuf() const
+ { return const_cast(&sb); }
+
+ /**
+ * @brief Check if file is open.
+ * @return True if file is open.
+ */
+ bool
+ is_open() { return sb.is_open(); }
+
+ /**
+ * @brief Open gzipped file.
+ * @param name File name.
+ * @param mode Open mode flags (forced to contain ios::in).
+ *
+ * Stream will be in state good() if file opens successfully;
+ * otherwise in state fail(). This differs from the behavior of
+ * ifstream, which never sets the state to good() and therefore
+ * won't allow you to reuse the stream for a second file unless
+ * you manually clear() the state. The choice is a matter of
+ * convenience.
+ */
+ void
+ open(const char* name,
+ std::ios_base::openmode mode = std::ios_base::in);
+
+ /**
+ * @brief Attach to already open gzipped file.
+ * @param fd File descriptor.
+ * @param mode Open mode flags (forced to contain ios::in).
+ *
+ * Stream will be in state good() if attach succeeded; otherwise
+ * in state fail().
+ */
+ void
+ attach(int fd,
+ std::ios_base::openmode mode = std::ios_base::in);
+
+ /**
+ * @brief Close gzipped file.
+ *
+ * Stream will be in state fail() if close failed.
+ */
+ void
+ close();
+
+private:
+ /**
+ * Underlying stream buffer.
+ */
+ gzfilebuf sb;
+};
+
+/*****************************************************************************/
+
+/**
+ * @brief Gzipped file output stream class.
+ *
+ * This class implements ofstream for gzipped files. Seeking and putback
+ * is not supported yet.
+*/
+class gzofstream : public std::ostream
+{
+public:
+ // Default constructor
+ gzofstream();
+
+ /**
+ * @brief Construct stream on gzipped file to be opened.
+ * @param name File name.
+ * @param mode Open mode flags (forced to contain ios::out).
+ */
+ explicit
+ gzofstream(const char* name,
+ std::ios_base::openmode mode = std::ios_base::out);
+
+ /**
+ * @brief Construct stream on already open gzipped file.
+ * @param fd File descriptor.
+ * @param mode Open mode flags (forced to contain ios::out).
+ */
+ explicit
+ gzofstream(int fd,
+ std::ios_base::openmode mode = std::ios_base::out);
+
+ /**
+ * Obtain underlying stream buffer.
+ */
+ gzfilebuf*
+ rdbuf() const
+ { return const_cast(&sb); }
+
+ /**
+ * @brief Check if file is open.
+ * @return True if file is open.
+ */
+ bool
+ is_open() { return sb.is_open(); }
+
+ /**
+ * @brief Open gzipped file.
+ * @param name File name.
+ * @param mode Open mode flags (forced to contain ios::out).
+ *
+ * Stream will be in state good() if file opens successfully;
+ * otherwise in state fail(). This differs from the behavior of
+ * ofstream, which never sets the state to good() and therefore
+ * won't allow you to reuse the stream for a second file unless
+ * you manually clear() the state. The choice is a matter of
+ * convenience.
+ */
+ void
+ open(const char* name,
+ std::ios_base::openmode mode = std::ios_base::out);
+
+ /**
+ * @brief Attach to already open gzipped file.
+ * @param fd File descriptor.
+ * @param mode Open mode flags (forced to contain ios::out).
+ *
+ * Stream will be in state good() if attach succeeded; otherwise
+ * in state fail().
+ */
+ void
+ attach(int fd,
+ std::ios_base::openmode mode = std::ios_base::out);
+
+ /**
+ * @brief Close gzipped file.
+ *
+ * Stream will be in state fail() if close failed.
+ */
+ void
+ close();
+
+private:
+ /**
+ * Underlying stream buffer.
+ */
+ gzfilebuf sb;
+};
+
+/*****************************************************************************/
+
+/**
+ * @brief Gzipped file output stream manipulator class.
+ *
+ * This class defines a two-argument manipulator for gzofstream. It is used
+ * as base for the setcompression(int,int) manipulator.
+*/
+template
+ class gzomanip2
+ {
+ public:
+ // Allows insertor to peek at internals
+ template
+ friend gzofstream&
+ operator<<(gzofstream&,
+ const gzomanip2&);
+
+ // Constructor
+ gzomanip2(gzofstream& (*f)(gzofstream&, T1, T2),
+ T1 v1,
+ T2 v2);
+ private:
+ // Underlying manipulator function
+ gzofstream&
+ (*func)(gzofstream&, T1, T2);
+
+ // Arguments for manipulator function
+ T1 val1;
+ T2 val2;
+ };
+
+/*****************************************************************************/
+
+// Manipulator function thunks through to stream buffer
+inline gzofstream&
+setcompression(gzofstream &gzs, int l, int s = Z_DEFAULT_STRATEGY)
+{
+ (gzs.rdbuf())->setcompression(l, s);
+ return gzs;
+}
+
+// Manipulator constructor stores arguments
+template
+ inline
+ gzomanip2::gzomanip2(gzofstream &(*f)(gzofstream &, T1, T2),
+ T1 v1,
+ T2 v2)
+ : func(f), val1(v1), val2(v2)
+ { }
+
+// Insertor applies underlying manipulator function to stream
+template
+ inline gzofstream&
+ operator<<(gzofstream& s, const gzomanip2& m)
+ { return (*m.func)(s, m.val1, m.val2); }
+
+// Insert this onto stream to simplify setting of compression level
+inline gzomanip2
+setcompression(int l, int s = Z_DEFAULT_STRATEGY)
+{ return gzomanip2(&setcompression, l, s); }
+
+#endif // ZFSTREAM_H
ADDED compat/zlib/contrib/minizip/Makefile
Index: compat/zlib/contrib/minizip/Makefile
==================================================================
--- compat/zlib/contrib/minizip/Makefile
+++ compat/zlib/contrib/minizip/Makefile
@@ -0,0 +1,29 @@
+CC=cc
+CFLAGS := $(CFLAGS) -O -I../..
+
+UNZ_OBJS = miniunz.o unzip.o ioapi.o ../../libz.a
+ZIP_OBJS = minizip.o zip.o ioapi.o ../../libz.a
+
+.c.o:
+ $(CC) -c $(CFLAGS) $*.c
+
+all: miniunz minizip
+
+miniunz: $(UNZ_OBJS)
+ $(CC) $(CFLAGS) -o $@ $(UNZ_OBJS)
+
+minizip: $(ZIP_OBJS)
+ $(CC) $(CFLAGS) -o $@ $(ZIP_OBJS)
+
+test: miniunz minizip
+ @rm -f test.*
+ @echo hello hello hello > test.txt
+ ./minizip test test.txt
+ ./miniunz -l test.zip
+ @mv test.txt test.old
+ ./miniunz test.zip
+ @cmp test.txt test.old
+ @rm -f test.*
+
+clean:
+ /bin/rm -f *.o *~ minizip miniunz test.*
ADDED compat/zlib/contrib/minizip/Makefile.am
Index: compat/zlib/contrib/minizip/Makefile.am
==================================================================
--- compat/zlib/contrib/minizip/Makefile.am
+++ compat/zlib/contrib/minizip/Makefile.am
@@ -0,0 +1,45 @@
+lib_LTLIBRARIES = libminizip.la
+
+if COND_DEMOS
+bin_PROGRAMS = miniunzip minizip
+endif
+
+zlib_top_srcdir = $(top_srcdir)/../..
+zlib_top_builddir = $(top_builddir)/../..
+
+AM_CPPFLAGS = -I$(zlib_top_srcdir)
+AM_LDFLAGS = -L$(zlib_top_builddir)
+
+if WIN32
+iowin32_src = iowin32.c
+iowin32_h = iowin32.h
+endif
+
+libminizip_la_SOURCES = \
+ ioapi.c \
+ mztools.c \
+ unzip.c \
+ zip.c \
+ ${iowin32_src}
+
+libminizip_la_LDFLAGS = $(AM_LDFLAGS) -version-info 1:0:0 -lz
+
+minizip_includedir = $(includedir)/minizip
+minizip_include_HEADERS = \
+ crypt.h \
+ ioapi.h \
+ mztools.h \
+ unzip.h \
+ zip.h \
+ ${iowin32_h}
+
+pkgconfigdir = $(libdir)/pkgconfig
+pkgconfig_DATA = minizip.pc
+
+EXTRA_PROGRAMS = miniunzip minizip
+
+miniunzip_SOURCES = miniunz.c
+miniunzip_LDADD = libminizip.la
+
+minizip_SOURCES = minizip.c
+minizip_LDADD = libminizip.la -lz
ADDED compat/zlib/contrib/minizip/MiniZip64_Changes.txt
Index: compat/zlib/contrib/minizip/MiniZip64_Changes.txt
==================================================================
--- compat/zlib/contrib/minizip/MiniZip64_Changes.txt
+++ compat/zlib/contrib/minizip/MiniZip64_Changes.txt
@@ -0,0 +1,6 @@
+
+MiniZip 1.1 was derrived from MiniZip at version 1.01f
+
+Change in 1.0 (Okt 2009)
+ - **TODO - Add history**
+
ADDED compat/zlib/contrib/minizip/MiniZip64_info.txt
Index: compat/zlib/contrib/minizip/MiniZip64_info.txt
==================================================================
--- compat/zlib/contrib/minizip/MiniZip64_info.txt
+++ compat/zlib/contrib/minizip/MiniZip64_info.txt
@@ -0,0 +1,74 @@
+MiniZip - Copyright (c) 1998-2010 - by Gilles Vollant - version 1.1 64 bits from Mathias Svensson
+
+Introduction
+---------------------
+MiniZip 1.1 is built from MiniZip 1.0 by Gilles Vollant ( http://www.winimage.com/zLibDll/minizip.html )
+
+When adding ZIP64 support into minizip it would result into risk of breaking compatibility with minizip 1.0.
+All possible work was done for compatibility.
+
+
+Background
+---------------------
+When adding ZIP64 support Mathias Svensson found that Even Rouault have added ZIP64
+support for unzip.c into minizip for a open source project called gdal ( http://www.gdal.org/ )
+
+That was used as a starting point. And after that ZIP64 support was added to zip.c
+some refactoring and code cleanup was also done.
+
+
+Changed from MiniZip 1.0 to MiniZip 1.1
+---------------------------------------
+* Added ZIP64 support for unzip ( by Even Rouault )
+* Added ZIP64 support for zip ( by Mathias Svensson )
+* Reverted some changed that Even Rouault did.
+* Bunch of patches received from Gulles Vollant that he received for MiniZip from various users.
+* Added unzip patch for BZIP Compression method (patch create by Daniel Borca)
+* Added BZIP Compress method for zip
+* Did some refactoring and code cleanup
+
+
+Credits
+
+ Gilles Vollant - Original MiniZip author
+ Even Rouault - ZIP64 unzip Support
+ Daniel Borca - BZip Compression method support in unzip
+ Mathias Svensson - ZIP64 zip support
+ Mathias Svensson - BZip Compression method support in zip
+
+ Resources
+
+ ZipLayout http://result42.com/projects/ZipFileLayout
+ Command line tool for Windows that shows the layout and information of the headers in a zip archive.
+ Used when debugging and validating the creation of zip files using MiniZip64
+
+
+ ZIP App Note http://www.pkware.com/documents/casestudies/APPNOTE.TXT
+ Zip File specification
+
+
+Notes.
+ * To be able to use BZip compression method in zip64.c or unzip64.c the BZIP2 lib is needed and HAVE_BZIP2 need to be defined.
+
+License
+----------------------------------------------------------
+ Condition of use and distribution are the same than zlib :
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+----------------------------------------------------------
+
ADDED compat/zlib/contrib/minizip/configure.ac
Index: compat/zlib/contrib/minizip/configure.ac
==================================================================
--- compat/zlib/contrib/minizip/configure.ac
+++ compat/zlib/contrib/minizip/configure.ac
@@ -0,0 +1,32 @@
+# -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+
+AC_INIT([minizip], [1.2.13], [bugzilla.redhat.com])
+AC_CONFIG_SRCDIR([minizip.c])
+AM_INIT_AUTOMAKE([foreign])
+LT_INIT
+
+AC_MSG_CHECKING([whether to build example programs])
+AC_ARG_ENABLE([demos], AC_HELP_STRING([--enable-demos], [build example programs]))
+AM_CONDITIONAL([COND_DEMOS], [test "$enable_demos" = yes])
+if test "$enable_demos" = yes
+then
+ AC_MSG_RESULT([yes])
+else
+ AC_MSG_RESULT([no])
+fi
+
+case "${host}" in
+ *-mingw* | mingw*)
+ WIN32="yes"
+ ;;
+ *)
+ ;;
+esac
+AM_CONDITIONAL([WIN32], [test "${WIN32}" = "yes"])
+
+
+AC_SUBST([HAVE_UNISTD_H], [0])
+AC_CHECK_HEADER([unistd.h], [HAVE_UNISTD_H=1], [])
+AC_CONFIG_FILES([Makefile minizip.pc])
+AC_OUTPUT
ADDED compat/zlib/contrib/minizip/crypt.h
Index: compat/zlib/contrib/minizip/crypt.h
==================================================================
--- compat/zlib/contrib/minizip/crypt.h
+++ compat/zlib/contrib/minizip/crypt.h
@@ -0,0 +1,132 @@
+/* crypt.h -- base code for crypt/uncrypt ZIPfile
+
+
+ Version 1.01e, February 12th, 2005
+
+ Copyright (C) 1998-2005 Gilles Vollant
+
+ This code is a modified version of crypting code in Infozip distribution
+
+ The encryption/decryption parts of this source code (as opposed to the
+ non-echoing password parts) were originally written in Europe. The
+ whole source package can be freely distributed, including from the USA.
+ (Prior to January 2000, re-export from the US was a violation of US law.)
+
+ This encryption code is a direct transcription of the algorithm from
+ Roger Schlafly, described by Phil Katz in the file appnote.txt. This
+ file (appnote.txt) is distributed with the PKZIP program (even in the
+ version without encryption capabilities).
+
+ If you don't need crypting in your application, just define symbols
+ NOCRYPT and NOUNCRYPT.
+
+ This code support the "Traditional PKWARE Encryption".
+
+ The new AES encryption added on Zip format by Winzip (see the page
+ http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
+ Encryption is not supported.
+*/
+
+#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
+
+/***********************************************************************
+ * Return the next byte in the pseudo-random sequence
+ */
+static int decrypt_byte(unsigned long* pkeys, const z_crc_t* pcrc_32_tab)
+{
+ unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an
+ * unpredictable manner on 16-bit systems; not a problem
+ * with any known compiler so far, though */
+
+ (void)pcrc_32_tab;
+ temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
+ return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
+}
+
+/***********************************************************************
+ * Update the encryption keys with the next byte of plain text
+ */
+static int update_keys(unsigned long* pkeys,const z_crc_t* pcrc_32_tab,int c)
+{
+ (*(pkeys+0)) = CRC32((*(pkeys+0)), c);
+ (*(pkeys+1)) += (*(pkeys+0)) & 0xff;
+ (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
+ {
+ register int keyshift = (int)((*(pkeys+1)) >> 24);
+ (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
+ }
+ return c;
+}
+
+
+/***********************************************************************
+ * Initialize the encryption keys and the random header according to
+ * the given password.
+ */
+static void init_keys(const char* passwd,unsigned long* pkeys,const z_crc_t* pcrc_32_tab)
+{
+ *(pkeys+0) = 305419896L;
+ *(pkeys+1) = 591751049L;
+ *(pkeys+2) = 878082192L;
+ while (*passwd != '\0') {
+ update_keys(pkeys,pcrc_32_tab,(int)*passwd);
+ passwd++;
+ }
+}
+
+#define zdecode(pkeys,pcrc_32_tab,c) \
+ (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab)))
+
+#define zencode(pkeys,pcrc_32_tab,c,t) \
+ (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), (Byte)t^(c))
+
+#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
+
+#define RAND_HEAD_LEN 12
+ /* "last resort" source for second part of crypt seed pattern */
+# ifndef ZCR_SEED2
+# define ZCR_SEED2 3141592654UL /* use PI as default pattern */
+# endif
+
+static unsigned crypthead(const char* passwd, /* password string */
+ unsigned char* buf, /* where to write header */
+ int bufSize,
+ unsigned long* pkeys,
+ const z_crc_t* pcrc_32_tab,
+ unsigned long crcForCrypting)
+{
+ unsigned n; /* index in random header */
+ int t; /* temporary */
+ int c; /* random byte */
+ unsigned char header[RAND_HEAD_LEN-2]; /* random header */
+ static unsigned calls = 0; /* ensure different random header each time */
+
+ if (bufSize> 7) & 0xff;
+ header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
+ }
+ /* Encrypt random header (last two bytes is high word of crc) */
+ init_keys(passwd, pkeys, pcrc_32_tab);
+ for (n = 0; n < RAND_HEAD_LEN-2; n++)
+ {
+ buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
+ }
+ buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
+ buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
+ return n;
+}
+
+#endif
ADDED compat/zlib/contrib/minizip/ioapi.c
Index: compat/zlib/contrib/minizip/ioapi.c
==================================================================
--- compat/zlib/contrib/minizip/ioapi.c
+++ compat/zlib/contrib/minizip/ioapi.c
@@ -0,0 +1,257 @@
+/* ioapi.h -- IO base function header for compress/uncompress .zip
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+*/
+
+#if defined(_WIN32) && (!(defined(_CRT_SECURE_NO_WARNINGS)))
+ #define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#if defined(__APPLE__) || defined(IOAPI_NO_64)
+// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
+#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
+#define FTELLO_FUNC(stream) ftello(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
+#else
+#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
+#define FTELLO_FUNC(stream) ftello64(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
+#endif
+
+
+#include "ioapi.h"
+
+voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)
+{
+ if (pfilefunc->zfile_func64.zopen64_file != NULL)
+ return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode);
+ else
+ {
+ return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode);
+ }
+}
+
+long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)
+{
+ if (pfilefunc->zfile_func64.zseek64_file != NULL)
+ return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin);
+ else
+ {
+ uLong offsetTruncated = (uLong)offset;
+ if (offsetTruncated != offset)
+ return -1;
+ else
+ return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin);
+ }
+}
+
+ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)
+{
+ if (pfilefunc->zfile_func64.zseek64_file != NULL)
+ return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream);
+ else
+ {
+ uLong tell_uLong = (uLong)(*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream);
+ if ((tell_uLong) == MAXU32)
+ return (ZPOS64_T)-1;
+ else
+ return tell_uLong;
+ }
+}
+
+void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32)
+{
+ p_filefunc64_32->zfile_func64.zopen64_file = NULL;
+ p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file;
+ p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
+ p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file;
+ p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file;
+ p_filefunc64_32->zfile_func64.ztell64_file = NULL;
+ p_filefunc64_32->zfile_func64.zseek64_file = NULL;
+ p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file;
+ p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
+ p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque;
+ p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file;
+ p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file;
+}
+
+
+
+static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode));
+static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size));
+static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream));
+static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream));
+static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream));
+
+static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
+{
+ FILE* file = NULL;
+ const char* mode_fopen = NULL;
+ (void)opaque;
+ if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+ mode_fopen = "rb";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+ mode_fopen = "r+b";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+ mode_fopen = "wb";
+
+ if ((filename!=NULL) && (mode_fopen != NULL))
+ file = fopen(filename, mode_fopen);
+ return file;
+}
+
+static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode)
+{
+ FILE* file = NULL;
+ const char* mode_fopen = NULL;
+ (void)opaque;
+ if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+ mode_fopen = "rb";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+ mode_fopen = "r+b";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+ mode_fopen = "wb";
+
+ if ((filename!=NULL) && (mode_fopen != NULL))
+ file = FOPEN_FUNC((const char*)filename, mode_fopen);
+ return file;
+}
+
+
+static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
+{
+ uLong ret;
+ (void)opaque;
+ ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
+ return ret;
+}
+
+static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
+{
+ uLong ret;
+ (void)opaque;
+ ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
+ return ret;
+}
+
+static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
+{
+ long ret;
+ (void)opaque;
+ ret = ftell((FILE *)stream);
+ return ret;
+}
+
+
+static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
+{
+ ZPOS64_T ret;
+ (void)opaque;
+ ret = (ZPOS64_T)FTELLO_FUNC((FILE *)stream);
+ return ret;
+}
+
+static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin)
+{
+ int fseek_origin=0;
+ long ret;
+ (void)opaque;
+ switch (origin)
+ {
+ case ZLIB_FILEFUNC_SEEK_CUR :
+ fseek_origin = SEEK_CUR;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END :
+ fseek_origin = SEEK_END;
+ break;
+ case ZLIB_FILEFUNC_SEEK_SET :
+ fseek_origin = SEEK_SET;
+ break;
+ default: return -1;
+ }
+ ret = 0;
+ if (fseek((FILE *)stream, (long)offset, fseek_origin) != 0)
+ ret = -1;
+ return ret;
+}
+
+static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)
+{
+ int fseek_origin=0;
+ long ret;
+ (void)opaque;
+ switch (origin)
+ {
+ case ZLIB_FILEFUNC_SEEK_CUR :
+ fseek_origin = SEEK_CUR;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END :
+ fseek_origin = SEEK_END;
+ break;
+ case ZLIB_FILEFUNC_SEEK_SET :
+ fseek_origin = SEEK_SET;
+ break;
+ default: return -1;
+ }
+ ret = 0;
+
+ if(FSEEKO_FUNC((FILE *)stream, (z_off_t)offset, fseek_origin) != 0)
+ ret = -1;
+
+ return ret;
+}
+
+
+static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
+{
+ int ret;
+ (void)opaque;
+ ret = fclose((FILE *)stream);
+ return ret;
+}
+
+static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
+{
+ int ret;
+ (void)opaque;
+ ret = ferror((FILE *)stream);
+ return ret;
+}
+
+void fill_fopen_filefunc (pzlib_filefunc_def)
+ zlib_filefunc_def* pzlib_filefunc_def;
+{
+ pzlib_filefunc_def->zopen_file = fopen_file_func;
+ pzlib_filefunc_def->zread_file = fread_file_func;
+ pzlib_filefunc_def->zwrite_file = fwrite_file_func;
+ pzlib_filefunc_def->ztell_file = ftell_file_func;
+ pzlib_filefunc_def->zseek_file = fseek_file_func;
+ pzlib_filefunc_def->zclose_file = fclose_file_func;
+ pzlib_filefunc_def->zerror_file = ferror_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
+
+void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def)
+{
+ pzlib_filefunc_def->zopen64_file = fopen64_file_func;
+ pzlib_filefunc_def->zread_file = fread_file_func;
+ pzlib_filefunc_def->zwrite_file = fwrite_file_func;
+ pzlib_filefunc_def->ztell64_file = ftell64_file_func;
+ pzlib_filefunc_def->zseek64_file = fseek64_file_func;
+ pzlib_filefunc_def->zclose_file = fclose_file_func;
+ pzlib_filefunc_def->zerror_file = ferror_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
ADDED compat/zlib/contrib/minizip/ioapi.h
Index: compat/zlib/contrib/minizip/ioapi.h
==================================================================
--- compat/zlib/contrib/minizip/ioapi.h
+++ compat/zlib/contrib/minizip/ioapi.h
@@ -0,0 +1,210 @@
+/* ioapi.h -- IO base function header for compress/uncompress .zip
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+ Changes
+
+ Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
+ Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
+ More if/def section may be needed to support other platforms
+ Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
+ (but you should use iowin32.c for windows instead)
+
+*/
+
+#ifndef _ZLIBIOAPI64_H
+#define _ZLIBIOAPI64_H
+
+#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
+
+ // Linux needs this to support file operation on files larger then 4+GB
+ // But might need better if/def to select just the platforms that needs them.
+
+ #ifndef __USE_FILE_OFFSET64
+ #define __USE_FILE_OFFSET64
+ #endif
+ #ifndef __USE_LARGEFILE64
+ #define __USE_LARGEFILE64
+ #endif
+ #ifndef _LARGEFILE64_SOURCE
+ #define _LARGEFILE64_SOURCE
+ #endif
+ #ifndef _FILE_OFFSET_BIT
+ #define _FILE_OFFSET_BIT 64
+ #endif
+
+#endif
+
+#include
+#include
+#include "zlib.h"
+
+#if defined(USE_FILE32API)
+#define fopen64 fopen
+#define ftello64 ftell
+#define fseeko64 fseek
+#else
+#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+#define fopen64 fopen
+#define ftello64 ftello
+#define fseeko64 fseeko
+#endif
+#ifdef _MSC_VER
+ #define fopen64 fopen
+ #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
+ #define ftello64 _ftelli64
+ #define fseeko64 _fseeki64
+ #else // old MSC
+ #define ftello64 ftell
+ #define fseeko64 fseek
+ #endif
+#endif
+#endif
+
+/*
+#ifndef ZPOS64_T
+ #ifdef _WIN32
+ #define ZPOS64_T fpos_t
+ #else
+ #include
+ #define ZPOS64_T uint64_t
+ #endif
+#endif
+*/
+
+#ifdef HAVE_MINIZIP64_CONF_H
+#include "mz64conf.h"
+#endif
+
+/* a type choosen by DEFINE */
+#ifdef HAVE_64BIT_INT_CUSTOM
+typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T;
+#else
+#ifdef HAS_STDINT_H
+#include "stdint.h"
+typedef uint64_t ZPOS64_T;
+#else
+
+
+
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+typedef unsigned __int64 ZPOS64_T;
+#else
+typedef unsigned long long int ZPOS64_T;
+#endif
+#endif
+#endif
+
+/* Maximum unsigned 32-bit value used as placeholder for zip64 */
+#ifndef MAXU32
+#define MAXU32 (0xffffffff)
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define ZLIB_FILEFUNC_SEEK_CUR (1)
+#define ZLIB_FILEFUNC_SEEK_END (2)
+#define ZLIB_FILEFUNC_SEEK_SET (0)
+
+#define ZLIB_FILEFUNC_MODE_READ (1)
+#define ZLIB_FILEFUNC_MODE_WRITE (2)
+#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
+
+#define ZLIB_FILEFUNC_MODE_EXISTING (4)
+#define ZLIB_FILEFUNC_MODE_CREATE (8)
+
+
+#ifndef ZCALLBACK
+ #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
+ #define ZCALLBACK CALLBACK
+ #else
+ #define ZCALLBACK
+ #endif
+#endif
+
+
+
+
+typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
+typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
+typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
+typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
+
+typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
+typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
+
+
+/* here is the "old" 32 bits structure structure */
+typedef struct zlib_filefunc_def_s
+{
+ open_file_func zopen_file;
+ read_file_func zread_file;
+ write_file_func zwrite_file;
+ tell_file_func ztell_file;
+ seek_file_func zseek_file;
+ close_file_func zclose_file;
+ testerror_file_func zerror_file;
+ voidpf opaque;
+} zlib_filefunc_def;
+
+typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream));
+typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode));
+
+typedef struct zlib_filefunc64_def_s
+{
+ open64_file_func zopen64_file;
+ read_file_func zread_file;
+ write_file_func zwrite_file;
+ tell64_file_func ztell64_file;
+ seek64_file_func zseek64_file;
+ close_file_func zclose_file;
+ testerror_file_func zerror_file;
+ voidpf opaque;
+} zlib_filefunc64_def;
+
+void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
+void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
+
+/* now internal definition, only for zip.c and unzip.h */
+typedef struct zlib_filefunc64_32_def_s
+{
+ zlib_filefunc64_def zfile_func64;
+ open_file_func zopen32_file;
+ tell_file_func ztell32_file;
+ seek_file_func zseek32_file;
+} zlib_filefunc64_32_def;
+
+
+#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
+#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
+//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
+//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
+#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
+#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
+
+voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
+long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
+ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
+
+void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
+
+#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
+#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
+#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
ADDED compat/zlib/contrib/minizip/iowin32.c
Index: compat/zlib/contrib/minizip/iowin32.c
==================================================================
--- compat/zlib/contrib/minizip/iowin32.c
+++ compat/zlib/contrib/minizip/iowin32.c
@@ -0,0 +1,467 @@
+/* iowin32.c -- IO base function header for compress/uncompress .zip
+ Version 1.1, February 14h, 2010
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+*/
+
+#include
+
+#include "zlib.h"
+#include "ioapi.h"
+#include "iowin32.h"
+
+#ifndef INVALID_HANDLE_VALUE
+#define INVALID_HANDLE_VALUE (0xFFFFFFFF)
+#endif
+
+#ifndef INVALID_SET_FILE_POINTER
+#define INVALID_SET_FILE_POINTER ((DWORD)-1)
+#endif
+
+
+// see Include/shared/winapifamily.h in the Windows Kit
+#if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API)))
+
+#if !defined(WINAPI_FAMILY_ONE_PARTITION)
+#define WINAPI_FAMILY_ONE_PARTITION(PartitionSet, Partition) ((WINAPI_FAMILY & PartitionSet) == Partition)
+#endif
+
+#if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP)
+#define IOWIN32_USING_WINRT_API 1
+#endif
+#endif
+
+voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode));
+uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+uLong ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
+ZPOS64_T ZCALLBACK win32_tell64_file_func OF((voidpf opaque, voidpf stream));
+long ZCALLBACK win32_seek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+int ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream));
+int ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream));
+
+typedef struct
+{
+ HANDLE hf;
+ int error;
+} WIN32FILE_IOWIN;
+
+
+static void win32_translate_open_mode(int mode,
+ DWORD* lpdwDesiredAccess,
+ DWORD* lpdwCreationDisposition,
+ DWORD* lpdwShareMode,
+ DWORD* lpdwFlagsAndAttributes)
+{
+ *lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0;
+
+ if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+ {
+ *lpdwDesiredAccess = GENERIC_READ;
+ *lpdwCreationDisposition = OPEN_EXISTING;
+ *lpdwShareMode = FILE_SHARE_READ;
+ }
+ else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+ {
+ *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
+ *lpdwCreationDisposition = OPEN_EXISTING;
+ }
+ else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+ {
+ *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
+ *lpdwCreationDisposition = CREATE_ALWAYS;
+ }
+}
+
+static voidpf win32_build_iowin(HANDLE hFile)
+{
+ voidpf ret=NULL;
+
+ if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
+ {
+ WIN32FILE_IOWIN w32fiow;
+ w32fiow.hf = hFile;
+ w32fiow.error = 0;
+ ret = malloc(sizeof(WIN32FILE_IOWIN));
+
+ if (ret==NULL)
+ CloseHandle(hFile);
+ else
+ *((WIN32FILE_IOWIN*)ret) = w32fiow;
+ }
+ return ret;
+}
+
+voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode)
+{
+ const char* mode_fopen = NULL;
+ DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+ HANDLE hFile = NULL;
+
+ win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+#ifdef IOWIN32_USING_WINRT_API
+#ifdef UNICODE
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
+#else
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ {
+ WCHAR filenameW[FILENAME_MAX + 0x200 + 1];
+ MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200);
+ hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
+ }
+#endif
+#else
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+#endif
+
+ return win32_build_iowin(hFile);
+}
+
+
+voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode)
+{
+ const char* mode_fopen = NULL;
+ DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+ HANDLE hFile = NULL;
+
+ win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+#ifdef IOWIN32_USING_WINRT_API
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ {
+ WCHAR filenameW[FILENAME_MAX + 0x200 + 1];
+ MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200);
+ hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
+ }
+#else
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+#endif
+
+ return win32_build_iowin(hFile);
+}
+
+
+voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode)
+{
+ const char* mode_fopen = NULL;
+ DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+ HANDLE hFile = NULL;
+
+ win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+#ifdef IOWIN32_USING_WINRT_API
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ hFile = CreateFile2((LPCWSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition,NULL);
+#else
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+#endif
+
+ return win32_build_iowin(hFile);
+}
+
+
+voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode)
+{
+ const char* mode_fopen = NULL;
+ DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
+ HANDLE hFile = NULL;
+
+ win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
+
+#ifdef IOWIN32_USING_WINRT_API
+#ifdef UNICODE
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
+#else
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ {
+ WCHAR filenameW[FILENAME_MAX + 0x200 + 1];
+ MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200);
+ hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL);
+ }
+#endif
+#else
+ if ((filename!=NULL) && (dwDesiredAccess != 0))
+ hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
+#endif
+
+ return win32_build_iowin(hFile);
+}
+
+
+uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size)
+{
+ uLong ret=0;
+ HANDLE hFile = NULL;
+ if (stream!=NULL)
+ hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+
+ if (hFile != NULL)
+ {
+ if (!ReadFile(hFile, buf, size, &ret, NULL))
+ {
+ DWORD dwErr = GetLastError();
+ if (dwErr == ERROR_HANDLE_EOF)
+ dwErr = 0;
+ ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+ }
+ }
+
+ return ret;
+}
+
+
+uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size)
+{
+ uLong ret=0;
+ HANDLE hFile = NULL;
+ if (stream!=NULL)
+ hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+
+ if (hFile != NULL)
+ {
+ if (!WriteFile(hFile, buf, size, &ret, NULL))
+ {
+ DWORD dwErr = GetLastError();
+ if (dwErr == ERROR_HANDLE_EOF)
+ dwErr = 0;
+ ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+ }
+ }
+
+ return ret;
+}
+
+static BOOL MySetFilePointerEx(HANDLE hFile, LARGE_INTEGER pos, LARGE_INTEGER *newPos, DWORD dwMoveMethod)
+{
+#ifdef IOWIN32_USING_WINRT_API
+ return SetFilePointerEx(hFile, pos, newPos, dwMoveMethod);
+#else
+ LONG lHigh = pos.HighPart;
+ DWORD dwNewPos = SetFilePointer(hFile, pos.LowPart, &lHigh, dwMoveMethod);
+ BOOL fOk = TRUE;
+ if (dwNewPos == 0xFFFFFFFF)
+ if (GetLastError() != NO_ERROR)
+ fOk = FALSE;
+ if ((newPos != NULL) && (fOk))
+ {
+ newPos->LowPart = dwNewPos;
+ newPos->HighPart = lHigh;
+ }
+ return fOk;
+#endif
+}
+
+long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream)
+{
+ long ret=-1;
+ HANDLE hFile = NULL;
+ if (stream!=NULL)
+ hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+ if (hFile != NULL)
+ {
+ LARGE_INTEGER pos;
+ pos.QuadPart = 0;
+
+ if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT))
+ {
+ DWORD dwErr = GetLastError();
+ ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+ ret = -1;
+ }
+ else
+ ret=(long)pos.LowPart;
+ }
+ return ret;
+}
+
+ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream)
+{
+ ZPOS64_T ret= (ZPOS64_T)-1;
+ HANDLE hFile = NULL;
+ if (stream!=NULL)
+ hFile = ((WIN32FILE_IOWIN*)stream)->hf;
+
+ if (hFile)
+ {
+ LARGE_INTEGER pos;
+ pos.QuadPart = 0;
+
+ if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT))
+ {
+ DWORD dwErr = GetLastError();
+ ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+ ret = (ZPOS64_T)-1;
+ }
+ else
+ ret=pos.QuadPart;
+ }
+ return ret;
+}
+
+
+long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin)
+{
+ DWORD dwMoveMethod=0xFFFFFFFF;
+ HANDLE hFile = NULL;
+
+ long ret=-1;
+ if (stream!=NULL)
+ hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+ switch (origin)
+ {
+ case ZLIB_FILEFUNC_SEEK_CUR :
+ dwMoveMethod = FILE_CURRENT;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END :
+ dwMoveMethod = FILE_END;
+ break;
+ case ZLIB_FILEFUNC_SEEK_SET :
+ dwMoveMethod = FILE_BEGIN;
+ break;
+ default: return -1;
+ }
+
+ if (hFile != NULL)
+ {
+ LARGE_INTEGER pos;
+ pos.QuadPart = offset;
+ if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod))
+ {
+ DWORD dwErr = GetLastError();
+ ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+ ret = -1;
+ }
+ else
+ ret=0;
+ }
+ return ret;
+}
+
+long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin)
+{
+ DWORD dwMoveMethod=0xFFFFFFFF;
+ HANDLE hFile = NULL;
+ long ret=-1;
+
+ if (stream!=NULL)
+ hFile = ((WIN32FILE_IOWIN*)stream)->hf;
+
+ switch (origin)
+ {
+ case ZLIB_FILEFUNC_SEEK_CUR :
+ dwMoveMethod = FILE_CURRENT;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END :
+ dwMoveMethod = FILE_END;
+ break;
+ case ZLIB_FILEFUNC_SEEK_SET :
+ dwMoveMethod = FILE_BEGIN;
+ break;
+ default: return -1;
+ }
+
+ if (hFile)
+ {
+ LARGE_INTEGER pos;
+ pos.QuadPart = offset;
+ if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod))
+ {
+ DWORD dwErr = GetLastError();
+ ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
+ ret = -1;
+ }
+ else
+ ret=0;
+ }
+ return ret;
+}
+
+int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream)
+{
+ int ret=-1;
+
+ if (stream!=NULL)
+ {
+ HANDLE hFile;
+ hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
+ if (hFile != NULL)
+ {
+ CloseHandle(hFile);
+ ret=0;
+ }
+ free(stream);
+ }
+ return ret;
+}
+
+int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream)
+{
+ int ret=-1;
+ if (stream!=NULL)
+ {
+ ret = ((WIN32FILE_IOWIN*)stream) -> error;
+ }
+ return ret;
+}
+
+void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def)
+{
+ pzlib_filefunc_def->zopen_file = win32_open_file_func;
+ pzlib_filefunc_def->zread_file = win32_read_file_func;
+ pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+ pzlib_filefunc_def->ztell_file = win32_tell_file_func;
+ pzlib_filefunc_def->zseek_file = win32_seek_file_func;
+ pzlib_filefunc_def->zclose_file = win32_close_file_func;
+ pzlib_filefunc_def->zerror_file = win32_error_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
+
+void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def)
+{
+ pzlib_filefunc_def->zopen64_file = win32_open64_file_func;
+ pzlib_filefunc_def->zread_file = win32_read_file_func;
+ pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+ pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
+ pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
+ pzlib_filefunc_def->zclose_file = win32_close_file_func;
+ pzlib_filefunc_def->zerror_file = win32_error_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
+
+
+void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def)
+{
+ pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA;
+ pzlib_filefunc_def->zread_file = win32_read_file_func;
+ pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+ pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
+ pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
+ pzlib_filefunc_def->zclose_file = win32_close_file_func;
+ pzlib_filefunc_def->zerror_file = win32_error_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
+
+
+void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def)
+{
+ pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW;
+ pzlib_filefunc_def->zread_file = win32_read_file_func;
+ pzlib_filefunc_def->zwrite_file = win32_write_file_func;
+ pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
+ pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
+ pzlib_filefunc_def->zclose_file = win32_close_file_func;
+ pzlib_filefunc_def->zerror_file = win32_error_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
ADDED compat/zlib/contrib/minizip/iowin32.h
Index: compat/zlib/contrib/minizip/iowin32.h
==================================================================
--- compat/zlib/contrib/minizip/iowin32.h
+++ compat/zlib/contrib/minizip/iowin32.h
@@ -0,0 +1,28 @@
+/* iowin32.h -- IO base function header for compress/uncompress .zip
+ Version 1.1, February 14h, 2010
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+*/
+
+#include
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
+void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def));
+void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def));
+void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def));
+
+#ifdef __cplusplus
+}
+#endif
ADDED compat/zlib/contrib/minizip/make_vms.com
Index: compat/zlib/contrib/minizip/make_vms.com
==================================================================
--- compat/zlib/contrib/minizip/make_vms.com
+++ compat/zlib/contrib/minizip/make_vms.com
@@ -0,0 +1,25 @@
+$ if f$search("ioapi.h_orig") .eqs. "" then copy ioapi.h ioapi.h_orig
+$ open/write zdef vmsdefs.h
+$ copy sys$input: zdef
+$ deck
+#define unix
+#define fill_zlib_filefunc64_32_def_from_filefunc32 fillzffunc64from
+#define Write_Zip64EndOfCentralDirectoryLocator Write_Zip64EoDLocator
+#define Write_Zip64EndOfCentralDirectoryRecord Write_Zip64EoDRecord
+#define Write_EndOfCentralDirectoryRecord Write_EoDRecord
+$ eod
+$ close zdef
+$ copy vmsdefs.h,ioapi.h_orig ioapi.h
+$ cc/include=[--]/prefix=all ioapi.c
+$ cc/include=[--]/prefix=all miniunz.c
+$ cc/include=[--]/prefix=all unzip.c
+$ cc/include=[--]/prefix=all minizip.c
+$ cc/include=[--]/prefix=all zip.c
+$ link miniunz,unzip,ioapi,[--]libz.olb/lib
+$ link minizip,zip,ioapi,[--]libz.olb/lib
+$ mcr []minizip test minizip_info.txt
+$ mcr []miniunz -l test.zip
+$ rename minizip_info.txt; minizip_info.txt_old
+$ mcr []miniunz test.zip
+$ delete test.zip;*
+$exit
ADDED compat/zlib/contrib/minizip/miniunz.c
Index: compat/zlib/contrib/minizip/miniunz.c
==================================================================
--- compat/zlib/contrib/minizip/miniunz.c
+++ compat/zlib/contrib/minizip/miniunz.c
@@ -0,0 +1,659 @@
+/*
+ miniunz.c
+ Version 1.1, February 14h, 2010
+ sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications of Unzip for Zip64
+ Copyright (C) 2007-2008 Even Rouault
+
+ Modifications for Zip64 support on both zip and unzip
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+*/
+
+#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
+ #ifndef __USE_FILE_OFFSET64
+ #define __USE_FILE_OFFSET64
+ #endif
+ #ifndef __USE_LARGEFILE64
+ #define __USE_LARGEFILE64
+ #endif
+ #ifndef _LARGEFILE64_SOURCE
+ #define _LARGEFILE64_SOURCE
+ #endif
+ #ifndef _FILE_OFFSET_BIT
+ #define _FILE_OFFSET_BIT 64
+ #endif
+#endif
+
+#ifdef __APPLE__
+// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions
+#define FOPEN_FUNC(filename, mode) fopen(filename, mode)
+#define FTELLO_FUNC(stream) ftello(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
+#else
+#define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
+#define FTELLO_FUNC(stream) ftello64(stream)
+#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
+#endif
+
+
+#include