clearsilver-0.10.5/ 0000755 0012117 0011610 00000000000 10645505101 011101 5 0000000 0000000 clearsilver-0.10.5/README 0000644 0012117 0011610 00000004670 10261037504 011711 0000000 0000000 ************************************
* Clearsilver README
************************************
For more information, see the website:
http://www.clearsilver.net/
This package includes Clearsilver, the CGI kit and HTML templating
system. For information about building and installing, see the
included INSTALL file. This package also includes tools which
help you use Clearsilver, as well as a few examples.
************************************************************
*** Clearsilver
* Clearsilver - This is our html template system and cgi kit.
There are too many great things about clearsilver to list them all
here, but here are some of the salient points:
* get the html out of your code
* loops, conditionals, macros, and stuff
* cgi kit unifies query variable and cookie handling
* super-easy to go from static mockup to dynamic page
* run multiple front-ends on the same application code
* super-fast C-library
* unifies Query variable and cookie handling
* language neutral (C,C++,Python,Ruby,Perl,Java,C#)
* nice iterative page debugging/development features
* generate static-data-driven page content without using any code
* did I mention super-fast?
Supported language information:
README.python
*************************************************************
*** Tools
* trans.py
This is our transparent translation system. It's based on how we did
translation at Yahoo!. You leave all the english strings right in the
clearsilver templates. trans parses the html and extracts your
language strings into a translation database. You can then translate
the strings using any means. (it includes tools for dump and loading
per-language files for shipping to translators). Occasionally trans
isn't smart enough to find your language strings, in this case you can
manually extract them into static language string files and trans will
automatically pick them up. When it comes time to ship, trans
generates language-independent templates, and a set of language files
from your database.
*************************************************************
*** Examples
* static.cgi
This is a standalone binary which handles Clearsilver rendering of
static content. This is a great way to play with clearsilver syntax
before you start writing dynamic CGIs with it. This is also a great
way to do webpage mockups with much more power than server side
includes. See the INSTALL file for information about configuring
this for use with apache.
clearsilver-0.10.5/README.python 0000644 0012117 0011610 00000004102 10261037504 013217 0000000 0000000
************************************************************
*** Python Environment Information
* Python - we know it and love it
* Apache - the defacto standard
* PyApache/mod_python
Either one is fine, the goal is to load all Python code once, before
Apache forks. Then, for every web-request, Apache just makes a
function call into the Python environment which serves the page. This
is "really fast" as it gets rid of all of the parsing and loading of
Python. Various versions of PyApache and mod_python have gained and
lost and gained again the ability to do this well. We used a hacked
version of PyApache way back when, I think mod_python does this out of
the box today.
************************************************************
*** Python Tools
* CSPage.py
This is our "page rendering superclass". It's pretty simple and has
nice machinery for some of the stuff talked about on this list. For
example, it has nice debugging and redirect support, and it has a
mechanism for mapping form submit buttons to method names. Here is an
example of how the form stuff works:
class MyPage(CSPage):
def setup(self):
# this runs before everything else
pass
def display(self):
# this is a regular non-submission render
pass
def Action_Foo(self):
# this is run automatically when the Foo submit button is clicked
pass
* odb.py
This is an object to relational database mapping tool. It makes
interacting with SQL databases really easy. It gives you a place to
put all your SQL code. It also could be changed to work with flat
files as well. We have some nice hooks to connect this to Clearsilver,
so rendering database data into webpages is really easy. Here is an
example:
rows = mydb.mytable.fetchAllRows() # fetch all rows
rows.hdfExport("CGI.tabledata",ncgi.hdf) # export them into the dataset
# it is also really easy to change rows:
row = mydb.mytable.fetchRow( ('user', 'jeske') )
row.email = 'jeske at chat.net'
row.save()
clearsilver-0.10.5/INSTALL 0000644 0012117 0011610 00000011554 10261037503 012060 0000000 0000000 ********************************************
*
* Clearsilver INSTALL
*
* http://www.clearsilver.net
*
* Brandon Long, David Jeske
*
********************************************
1) Compile ------------------------------------------------
Simplest case:
# ./configure
# make
Options to configure:
--disable-compression Disables HTML Compression support
--enable-remote-debugger Enables remote X CGI debugging
--disable-apache Disables building of apache 1.3.x module
--with-apache=path Set location of Apache installation
--disable-python Disables building of python module
--with-python=path Set location of Python Includes
--disable-perl Disables building of perl module
--with-perl=path Set location of Perl binary
--disable-ruby Disables building of ruby module
--with-ruby=path Set location of Ruby binary
--disable-java Disables building of java module
--with-java=path Set location of J2SDK
--disable-csharp Disables building of csharp module
--with-csharp=path Set location of csharp
--enable-gettext Enable gettext message translation
--disable-compression: Currently, the CGI output code in the cgi
kit automatically attempts to detect whether the remote browser can
handle compressed data, and if it does, compresses the output for
text/html. This is run-time configurable via Config.CompressionEnabled.
Disabling it at compile time eliminates the dependency on libz.
--enable-remote-debugger: The CGI kit contains code for remotely
debuggin CGI programs by launching an X based debugger (such as xxgdb or
ddd) at the X display you specify in the HTTP request. There are
controls such as a configurable list of allowed displays, but remote
debugging is disabled by default.
--enable-gettext: Enables gettext message translation. Once enabled
you have a new builtin function "_()". This function calls the
function gettext (man 3 gettext).
The rest of the --disable/--with either disable a specific module, or
point ClearSilver at the right program to enable it. The configure
script will simple not build any module it can't find the right versions
of programs to build against. Alternatively, if you are making
ClearSilver part of your build environment, you can simple delete
whichever module directory you don't want, and the build will ignore it.
For information about compiling on Windows under MingW and MSYS, see
python/README.txt
The csharp wrapper was built with Mono (www.go-mono.com) and should work
with v0.24 and later (give or take). In theory, it should be fairly
simple to get this working on MS.Net as well.
2) Install ------------------------------------------------
# make install
The make install is relatively new, and just installs the
libraries/header files (and probably the perl and python modules, but
that's a guess)
3) Example 1, Apache static.cgi ----------------------------------
"static.cgi" is a simple binary which will allow you to write static
HDF files, static ClearSilver templates, and render them. This is a
good way to get started and learn the clearsilver model and
syntax. Follow the steps below to install static.cgi into your Apache
configuration and then read the documentation while playing with
static files.
http://www.clearsilver.net/docs/man_hdf.hdf
Add the following to your Apache configuration and copy the
Clearsilver static.cgi binary from cgi/static.cgi into your Apache
cgi-bin directory.
AddHandler cgi-script .cgi
Action cs-handler /cgi-bin/static.cgi
AddHandler cs-handler .cs
Since any html file is a valid CS file, I also run with:
AddHandler cs-handler .html
* About static.cgi:
static.cgi works by assuming that whatever file it was pointed at is a
CS template. It first tries to load common.hdf in the same directory,
then it tries to load some other hdf files, and then it parses and
displays the template file.
Ie, if its pointed at foo.cs, it will load common.hdf, try to load
foo.cs.hdf, if that fails, it tries foo.hdf. If the hdf defines
CGI.StaticContent, it will assume that's the real template file (which
is how we use it on www.clearsilver.net, we just point at he .hdf files,
which define StaticContent as a wrapper.cs, which includes another file
defined in the .hdf file).
4) Example 2, imd image server ------------------------------------
"imd" is a simple image server written with C and clearsilver. The imd
directory has a README on how to set up imd with Apache.
5) Example 3, using with Python -----------------------------------
The clearsilver python wrapper comes with CSPage.py. This file
contains the CSPage superclass, and this file gives some pointers on
how to use the cs handler via python. A much more thorough example
is Scott Hassan's image_server, available from
http://www.dotfunk.com/projects/image_server
clearsilver-0.10.5/LICENSE 0000644 0012117 0011610 00000001235 10527221146 012032 0000000 0000000
This source tree contains source code from Neotonic.
All files in this release are marked with their license
terms. Files which are part of our public open-source
toolkits are released under our Neotonic ClearSilver License.
A few files are from other sources, and will include their respective
copyrights and licenses.
If you did not receive a copy of the Neotonic ClearSilver License with
this kit, you can get one from:
http://www.clearsilver.net/license.hdf
Some source-kits received from Neotonic may contain
licensed Neotonic source code. That source code is
Copyright (C) Neotonic, and may not be used without
express written permission of Neotonic.
clearsilver-0.10.5/CS_LICENSE 0000644 0012117 0011610 00000005147 10261037503 012422 0000000 0000000
ClearSilver is available under the following license, derived
from the Apache Software License v1.1
For alternative licensing, please contact the authors at
blong@clearsilver.net
ClearSilver Software License
Version 1.0
Copyright (c) 2003 Brandon Long. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if any,
must include the following acknowledgment:
"This product includes software developed by
Neotonic Software Corp. (http://www.neotonic.com/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Neotonic" and "ClearSilver" must not be used
to endorse or promote products derived from this software without prior
written permission. For written permission, please contact
clearsilver@neotonic.com.
5. Products derived from this software may not be called "ClearSilver", nor
may "ClearSilver" appear in their name, without prior written permission of
Brandon Long or Neotonic Software Corp.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED 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 NEOTONIC, INC., OR ITS CLEARSILVER 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.
This software consists of voluntary contributions made by many
individuals on behalf of Brandon Long and Neotonic Software Corp. For
more information on Neotonic, please see .
Some of the concepts of this software are based on previous software
developed by Scott Shambarger, Paul Clegg, and John Cwikla. The current
authors wish to thank them for their efforts.
clearsilver-0.10.5/rules.mk.in 0000644 0012117 0011610 00000007502 10541666436 013133 0000000 0000000 ############################################################
#
# rules.mk is A U T O G E N E R A T E D
#
# you must edit: rules.mk.in
#
############################################################
##
## Global Makefile Rules
##
## Before including this file, you must set NEOTONIC_ROOT
##
OSNAME := $(shell uname -rs | cut -f 1-2 -d "." | cut -f 1 -d "-")
OSTYPE := $(shell uname -s)
LIB_DIR = $(NEOTONIC_ROOT)/libs/
## Installation Directories
srcdir = @srcdir@
top_srcdir = @top_srcdir@
VPATH = @srcdir@
prefix = @prefix@
exec_prefix = @exec_prefix@
bindir = @bindir@
sbindir = @sbindir@
libexecdir = @libexecdir@
datadir = @datadir@
sysconfdir = @sysconfdir@
sharedstatedir = @sharedstatedir@
localstatedir = @localstatedir@
libdir = @libdir@
infodir = @infodir@
mandir = @mandir@
includedir = @includedir@
DESTDIR =
cs_includedir = ${includedir}/ClearSilver
## NOTE: The wdb code in util will tickle a bug in SleepyCat 2.4.5,
## which ships with various versions of Linux as part of glibc. If you
## are going to use that code, you should compile against SleepyCat
## 2.7.7 instead
USE_DB2 = 1
USE_ZLIB = 1
@USE_MINGW32@
PICFLG = -fPIC
ifeq ($(OSTYPE),OSF1)
PICFLG =
endif
ifeq ($(OSNAME),MINGW32_NT)
PICFLG =
endif
## -------------- base (Linux/Neotonic) options
PYTHON_INC = @PYTHON_INC@
PYTHON_LIB = @PYTHON_LIB@
PYTHON_SITE = @PYTHON_SITE@
JAVA_PATH = @JAVA_PATH@
JAVA_INCLUDE_PATH = @JAVA_INCLUDE_PATH@
CSHARP_PATH = @CSHARP_PATH@
## Programs
@SET_MAKE@
INSTALL = @INSTALL@
CC = @CC@
MKDIR = mkdir -p
RM = rm -f
CPP = g++
JAVAC = $(JAVA_PATH)/bin/javac
JAVAH = $(JAVA_PATH)/bin/javah
JAR = $(JAVA_PATH)/bin/jar
APXS = @APXS_PATH@
PYTHON = @PYTHON@
PERL = @PERL@
RUBY = @RUBY@
CPPFLAGS = -I$(NEOTONIC_ROOT) @CPPFLAGS@
CFLAGS = @CFLAGS@ -Wall $(CPPFLAGS) $(PICFLG)
OUTPUT_OPTION = -o $@
LD = $(CC) -o
LDFLAGS = -L$(LIB_DIR) @LDFLAGS@
LDSHARED = $(CC) -shared $(PICFLG)
CPPLDSHARED = $(CPP) -shared $(PICFLG)
AR = @AR@ cr
RANLIB = @RANLIB@
DEP_LIBS = $(DLIBS:-l%=$(LIB_DIR)lib%.a)
DBI_LIBS = -ldbi -ldl -lz
LIBS = @LIBS@
LS = /bin/ls
XARGS = xargs -i%
BUILD_WRAPPERS = @BUILD_WRAPPERS@
EXTRA_UTL_OBJS = @EXTRA_UTL_OBJS@
EXTRA_UTL_SRC = @EXTRA_UTL_SRC@
## I don't really feel like writing a configure thing for this yet
ifeq ($(OSNAME),SunOS)
LDSHARED = ld -G -fPIC
endif
ifeq ($(OSTYPE),Darwin)
LDSHARED = $(CC) -bundle -flat_namespace -undefined suppress $(PICFLG)
CPPLDSHARED = $(CPP) -bundle -flat_namespace -undefined suppress $(PICFLG)
endif
## --------------win32 options
## ifeq ($(OSTYPE),WindowsNT)
## CFLAGS += -D__WINDOWS_GCC__
## USE_DB2 = 0
## USE_ZLIB = 0
## # SHELL=cmd.exe
## LS = ls
## PYTHON_INC = -Ic:/Python22/include
## LDSHARED= dllwrap
## endif
##
## ## --------------
##
## ifeq ($(OSTYPE),FreeBSD)
## XARGS = xargs -J%
## # This should work on freebsd... but I wouldn't worry too much about it
## USE_DB2 = 0
## PYTHON_INC = -I/usr/local/include/python2.2
## endif
##
## ifeq ($(USE_ZLIB),1)
## LIBS += -lz
## endif
##
## ifeq ($(USE_DB2),1)
## DB2_INC = -I$(HOME)/src/db-2.7.7/dist
## DB2_LIB = -L$(HOME)/src/db-2.7.7/dist -ldb
## CFLAGS += $(DB2_INC)
## endif
.c.o:
$(CC) $(CFLAGS) $(OUTPUT_OPTION) -c $<
everything: depend all
.PHONY: depend
depend: Makefile.depends
SOURCE_FILES := $(wildcard *.c)
Makefile.depends: $(NEOTONIC_ROOT)/rules.mk Makefile
@echo "*******************************************"
@echo "** Building Dependencies "
@echo "** OSNAME: $(OSTYPE)"
@rm -f Makefile.depends
@touch Makefile.depends
@if test "x" != "x$(SOURCE_FILES)"; then \
for II in "$(SOURCE_FILES)"; do \
gcc -M -MG ${CFLAGS} $$II >> Makefile.depends; \
done; \
fi
@echo "** (done) "
DEPEND_FILE := $(shell find . -name Makefile.depends -print)
ifneq ($(DEPEND_FILE),)
include Makefile.depends
endif
clearsilver-0.10.5/Makefile 0000644 0012117 0011610 00000006572 10645312520 012474 0000000 0000000 #
# Neotonic Source Kit
#
# Copyright (C) 2001 Neotonic and Brandon Long
#
#
NEOTONIC_ROOT = .
include rules.mk
SUBDIRS = util cs cgi $(BUILD_WRAPPERS)
OUTDIRS = bin libs
# These are blank here... but populated under automated build
VERSION =
RELEASE =
all: cs $(BUILD_WRAPPERS)
rules.mk: configure
./configure
configure: configure.in
./autogen.sh
cs: output_dir
@for mdir in $(SUBDIRS); do \
if test -d $$mdir; then \
if test -f $$mdir/Makefile.PL -a ! -f $$mdir/Makefile; then \
cd $$mdir; $(PERL) Makefile.PL PREFIX=$(prefix); cd ..; \
fi; \
$(MAKE) -C $$mdir PREFIX=$(prefix); \
fi; \
done
install: all
./mkinstalldirs $(DESTDIR)$(cs_includedir)
./mkinstalldirs $(DESTDIR)$(bindir)
./mkinstalldirs $(DESTDIR)$(libdir)
./mkinstalldirs $(DESTDIR)$(mandir)/man3
$(INSTALL) -m 644 ClearSilver.h $(DESTDIR)$(cs_includedir)/
$(INSTALL) -m 644 cs_config.h $(DESTDIR)$(cs_includedir)/
$(INSTALL) -m 644 man/man3/*.3 $(DESTDIR)$(mandir)/man3/
@for mdir in $(SUBDIRS); do \
if test -d $$mdir; then \
if test -f $$mdir/Makefile.PL -a ! -f $$mdir/Makefile; then \
cd $$mdir; $(PERL) Makefile.PL PREFIX=$(prefix); cd ..; \
fi; \
$(MAKE) -C $$mdir PREFIX=$(prefix) install; \
fi; \
done
depend:
@for mdir in $(SUBDIRS); do \
if test ! -f $$mdir/Makefile.PL; then \
$(MAKE) -C $$mdir depend; \
fi; \
done
newdepend: killdepend
@echo "*******************************************"
@echo "** Building dependencies..."
@for mdir in $(SUBDIRS); \
do $(MAKE) -C $$mdir depend; \
done
killdepend:
@echo "*******************************************"
@echo "** Removing Old dependencies..."
@find . -name "Makefile.depends" -print | $(XARGS) rm %
.PHONY: man
man:
@mkdir -p man/man3
@for mdir in $(SUBDIRS); do \
scripts/document.py --owner "ClearSilver" --outdir man/man3/ $$mdir/*.h; \
done
.PHONY: hdf
hdf:
@mkdir -p docs/hdf
@for mdir in $(SUBDIRS); do \
scripts/document.py --hdf --owner "ClearSilver" --outdir docs/hdf/ $$mdir/*.h; \
done
changelog:
p4 changes -l ./...
clean:
-@for mdir in $(SUBDIRS); do \
$(MAKE) -C $$mdir clean; \
done
distclean:
-@for mdir in $(SUBDIRS); do \
$(MAKE) -C $$mdir distclean; \
done
-@for mdir in $(OUTDIRS); do \
rm -rf $$mdir/*; \
done
rm -f config.cache config.log config.status rules.mk cs_config.h
rm -rf autom4te.cache
output_dir:
@for mdir in $(OUTDIRS); do \
mkdir -p $$mdir; \
done
CS_DISTDIR = clearsilver-0.10.5
CS_LABEL = CLEARSILVER-0_10_5
CS_FILES = README README.python INSTALL LICENSE CS_LICENSE rules.mk.in Makefile acconfig.h autogen.sh config.guess config.sub configure.in cs_config.h.in mkinstalldirs install-sh ClearSilver.h
CS_DIRS = util cs cgi python scripts mod_ecs imd java-jni perl ruby dso csharp ports contrib m4
cs_dist:
@if p4 labels Makefile | grep "${CS_LABEL}"; then \
echo "release ${CS_LABEL} already exists"; \
echo " to rebuild, type: p4 label -d ${CS_LABEL}"; \
exit 1; \
fi;
rm -rf $(CS_DISTDIR)
p4 label $(CS_LABEL)
p4 labelsync -l$(CS_LABEL) $(CS_FILES) $(addsuffix /..., $(CS_DIRS))
mkdir -p $(CS_DISTDIR)
tar -cf - `p4 files $(CS_FILES) $(addsuffix /..., $(CS_DIRS)) | cut -d'#' -f 1 | sed -e "s|//depot/google3/third_party/clearsilver/core/||"` | (cd $(CS_DISTDIR); tar -xf -)
$(MAKE) -C $(CS_DISTDIR) man distclean
chmod -R u+w $(CS_DISTDIR)
chmod -R a+r $(CS_DISTDIR)
tar chozf $(CS_DISTDIR).tar.gz $(CS_DISTDIR)
clearsilver-0.10.5/acconfig.h 0000644 0012117 0011610 00000002576 10261037504 012756 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
/*
* config file
*/
#ifndef __CS_CONFIG_H_
#define __CS_CONFIG_H_ 1
@TOP@
/* Enable support for HTML Compression (still must be enabled at run time) */
#undef HTML_COMPRESSION
/* Enable support for X Remote CGI Debugging */
#undef ENABLE_REMOTE_DEBUG
/********* SYSTEM CONFIG ***************************************************/
/* autoconf/configure should figure all of these out for you */
/* Does your system have the snprintf() call? */
#undef HAVE_SNPRINTF
/* Does your system have the vsnprintf() call? */
#undef HAVE_VSNPRINTF
/* Does your system have the strtok_r() call? */
#undef HAVE_STRTOK_R
/* Does your system have the localtime_r() call? */
#undef HAVE_LOCALTIME_R
/* Does your system have the gmtime_r() call? */
#undef HAVE_GMTIME_R
/* Does your system have the mkstemp() call? */
#undef HAVE_MKSTEMP
/* Does your system have regex.h */
#undef HAVE_REGEX
/* Does your system have pthreads? */
#undef HAVE_PTHREADS
/* Does your system have lockf ? */
#undef HAVE_LOCKF
/* Does your system have Berkeley DB v2 ? */
#undef HAVE_DB2
/* Enable support for gettext message translation */
#undef ENABLE_GETTEXT
@BOTTOM@
#endif /* __CS_CONFIG_H_ */
clearsilver-0.10.5/autogen.sh 0000755 0012117 0011610 00000000247 10336777403 013042 0000000 0000000 #!/bin/sh
# Run this to generate all the initial makefiles, etc.
srcdir=`dirname $0`
test -z "$srcdir" && srcdir=.
aclocal -I m4
autoheader
autoconf
./configure $*
clearsilver-0.10.5/config.guess 0000755 0012117 0011610 00000113150 10326267523 013353 0000000 0000000 #! /bin/sh
# Attempt to guess a canonical system name.
# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
# Free Software Foundation, Inc.
timestamp='2001-09-04'
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# 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.
# Written by Per Bothner .
# Please send patches to .
#
# This script attempts to guess a canonical system name similar to
# config.sub. If it succeeds, it prints the system name on stdout, and
# exits with 0. Otherwise, it exits with 1.
#
# The plan is that this can be called by configure scripts if you
# don't specify an explicit build system type.
me=`echo "$0" | sed -e 's,.*/,,'`
usage="\
Usage: $0 [OPTION]
Output the configuration name of the system \`$me' is run on.
Operation modes:
-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 (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
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 0 ;;
--version | -v )
echo "$version" ; exit 0 ;;
--help | --h* | -h )
echo "$usage"; exit 0 ;;
-- ) # 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
dummy=dummy-$$
trap 'rm -f $dummy.c $dummy.o $dummy.rel $dummy; exit 1' 1 2 15
# CC_FOR_BUILD -- compiler used by this script.
# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
# use `HOST_CC' if defined, but it is deprecated.
set_cc_for_build='case $CC_FOR_BUILD,$HOST_CC,$CC in
,,) echo "int dummy(){}" > $dummy.c ;
for c in cc gcc c89 ; do
($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1 ;
if test $? = 0 ; then
CC_FOR_BUILD="$c"; break ;
fi ;
done ;
rm -f $dummy.c $dummy.o $dummy.rel ;
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'
# 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
# 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 tupples: *-*-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.
# Determine the machine/vendor (is the vendor relevant).
case "${UNAME_MACHINE}" in
amiga) machine=m68k-unknown ;;
arm32) machine=arm-unknown ;;
atari*) machine=m68k-atari ;;
sun3*) machine=m68k-sun ;;
mac68k) machine=m68k-apple ;;
macppc) machine=powerpc-apple ;;
hp3[0-9][05]) machine=m68k-hp ;;
ibmrt|romp-ibm) machine=romp-ibm ;;
*) machine=${UNAME_MACHINE}-unknown ;;
esac
# The Operating System including object format, if it has switched
# to ELF recently, or will in the future.
case "${UNAME_MACHINE}" in
i386|sparc|amiga|arm*|hp300|mvme68k|vax|atari|luna68k|mac68k|news68k|next68k|pc532|sun3*|x68k)
eval $set_cc_for_build
if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
| grep __ELF__ >/dev/null
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
# The OS release
release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
# contains redundant information, the shorter form:
# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
echo "${machine}-${os}${release}"
exit 0 ;;
alpha:OSF1:*:*)
if test $UNAME_RELEASE = "V4.0"; then
UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
fi
# 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.
cat <$dummy.s
.data
\$Lformat:
.byte 37,100,45,37,120,10,0 # "%d-%x\n"
.text
.globl main
.align 4
.ent main
main:
.frame \$30,16,\$26,0
ldgp \$29,0(\$27)
.prologue 1
.long 0x47e03d80 # implver \$0
lda \$2,-1
.long 0x47e20c21 # amask \$2,\$1
lda \$16,\$Lformat
mov \$0,\$17
not \$1,\$18
jsr \$26,printf
ldgp \$29,0(\$26)
mov 0,\$16
jsr \$26,exit
.end main
EOF
eval $set_cc_for_build
$CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null
if test "$?" = 0 ; then
case `./$dummy` in
0-0)
UNAME_MACHINE="alpha"
;;
1-0)
UNAME_MACHINE="alphaev5"
;;
1-1)
UNAME_MACHINE="alphaev56"
;;
1-101)
UNAME_MACHINE="alphapca56"
;;
2-303)
UNAME_MACHINE="alphaev6"
;;
2-307)
UNAME_MACHINE="alphaev67"
;;
2-1307)
UNAME_MACHINE="alphaev68"
;;
esac
fi
rm -f $dummy.s $dummy
echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
exit 0 ;;
Alpha\ *:Windows_NT*:*)
# How do we know it's Interix rather than the generic POSIX subsystem?
# Should we change UNAME_MACHINE based on the output of uname instead
# of the specific Alpha model?
echo alpha-pc-interix
exit 0 ;;
21064:Windows_NT:50:3)
echo alpha-dec-winnt3.5
exit 0 ;;
Amiga*:UNIX_System_V:4.0:*)
echo m68k-unknown-sysv4
exit 0;;
amiga:OpenBSD:*:*)
echo m68k-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
*:[Aa]miga[Oo][Ss]:*:*)
echo ${UNAME_MACHINE}-unknown-amigaos
exit 0 ;;
arc64:OpenBSD:*:*)
echo mips64el-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
arc:OpenBSD:*:*)
echo mipsel-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
hkmips:OpenBSD:*:*)
echo mips-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
pmax:OpenBSD:*:*)
echo mipsel-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
sgi:OpenBSD:*:*)
echo mips-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
wgrisc:OpenBSD:*:*)
echo mipsel-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
*:OS/390:*:*)
echo i370-ibm-openedition
exit 0 ;;
arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
echo arm-acorn-riscix${UNAME_RELEASE}
exit 0;;
SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
echo hppa1.1-hitachi-hiuxmpp
exit 0;;
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 0 ;;
NILE*:*:*:dcosx)
echo pyramid-pyramid-svr4
exit 0 ;;
sun4H:SunOS:5.*:*)
echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
exit 0 ;;
sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
exit 0 ;;
i86pc:SunOS:5.*:*)
echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
exit 0 ;;
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 0 ;;
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 0 ;;
sun3*:SunOS:*:*)
echo m68k-sun-sunos${UNAME_RELEASE}
exit 0 ;;
sun*:*:4.2BSD:*)
UNAME_RELEASE=`(head -1 /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 0 ;;
aushp:SunOS:*:*)
echo sparc-auspex-sunos${UNAME_RELEASE}
exit 0 ;;
sparc*:NetBSD:*)
echo `uname -p`-unknown-netbsd${UNAME_RELEASE}
exit 0 ;;
atari*:OpenBSD:*:*)
echo m68k-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
# 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 0 ;;
atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
echo m68k-atari-mint${UNAME_RELEASE}
exit 0 ;;
*falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
echo m68k-atari-mint${UNAME_RELEASE}
exit 0 ;;
milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
echo m68k-milan-mint${UNAME_RELEASE}
exit 0 ;;
hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
echo m68k-hades-mint${UNAME_RELEASE}
exit 0 ;;
*:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
echo m68k-unknown-mint${UNAME_RELEASE}
exit 0 ;;
sun3*:OpenBSD:*:*)
echo m68k-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
mac68k:OpenBSD:*:*)
echo m68k-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
mvme68k:OpenBSD:*:*)
echo m68k-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
mvme88k:OpenBSD:*:*)
echo m88k-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
powerpc:machten:*:*)
echo powerpc-apple-machten${UNAME_RELEASE}
exit 0 ;;
RISC*:Mach:*:*)
echo mips-dec-mach_bsd4.3
exit 0 ;;
RISC*:ULTRIX:*:*)
echo mips-dec-ultrix${UNAME_RELEASE}
exit 0 ;;
VAX*:ULTRIX*:*:*)
echo vax-dec-ultrix${UNAME_RELEASE}
exit 0 ;;
2020:CLIX:*:* | 2430:CLIX:*:*)
echo clipper-intergraph-clix${UNAME_RELEASE}
exit 0 ;;
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 $dummy.c -o $dummy \
&& ./$dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
&& rm -f $dummy.c $dummy && exit 0
rm -f $dummy.c $dummy
echo mips-mips-riscos${UNAME_RELEASE}
exit 0 ;;
Motorola:PowerMAX_OS:*:*)
echo powerpc-motorola-powermax
exit 0 ;;
Night_Hawk:Power_UNIX:*:*)
echo powerpc-harris-powerunix
exit 0 ;;
m88k:CX/UX:7*:*)
echo m88k-harris-cxux7
exit 0 ;;
m88k:*:4*:R4*)
echo m88k-motorola-sysv4
exit 0 ;;
m88k:*:3*:R3*)
echo m88k-motorola-sysv3
exit 0 ;;
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 0 ;;
M88*:DolphinOS:*:*) # DolphinOS (SVR3)
echo m88k-dolphin-sysv3
exit 0 ;;
M88*:*:R3*:*)
# Delta 88k system running SVR3
echo m88k-motorola-sysv3
exit 0 ;;
XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
echo m88k-tektronix-sysv3
exit 0 ;;
Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
echo m68k-tektronix-bsd
exit 0 ;;
*:IRIX*:*:*)
echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
exit 0 ;;
????????: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 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX '
i*86:AIX:*:*)
echo i386-ibm-aix
exit 0 ;;
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 0 ;;
*: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
$CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
rm -f $dummy.c $dummy
echo rs6000-ibm-aix3.2.5
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 0 ;;
*:AIX:*:[45])
IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | 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/oslevel ] ; then
IBM_REV=`/usr/bin/oslevel`
else
IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
fi
echo ${IBM_ARCH}-ibm-aix${IBM_REV}
exit 0 ;;
*:AIX:*:*)
echo rs6000-ibm-aix
exit 0 ;;
ibmrt:4.4BSD:*|romp-ibm:BSD:*)
echo romp-ibm-bsd4.4
exit 0 ;;
ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
exit 0 ;; # report: romp-ibm BSD 4.3
*:BOSX:*:*)
echo rs6000-bull-bosx
exit 0 ;;
DPX/2?00:B.O.S.:*:*)
echo m68k-bull-sysv3
exit 0 ;;
9000/[34]??:4.3bsd:1.*:*)
echo m68k-hp-bsd
exit 0 ;;
hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
echo m68k-hp-bsd4.4
exit 0 ;;
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])
case "${HPUX_REV}" in
11.[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" ;;
esac ;;
esac
fi ;;
esac
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 $dummy.c -o $dummy 2>/dev/null ) && HP_ARCH=`./$dummy`
if test -z "$HP_ARCH"; then HP_ARCH=hppa; fi
rm -f $dummy.c $dummy
fi ;;
esac
echo ${HP_ARCH}-hp-hpux${HPUX_REV}
exit 0 ;;
ia64:HP-UX:*:*)
HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
echo ia64-hp-hpux${HPUX_REV}
exit 0 ;;
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 $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
rm -f $dummy.c $dummy
echo unknown-hitachi-hiuxwe2
exit 0 ;;
9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
echo hppa1.1-hp-bsd
exit 0 ;;
9000/8??:4.3bsd:*:*)
echo hppa1.0-hp-bsd
exit 0 ;;
*9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
echo hppa1.0-hp-mpeix
exit 0 ;;
hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
echo hppa1.1-hp-osf
exit 0 ;;
hp8??:OSF1:*:*)
echo hppa1.0-hp-osf
exit 0 ;;
i*86:OSF1:*:*)
if [ -x /usr/sbin/sysversion ] ; then
echo ${UNAME_MACHINE}-unknown-osf1mk
else
echo ${UNAME_MACHINE}-unknown-osf1
fi
exit 0 ;;
parisc*:Lites*:*:*)
echo hppa1.1-hp-lites
exit 0 ;;
hppa*:OpenBSD:*:*)
echo hppa-unknown-openbsd
exit 0 ;;
C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
echo c1-convex-bsd
exit 0 ;;
C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
if getsysinfo -f scalar_acc
then echo c32-convex-bsd
else echo c2-convex-bsd
fi
exit 0 ;;
C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
echo c34-convex-bsd
exit 0 ;;
C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
echo c38-convex-bsd
exit 0 ;;
C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
echo c4-convex-bsd
exit 0 ;;
CRAY*X-MP:*:*:*)
echo xmp-cray-unicos
exit 0 ;;
CRAY*Y-MP:*:*:*)
echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
exit 0 ;;
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 0 ;;
CRAY*TS:*:*:*)
echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
exit 0 ;;
CRAY*T3D:*:*:*)
echo alpha-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
exit 0 ;;
CRAY*T3E:*:*:*)
echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
exit 0 ;;
CRAY*SV1:*:*:*)
echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
exit 0 ;;
CRAY-2:*:*:*)
echo cray2-cray-unicos
exit 0 ;;
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 0 ;;
hp300:OpenBSD:*:*)
echo m68k-unknown-openbsd${UNAME_RELEASE}
exit 0 ;;
i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
exit 0 ;;
sparc*:BSD/OS:*:*)
echo sparc-unknown-bsdi${UNAME_RELEASE}
exit 0 ;;
*:BSD/OS:*:*)
echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
exit 0 ;;
*:FreeBSD:*:*)
echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
exit 0 ;;
*:OpenBSD:*:*)
echo ${UNAME_MACHINE}-unknown-openbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
exit 0 ;;
i*:CYGWIN*:*)
echo ${UNAME_MACHINE}-pc-cygwin
exit 0 ;;
i*:MINGW*:*)
echo ${UNAME_MACHINE}-pc-mingw32
exit 0 ;;
i*:PW*:*)
echo ${UNAME_MACHINE}-pc-pw32
exit 0 ;;
i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
# How do we know it's Interix rather than the generic POSIX subsystem?
# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
# UNAME_MACHINE based on the output of uname instead of i386?
echo i386-pc-interix
exit 0 ;;
i*:UWIN*:*)
echo ${UNAME_MACHINE}-pc-uwin
exit 0 ;;
p*:CYGWIN*:*)
echo powerpcle-unknown-cygwin
exit 0 ;;
prep*:SunOS:5.*:*)
echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
exit 0 ;;
*:GNU:*:*)
echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
exit 0 ;;
i*86:Minix:*:*)
echo ${UNAME_MACHINE}-pc-minix
exit 0 ;;
arm*:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux-gnu
exit 0 ;;
ia64:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux
exit 0 ;;
m68*:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux-gnu
exit 0 ;;
mips:Linux:*:*)
case `sed -n '/^byte/s/^.*: \(.*\) endian/\1/p' < /proc/cpuinfo` in
big) echo mips-unknown-linux-gnu && exit 0 ;;
little) echo mipsel-unknown-linux-gnu && exit 0 ;;
esac
;;
ppc:Linux:*:*)
echo powerpc-unknown-linux-gnu
exit 0 ;;
ppc64:Linux:*:*)
echo powerpc64-unknown-linux-gnu
exit 0 ;;
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 ld.so.1 >/dev/null
if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
exit 0 ;;
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-gnu ;;
PA8*) echo hppa2.0-unknown-linux-gnu ;;
*) echo hppa-unknown-linux-gnu ;;
esac
exit 0 ;;
parisc64:Linux:*:* | hppa64:Linux:*:*)
echo hppa64-unknown-linux-gnu
exit 0 ;;
s390:Linux:*:* | s390x:Linux:*:*)
echo ${UNAME_MACHINE}-ibm-linux
exit 0 ;;
sh*:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux-gnu
exit 0 ;;
sparc:Linux:*:* | sparc64:Linux:*:*)
echo ${UNAME_MACHINE}-unknown-linux-gnu
exit 0 ;;
x86_64:Linux:*:*)
echo x86_64-unknown-linux-gnu
exit 0 ;;
i*86:Linux:*:*)
# The BFD linker knows what the default object file format is, so
# first see if it will tell us. cd to the root directory to prevent
# problems with other programs or directories called `ld' in the path.
ld_supported_targets=`cd /; ld --help 2>&1 \
| sed -ne '/supported targets:/!d
s/[ ][ ]*/ /g
s/.*supported targets: *//
s/ .*//
p'`
case "$ld_supported_targets" in
elf32-i386)
TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
;;
a.out-i386-linux)
echo "${UNAME_MACHINE}-pc-linux-gnuaout"
exit 0 ;;
coff-i386)
echo "${UNAME_MACHINE}-pc-linux-gnucoff"
exit 0 ;;
"")
# Either a pre-BFD a.out linker (linux-gnuoldld) or
# one that does not give us useful --help.
echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
exit 0 ;;
esac
# Determine whether the default compiler is a.out or elf
eval $set_cc_for_build
cat >$dummy.c <
#ifdef __cplusplus
#include /* for printf() prototype */
int main (int argc, char *argv[]) {
#else
int main (argc, argv) int argc; char *argv[]; {
#endif
#ifdef __ELF__
# ifdef __GLIBC__
# if __GLIBC__ >= 2
printf ("%s-pc-linux-gnu\n", argv[1]);
# else
printf ("%s-pc-linux-gnulibc1\n", argv[1]);
# endif
# else
printf ("%s-pc-linux-gnulibc1\n", argv[1]);
# endif
#else
printf ("%s-pc-linux-gnuaout\n", argv[1]);
#endif
return 0;
}
EOF
$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0
rm -f $dummy.c $dummy
test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
;;
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 0 ;;
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 0 ;;
i*86:*:4.*:* | i*86:SYSTEM_V: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 0 ;;
i*86:*:5:[78]*)
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 0 ;;
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|egrep Release|sed -e 's/.*= //')`
(/bin/uname -X|egrep i80486 >/dev/null) && UNAME_MACHINE=i486
(/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \
&& UNAME_MACHINE=i586
(/bin/uname -X|egrep '^Machine.*Pent ?II' >/dev/null) \
&& UNAME_MACHINE=i686
(/bin/uname -X|egrep '^Machine.*Pentium Pro' >/dev/null) \
&& UNAME_MACHINE=i686
echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
else
echo ${UNAME_MACHINE}-pc-sysv32
fi
exit 0 ;;
i*86:*DOS:*:*)
echo ${UNAME_MACHINE}-pc-msdosdjgpp
exit 0 ;;
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 i386.
echo i386-pc-msdosdjgpp
exit 0 ;;
Intel:Mach:3*:*)
echo i386-pc-mach3
exit 0 ;;
paragon:*:*:*)
echo i860-intel-osf1
exit 0 ;;
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 0 ;;
mini*:CTIX:SYS*5:*)
# "miniframe"
echo m68010-convergent-sysv
exit 0 ;;
M68*:*:R3V[567]*:*)
test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 4850:*: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 0
/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
&& echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
&& echo i486-ncr-sysv4 && exit 0 ;;
m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
echo m68k-unknown-lynxos${UNAME_RELEASE}
exit 0 ;;
mc68030:UNIX_System_V:4.*:*)
echo m68k-atari-sysv4
exit 0 ;;
i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
echo i386-unknown-lynxos${UNAME_RELEASE}
exit 0 ;;
TSUNAMI:LynxOS:2.*:*)
echo sparc-unknown-lynxos${UNAME_RELEASE}
exit 0 ;;
rs6000:LynxOS:2.*:*)
echo rs6000-unknown-lynxos${UNAME_RELEASE}
exit 0 ;;
PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
echo powerpc-unknown-lynxos${UNAME_RELEASE}
exit 0 ;;
SM[BE]S:UNIX_SV:*:*)
echo mips-dde-sysv${UNAME_RELEASE}
exit 0 ;;
RM*:ReliantUNIX-*:*:*)
echo mips-sni-sysv4
exit 0 ;;
RM*:SINIX-*:*:*)
echo mips-sni-sysv4
exit 0 ;;
*: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 0 ;;
PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
# says
echo i586-unisys-sysv4
exit 0 ;;
*:UNIX_System_V:4*:FTX*)
# From Gerald Hewes .
# How about differentiating between stratus architectures? -djm
echo hppa1.1-stratus-sysv4
exit 0 ;;
*:*:*:FTX*)
# From seanf@swdc.stratus.com.
echo i860-stratus-sysv4
exit 0 ;;
*:VOS:*:*)
# From Paul.Green@stratus.com.
echo hppa1.1-stratus-vos
exit 0 ;;
mc68*:A/UX:*:*)
echo m68k-apple-aux${UNAME_RELEASE}
exit 0 ;;
news*:NEWS-OS:6*:*)
echo mips-sony-newsos6
exit 0 ;;
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 0 ;;
BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
echo powerpc-be-beos
exit 0 ;;
BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
echo powerpc-apple-beos
exit 0 ;;
BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
echo i586-pc-beos
exit 0 ;;
SX-4:SUPER-UX:*:*)
echo sx4-nec-superux${UNAME_RELEASE}
exit 0 ;;
SX-5:SUPER-UX:*:*)
echo sx5-nec-superux${UNAME_RELEASE}
exit 0 ;;
Power*:Rhapsody:*:*)
echo powerpc-apple-rhapsody${UNAME_RELEASE}
exit 0 ;;
*:Rhapsody:*:*)
echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
exit 0 ;;
*:Darwin:*:*)
echo `uname -p`-apple-darwin${UNAME_RELEASE}
exit 0 ;;
*:procnto*:*:* | *:QNX:[0123456789]*:*)
if test "${UNAME_MACHINE}" = "x86pc"; then
UNAME_MACHINE=pc
fi
echo `uname -p`-${UNAME_MACHINE}-nto-qnx
exit 0 ;;
*:QNX:*:4*)
echo i386-pc-qnx
exit 0 ;;
NSR-[KW]:NONSTOP_KERNEL:*:*)
echo nsr-tandem-nsk${UNAME_RELEASE}
exit 0 ;;
*:NonStop-UX:*:*)
echo mips-compaq-nonstopux
exit 0 ;;
BS2000:POSIX*:*:*)
echo bs2000-siemens-sysv
exit 0 ;;
DS/*:UNIX_System_V:*:*)
echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
exit 0 ;;
*: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 0 ;;
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 0 ;;
*:TOPS-10:*:*)
echo pdp10-unknown-tops10
exit 0 ;;
*:TENEX:*:*)
echo pdp10-unknown-tenex
exit 0 ;;
KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
echo pdp10-dec-tops20
exit 0 ;;
XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
echo pdp10-xkl-tops20
exit 0 ;;
*:TOPS-20:*:*)
echo pdp10-unknown-tops20
exit 0 ;;
*:ITS:*:*)
echo pdp10-unknown-its
exit 0 ;;
i*86:XTS-300:*:STOP)
echo ${UNAME_MACHINE}-unknown-stop
exit 0 ;;
i*86:atheos:*:*)
echo ${UNAME_MACHINE}-unknown-atheos
exit 0 ;;
esac
#echo '(No uname command or uname output not recognized.)' 1>&2
#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
eval $set_cc_for_build
cat >$dummy.c <
# include
#endif
main ()
{
#if defined (sony)
#if defined (MIPSEB)
/* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed,
I don't know.... */
printf ("mips-sony-bsd\n"); exit (0);
#else
#include
printf ("m68k-sony-newsos%s\n",
#ifdef NEWSOS4
"4"
#else
""
#endif
); exit (0);
#endif
#endif
#if defined (__arm) && defined (__acorn) && defined (__unix)
printf ("arm-acorn-riscix"); exit (0);
#endif
#if defined (hp300) && !defined (hpux)
printf ("m68k-hp-bsd\n"); exit (0);
#endif
#if defined (NeXT)
#if !defined (__ARCHITECTURE__)
#define __ARCHITECTURE__ "m68k"
#endif
int version;
version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
if (version < 4)
printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
else
printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
exit (0);
#endif
#if defined (MULTIMAX) || defined (n16)
#if defined (UMAXV)
printf ("ns32k-encore-sysv\n"); exit (0);
#else
#if defined (CMU)
printf ("ns32k-encore-mach\n"); exit (0);
#else
printf ("ns32k-encore-bsd\n"); exit (0);
#endif
#endif
#endif
#if defined (__386BSD__)
printf ("i386-pc-bsd\n"); exit (0);
#endif
#if defined (sequent)
#if defined (i386)
printf ("i386-sequent-dynix\n"); exit (0);
#endif
#if defined (ns32000)
printf ("ns32k-sequent-dynix\n"); exit (0);
#endif
#endif
#if defined (_SEQUENT_)
struct utsname un;
uname(&un);
if (strncmp(un.version, "V2", 2) == 0) {
printf ("i386-sequent-ptx2\n"); exit (0);
}
if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
printf ("i386-sequent-ptx1\n"); exit (0);
}
printf ("i386-sequent-ptx\n"); exit (0);
#endif
#if defined (vax)
# if !defined (ultrix)
# include
# if defined (BSD)
# if BSD == 43
printf ("vax-dec-bsd4.3\n"); exit (0);
# else
# if BSD == 199006
printf ("vax-dec-bsd4.3reno\n"); exit (0);
# else
printf ("vax-dec-bsd\n"); exit (0);
# endif
# endif
# else
printf ("vax-dec-bsd\n"); exit (0);
# endif
# else
printf ("vax-dec-ultrix\n"); exit (0);
# endif
#endif
#if defined (alliant) && defined (i860)
printf ("i860-alliant-bsd\n"); exit (0);
#endif
exit (1);
}
EOF
$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy && rm -f $dummy.c $dummy && exit 0
rm -f $dummy.c $dummy
# Apollos put the system type in the environment.
test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
# Convex versions that predate uname can use getsysinfo(1)
if [ -x /usr/convex/getsysinfo ]
then
case `getsysinfo -f cpu_type` in
c1*)
echo c1-convex-bsd
exit 0 ;;
c2*)
if getsysinfo -f scalar_acc
then echo c32-convex-bsd
else echo c2-convex-bsd
fi
exit 0 ;;
c34*)
echo c34-convex-bsd
exit 0 ;;
c38*)
echo c38-convex-bsd
exit 0 ;;
c4*)
echo c4-convex-bsd
exit 0 ;;
esac
fi
cat >&2 < in order to provide the needed
information to handle your system.
config.guess timestamp = $timestamp
uname -m = `(uname -m) 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 'write-file-hooks 'time-stamp)
# time-stamp-start: "timestamp='"
# time-stamp-format: "%:y-%02m-%02d"
# time-stamp-end: "'"
# End:
clearsilver-0.10.5/config.sub 0000755 0012117 0011610 00000067100 10326267524 013022 0000000 0000000 #! /bin/sh
# Configuration validation subroutine script.
# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
# Free Software Foundation, Inc.
timestamp='2001-09-07'
# This file is (in principle) common to ALL GNU software.
# The presence of a machine in this file suggests that SOME GNU software
# can handle that machine. It does not imply ALL GNU software can.
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# 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.
# 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.
# 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
$0 [OPTION] ALIAS
Canonicalize a configuration name.
Operation modes:
-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 (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
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 0 ;;
--version | -v )
echo "$version" ; exit 0 ;;
--help | --h* | -h )
echo "$usage"; exit 0 ;;
-- ) # 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 0;;
* )
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* | storm-chaos* | os2-emx* | windows32-*)
os=-$maybe_os
basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
;;
*)
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)
os=
basic_machine=$1
;;
-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
;;
-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/'`
;;
-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*)
os=-lynxos
;;
-ptx*)
basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
;;
-windowsnt*)
os=`echo $os | sed -e 's/windowsnt/winnt/'`
;;
-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 \
| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
| arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
| c4x | clipper \
| d10v | d30v | dsp16xx \
| fr30 \
| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
| i370 | i860 | i960 | ia64 \
| m32r | m68000 | m68k | m88k | mcore \
| mips16 | mips64 | mips64el | mips64orion | mips64orionel \
| mips64vr4100 | mips64vr4100el | mips64vr4300 \
| mips64vr4300el | mips64vr5000 | mips64vr5000el \
| mipsbe | mipseb | mipsel | mipsle | mipstx39 | mipstx39el \
| mipsisa32 \
| mn10200 | mn10300 \
| ns16k | ns32k \
| openrisc \
| pdp10 | pdp11 | pj | pjl \
| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
| pyramid \
| s390 | s390x \
| sh | sh[34] | sh[34]eb | shbe | shle \
| sparc | sparc64 | sparclet | sparclite | sparcv9 | sparcv9b \
| stormy16 | strongarm \
| tahoe | thumb | tic80 | tron \
| v850 \
| we32k \
| x86 | xscale \
| z8k)
basic_machine=$basic_machine-unknown
;;
m6811 | m68hc11 | m6812 | m68hc12)
# Motorola 68HC11/12.
basic_machine=$basic_machine-unknown
os=-none
;;
m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
;;
# 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-* \
| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
| alphapca5[67]-* | arc-* \
| arm-* | armbe-* | armle-* | armv*-* \
| bs2000-* \
| c[123]* | c30-* | [cjt]90-* | c54x-* \
| clipper-* | cray2-* | cydra-* \
| d10v-* | d30v-* \
| elxsi-* \
| f30[01]-* | f700-* | fr30-* | fx80-* \
| h8300-* | h8500-* \
| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
| i*86-* | i860-* | i960-* | ia64-* \
| m32r-* \
| m68000-* | m680[01234]0-* | m68360-* | m683?2-* | m68k-* \
| m88110-* | m88k-* | mcore-* \
| mips-* | mips16-* | mips64-* | mips64el-* | mips64orion-* \
| mips64orionel-* | mips64vr4100-* | mips64vr4100el-* \
| mips64vr4300-* | mips64vr4300el-* | mipsbe-* | mipseb-* \
| mipsle-* | mipsel-* | mipstx39-* | mipstx39el-* \
| none-* | np1-* | ns16k-* | ns32k-* \
| orion-* \
| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
| pyramid-* \
| romp-* | rs6000-* \
| s390-* | s390x-* \
| sh-* | sh[34]-* | sh[34]eb-* | shbe-* | shle-* \
| sparc-* | sparc64-* | sparc86x-* | sparclite-* \
| sparcv9-* | sparcv9b-* | stormy16-* | strongarm-* | sv1-* \
| t3e-* | tahoe-* | thumb-* | tic30-* | tic54x-* | tic80-* | tron-* \
| v850-* | vax-* \
| we32k-* \
| x86-* | x86_64-* | xmp-* | xps100-* | xscale-* \
| ymp-* \
| z8k-*)
;;
# 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-unknown
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
;;
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
;;
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
;;
aux)
basic_machine=m68k-apple
os=-aux
;;
balance)
basic_machine=ns32k-sequent
os=-dynix
;;
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 | ymp)
basic_machine=ymp-cray
os=-unicos
;;
cray2)
basic_machine=cray2-cray
os=-unicos
;;
[cjt]90)
basic_machine=${basic_machine}-cray
os=-unicos
;;
crds | unos)
basic_machine=m68k-crds
;;
cris | cris-* | etrax*)
basic_machine=cris-axis
;;
da30 | da30-*)
basic_machine=m68k-da30
;;
decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
basic_machine=mips-dec
;;
delta | 3300 | motorola-3300 | motorola-delta \
| 3300-motorola | delta-motorola)
basic_machine=m68k-motorola
;;
delta88)
basic_machine=m88k-motorola
os=-sysv3
;;
dpx20 | dpx20-*)
basic_machine=rs6000-bull
os=-bosx
;;
dpx2* | dpx2*-bull)
basic_machine=m68k-bull
os=-sysv3
;;
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
;;
hppa-next)
os=-nextstep3
;;
hppaosf)
basic_machine=hppa1.1-hp
os=-osf
;;
hppro)
basic_machine=hppa1.1-hp
os=-proelf
;;
i370-ibm* | ibm*)
basic_machine=i370-ibm
;;
# I'm not sure what "Sysv32" means. Should this be sysv3.2?
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
;;
i386-vsta | 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
;;
m88k-omron*)
basic_machine=m88k-omron
;;
magnum | m3230)
basic_machine=mips-mips
os=-sysv
;;
merlin)
basic_machine=ns32k-utek
os=-sysv
;;
mingw32)
basic_machine=i386-pc
os=-mingw32
;;
miniframe)
basic_machine=m68000-convergent
;;
*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
basic_machine=m68k-atari
os=-mint
;;
mipsel*-linux*)
basic_machine=mipsel-unknown
os=-linux-gnu
;;
mips*-linux*)
basic_machine=mips-unknown
os=-linux-gnu
;;
mips3*-*)
basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
;;
mips3*)
basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
;;
mmix*)
basic_machine=mmix-knuth
os=-mmixware
;;
monitor)
basic_machine=m68k-rom68k
os=-coff
;;
msdos)
basic_machine=i386-pc
os=-msdos
;;
mvs)
basic_machine=i370-ibm
os=-mvs
;;
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
;;
nsr-tandem)
basic_machine=nsr-tandem
;;
op50n-* | op60c-*)
basic_machine=hppa1.1-oki
os=-proelf
;;
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
;;
pbd)
basic_machine=sparc-tti
;;
pbb)
basic_machine=m68k-tti
;;
pc532 | pc532-*)
basic_machine=ns32k-pc532
;;
pentium | p5 | k5 | k6 | nexgen)
basic_machine=i586-pc
;;
pentiumpro | p6 | 6x86 | athlon)
basic_machine=i686-pc
;;
pentiumii | pentium2)
basic_machine=i686-pc
;;
pentium-* | p5-* | k5-* | k6-* | nexgen-*)
basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pentiumpro-* | p6-* | 6x86-* | athlon-*)
basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pentiumii-* | pentium2-*)
basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pn)
basic_machine=pn-gould
;;
power) basic_machine=power-ibm
;;
ppc) basic_machine=powerpc-unknown
;;
ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
ppcle | powerpclittle | ppc-le | powerpc-little)
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 | ppc64-le | powerpc64-little)
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
;;
rom68k)
basic_machine=m68k-rom68k
os=-coff
;;
rm[46]00)
basic_machine=mips-siemens
;;
rtpc | rtpc-*)
basic_machine=romp-ibm
;;
sa29200)
basic_machine=a29k-amd
os=-udi
;;
sequent)
basic_machine=i386-sequent
;;
sh)
basic_machine=sh-hitachi
os=-hms
;;
sparclite-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
;;
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=t3e-cray
os=-unicos
;;
tic54x | c54x*)
basic_machine=tic54x-unknown
os=-coff
;;
tx39)
basic_machine=mipstx39-unknown
;;
tx39el)
basic_machine=mipstx39el-unknown
;;
tower | tower-32)
basic_machine=m68k-ncr
;;
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
;;
windows32)
basic_machine=i386-pc
os=-windows32-msvcrt
;;
xmp)
basic_machine=xmp-cray
os=-unicos
;;
xps | xps100)
basic_machine=xps100-honeywell
;;
z8k-*-coff)
basic_machine=z8k-unknown
os=-sim
;;
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
;;
mips)
if [ x$os = x-linux-gnu ]; then
basic_machine=mips-unknown
else
basic_machine=mips-mips
fi
;;
romp)
basic_machine=romp-ibm
;;
rs6000)
basic_machine=rs6000-ibm
;;
vax)
basic_machine=vax-dec
;;
pdp10)
# there are many clones, so DEC is not a safe bet
basic_machine=pdp10-unknown
;;
pdp11)
basic_machine=pdp11-dec
;;
we32k)
basic_machine=we32k-att
;;
sh3 | sh4 | sh3eb | sh4eb)
basic_machine=sh-unknown
;;
sparc | sparcv9 | sparcv9b)
basic_machine=sparc-sun
;;
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
;;
c4x*)
basic_machine=c4x-none
os=-coff
;;
*-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.
-solaris1 | -solaris1.*)
os=`echo $os | sed -e 's|solaris1|sunos4|'`
;;
-solaris)
os=-solaris2
;;
-svr4*)
os=-sysv4
;;
-unixware*)
os=-sysv4.2uw
;;
-gnu/linux*)
os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
;;
# First 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* | -sunos | -sunos[34]*\
| -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
| -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
| -aos* \
| -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
| -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
| -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \
| -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
| -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
| -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
| -chorusos* | -chorusrdb* \
| -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
| -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \
| -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \
| -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
| -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
| -os2* | -vos*)
# Remember, each alternative MUST END IN *, to match a version number.
;;
-qnx*)
case $basic_machine in
x86-* | i*86-*)
;;
*)
os=-nto$os
;;
esac
;;
-nto*)
os=-nto-qnx
;;
-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
| -windows* | -osx | -abug | -netware* | -os9* | -beos* \
| -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
;;
-mac*)
os=`echo $os | sed -e 's|mac|macos|'`
;;
-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
;;
-wince*)
os=-wince
;;
-osfrose*)
os=-osfrose
;;
-osf*)
os=-osf
;;
-utek*)
os=-bsd
;;
-dynix*)
os=-bsd
;;
-acis*)
os=-aos
;;
-386bsd)
os=-bsd
;;
-ctix* | -uts*)
os=-sysv
;;
-ns2 )
os=-nextstep2
;;
-nsk*)
os=-nsk
;;
# Preserve the version number of sinix5.
-sinix5.*)
os=`echo $os | sed -e 's|sinix|sysv|'`
;;
-sinix*)
os=-sysv4
;;
-triton*)
os=-sysv3
;;
-oss*)
os=-sysv3
;;
-svr4)
os=-sysv4
;;
-svr3)
os=-sysv3
;;
-sysvr4)
os=-sysv4
;;
# This must come after -sysvr4.
-sysv*)
;;
-ose*)
os=-ose
;;
-es1800*)
os=-ose
;;
-xenix)
os=-xenix
;;
-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
os=-mint
;;
-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
*-acorn)
os=-riscix1.2
;;
arm*-rebel)
os=-linux
;;
arm*-semi)
os=-aout
;;
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
# This also exists in the configure program, but was not the
# default.
# os=-sunos4
;;
m68*-cisco)
os=-aout
;;
mips*-cisco)
os=-elf
;;
mips*-*)
os=-elf
;;
*-tti) # must be before sparc entry or we get the wrong os.
os=-sysv3
;;
sparc-* | *-sun)
os=-sunos4.1.1
;;
*-be)
os=-beos
;;
*-ibm)
os=-aix
;;
*-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
;;
*-next)
os=-nextstep3
;;
*-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
;;
-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
;;
-ptx*)
vendor=sequent
;;
-vxsim* | -vxworks*)
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 0
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "timestamp='"
# time-stamp-format: "%:y-%02m-%02d"
# time-stamp-end: "'"
# End:
clearsilver-0.10.5/configure.in 0000644 0012117 0011610 00000035150 10645501211 013334 0000000 0000000 dnl Process this file with autoconf to produce a configure script.
AC_INIT(cgi/cgi.c)
AC_CONFIG_HEADER(cs_config.h)
dnl Checks for programs.
AC_PROG_CC
AC_PROG_CPP
AC_PROG_LN_S
AC_CHECK_PROGS(AR, ar aal, ar)
AC_PROG_RANLIB
AC_PROG_MAKE_SET
AC_PROG_INSTALL
dnl Checks for Neotonic Paths
AC_MSG_CHECKING(for Neotonic Paths)
if test -d /neo/opt/include; then
AC_MSG_RESULT(found)
CPPFLAGS="$CPPFLAGS -I/neo/opt/include"
LDFLAGS="$LDFLAGS -L/neo/opt/lib"
else
AC_MSG_RESULT(not found)
fi
dnl Checks for header files.
AC_HEADER_DIRENT
AC_HEADER_STDC
AC_HEADER_SYS_WAIT
AC_CHECK_HEADERS(fcntl.h stdarg.h varargs.h limits.h strings.h sys/ioctl.h sys/time.h unistd.h features.h)
dnl Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST
AC_TYPE_MODE_T
AC_TYPE_OFF_T
AC_TYPE_PID_T
AC_TYPE_SIZE_T
AC_HEADER_TIME
AC_STRUCT_TM
AC_STRUCT_TIMEZONE
dnl Checks for library functions.
AC_TYPE_SIGNAL
AC_FUNC_STRFTIME
AC_FUNC_VPRINTF
AC_FUNC_WAIT3
AC_CHECK_FUNCS(gettimeofday mktime putenv strerror strspn strtod strtol strtoul)
AC_CHECK_FUNCS(random rand drand48)
dnl Checks for libraries.
EXTRA_UTL_OBJS=
EXTRA_UTL_SRC=
cs_cv_wdb=no
AC_ARG_ENABLE(apache, [ --disable-wdb Disables building of wdb],
[if test $enableval = no; then
AC_MSG_RESULT(Disabling wdb code)
else
AC_SEARCH_LIBS(db_open, db db2, [cs_cv_wdb=yes])
if test $cs_cv_wdb = yes; then
AC_DEFINE(HAVE_DB2)
EXTRA_UTL_SRC="$EXTRA_UTL_SRC wdb.c"
fi
fi])
dnl Check for locks
AC_CHECK_FUNC(lockf, [
AC_DEFINE(HAVE_LOCKF)
EXTRA_UTL_SRC="$EXTRA_UTL_SRC ulocks.c rcfs.c"
cs_cv_pthread=no
AC_CHECK_HEADER(pthread.h, [cs_cv_pthread=yes])
if test $cs_cv_pthread = yes; then
AC_DEFINE(HAVE_PTHREADS)
EXTRA_UTL_SRC="$EXTRA_UTL_SRC skiplist.c dict.c"
fi
])
AC_MINGW32()
if test "x$MINGW32" = "xyes"; then
CPPFLAGS="$CPPFLAGS -D__WINDOWS_GCC__"
USE_MINGW32="USE_MINGW32 = 1"
else
EXTRA_UTL_SRC="$EXTRA_UTL_SRC filter.c neo_net.c neo_server.c"
fi
dnl Check for snprintf and vsnprintf
cs_cv_snprintf=no
SNPRINTFOBJS=""
AC_CHECK_FUNC(snprintf, [AC_DEFINE(HAVE_SNPRINTF)], [cs_cv_snprintf=yes])
AC_CHECK_FUNC(vsnprintf, [AC_DEFINE(HAVE_VSNPRINTF)], [cs_cv_snprintf=yes])
if test $cs_cv_snprintf = yes; then
EXTRA_UTL_OBJS="$EXTRA_UTL_OBJS snprintf.o"
fi
dnl Check for missing re-entrant functions
cs_cv_missing=no
cs_cv_need_reentrant=no
dnl copied from libcurl
AC_CHECK_FUNCS(localtime_r, [
AC_MSG_CHECKING(whether localtime_r is declared)
AC_EGREP_CPP(localtime_r,[
#include ],[
AC_DEFINE(HAVE_LOCALTIME_R)
AC_MSG_RESULT(yes)],[
AC_MSG_RESULT(no)
AC_MSG_CHECKING(whether localtime_r with -D_REENTRANT is declared)
AC_EGREP_CPP(localtime_r,[
#define _REENTRANT
#include ],[
cs_cv_need_reentrant=yes
AC_MSG_RESULT(yes)],[
cs_cv_missing=yes
AC_MSG_RESULT(no)])])], [cs_cv_missing=yes])
AC_CHECK_FUNCS(gmtime_r, [
AC_MSG_CHECKING(whether gmtime_r is declared)
AC_EGREP_CPP(gmtime_r,[
#include ],[
AC_DEFINE(HAVE_GMTIME_R)
AC_MSG_RESULT(yes)],[
AC_MSG_RESULT(no)
AC_MSG_CHECKING(whether gmtime_r with -D_REENTRANT is declared)
AC_EGREP_CPP(gmtime_r,[
#define _REENTRANT
#include ],[
cs_cv_need_reentrant=yes
AC_MSG_RESULT(yes)],[
cs_cv_missing=yes
AC_MSG_RESULT(no)])])], [cs_cv_missing=yes])
AC_CHECK_FUNCS(strtok_r, [
AC_MSG_CHECKING(whether strtok_r is declared)
AC_EGREP_CPP(strtok_r,[
#include ],[
AC_DEFINE(HAVE_STRTOK_R)
AC_MSG_RESULT(yes)],[
AC_MSG_RESULT(no)
AC_MSG_CHECKING(whether strtok_r with -D_REENTRANT is declared)
AC_EGREP_CPP(strtok_r,[
#define _REENTRANT
#include ],[
cs_cv_need_reentrant=yes
AC_MSG_RESULT(yes)],[
cs_cv_missing=yes
AC_MSG_RESULT(no)])])], [cs_cv_missing=yes])
AC_CHECK_FUNC(mkstemp, [AC_DEFINE(HAVE_MKSTEMP)], [cs_cv_missing=yes])
if test $cs_cv_missing = yes; then
EXTRA_UTL_OBJS="$EXTRA_UTL_OBJS missing.o"
fi
if test $cs_cv_need_reentrant = yes; then
CPPFLAGS="$CPPFLAGS -D_REENTRANT"
fi
cs_cv_regex=yes
AC_CHECK_FUNC(regexec, [AC_DEFINE(HAVE_REGEX)], [cs_cv_regex=no])
if test $cs_cv_regex = no; then
CPPFLAGS="$CPPFLAGS -I\$(NEOTONIC_ROOT)/util/regex"
EXTRA_UTL_SRC="$EXTRA_UTL_SRC regex/regex.c"
fi
cs_cv_compression=yes
AC_CHECK_LIB(z, deflate, [cs_cv_compression=yes], [cs_cv_compression=no])
AC_ARG_ENABLE(compression, [ --disable-compression Disables HTML Compression support],
[if test $enableval = no; then
cs_cv_compression=no;
AC_MSG_RESULT(Disabling HTML Compression support)
fi])
if test $cs_cv_compression = yes; then
AC_DEFINE(HTML_COMPRESSION)
LIBS="$LIBS -lz"
fi
AC_ARG_ENABLE(remote-debugger, [ --enable-remote-debugger Enables remote X CGI debugging],
[if test $enableval = yes; then
AC_DEFINE(ENABLE_REMOTE_DEBUG)
AC_MSG_RESULT(Enabling CGI X Remote debugger)
fi])
dnl Check for Apache apxs
cs_cv_apache=yes
AC_ARG_ENABLE(apache, [ --disable-apache Disables building of apache 1.3.x module],
[if test $enableval = no; then
cs_cv_apache=no;
AC_MSG_RESULT(Disabling Apache 1.3.x Module)
fi])
AC_ARG_WITH(apache, [ --with-apache=path Set location of Apache installation], [cs_cv_apache_path="$withval"], [cs_cv_apache_path=])
if test $cs_cv_apache = yes; then
AC_MSG_CHECKING(for apache apxs)
apxs_path=no
apache_search_path="$cs_cv_apache_path /neo/opt /usr/local /usr"
for path in $apache_search_path; do
if test -x $path/httpd/bin/apxs; then
apxs_path=$path/httpd/bin/apxs
httpd_path=$path/httpd/bin/httpd
break
fi
if test -x $path/httpd/sbin/apxs; then
apxs_path=$path/httpd/sbin/apxs
httpd_path=$path/httpd/sbin/httpd
break
fi
if test -x $path/bin/apxs; then
apxs_path=$path/bin/apxs
httpd_path=$path/bin/httpd
break
fi
if test -x $path/sbin/apxs; then
apxs_path=$path/sbin/apxs
httpd_path=$path/sbin/httpd
break
fi
done
if test "x$apxs_path" = "xno"; then
AC_MSG_RESULT(not found)
else
AC_MSG_RESULT(found $apxs_path)
AC_MSG_CHECKING(for apache 1.3.x)
changequote(<<, >>)dnl
apache_version="`$httpd_path -v | grep 'Server version' | sed -e 's/.*Apache\/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/'`"
apache_major_version=`echo $apache_version | sed -e 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'`
apache_minor_version=`echo $apache_version | sed -e 's/.*\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'`
changequote([, ])dnl
if test "$apache_major_version" = "1" -a "$apache_minor_version" = "3"; then
AC_MSG_RESULT(found $apache_version)
APXS_PATH="$apxs_path"
BUILD_WRAPPERS="$BUILD_WRAPPERS mod_ecs"
else
AC_MSG_RESULT(found $apache_version - disabling module build)
fi
fi
fi
dnl Check for Python library/includes
cs_cv_python=yes
AC_ARG_ENABLE(python, [ --disable-python Disables building of python module],
[if test $enableval = no; then
cs_cv_python=no;
AC_MSG_RESULT(Disabling python module)
fi])
AC_ARG_WITH(python, [ --with-python=path Set location of Python Interpreter], [cs_cv_python_path="$withval"], [cs_cv_python_path=no])
if test $cs_cv_python = yes; then
AC_MSG_CHECKING(for python includes)
python_inc=no
python_lib=no
python_search_path="/neo/opt /usr/local /usr /c"
python_versions="2.4 2.3 2.2 2.1 2.0 1.5 24 23 22 21 20 15"
if test $cs_cv_python_path != "no" -a -x $cs_cv_python_path; then
python_bin=$cs_cv_python_path
vers=`$python_bin -c "import sys; print sys.version[[:3]]"`
py_inst_dir=`$python_bin -c "import sys; print sys.exec_prefix"`
python_inc=$py_inst_dir/include/python$vers
python_lib="-L$py_inst_dir/lib/python$vers/config -lpython$vers"
python_site=$py_inst_dir/lib/python$vers/site-packages
else
for vers in $python_versions; do
for path in $python_search_path; do
if test -x $path/bin/python$vers; then
python_bin=$path/bin/python$vers
major_vers=`echo $vers | cut -b 1`
if test $major_vers -ge 2; then
python_base=`$python_bin -c "import sys, os; print os.path.dirname([[x for x in sys.path if x.find('site-packages') != -1]][[0]])"`
else
python_base=`$python_bin -c "import site, os; print os.path.dirname(site.sitedirs[[0]])"`
fi
if test -d $python_base; then
python_lib="-L$python_base/config -lpython$vers"
python_site=$python_base/site-packages
fi
fi
if test -f $path/include/python$vers/Python.h; then
python_inc=$path/include/python$vers
fi
if test "x$python_lib" = "xno"; then
if test -d $path/lib/python$vers; then
python_lib="-L$path/lib/python$vers/config -lpython$vers"
python_site=$path/lib/python$vers/site-packages
fi
if test -d $path/lib64/python$vers; then
python_lib="-L$path/lib64/python$vers/config -lpython$vers"
python_site=$path/lib64/python$vers/site-packages
fi
fi
dnl This is currently special cased mostly for Windows
dnl installs, but we only use python_lib for windows anyways
if test -f $path/python$vers/include/Python.h; then
python_inc=$path/python$vers/include
python_lib="-L$path/python$vers/libs -lpython$vers"
python_site=$path/python$vers/Lib/site-packages
break 2
fi
if test "x$python_inc" != "xno" -a "x$python_lib" != "xno"; then
break 2
fi
done
done
fi
if test "x$python_inc" = "xno"; then
AC_MSG_RESULT(not found)
PYTHON=
PYTHON_INC=
PYTHON_LIB=
PYTHON_SITE=
else
AC_MSG_RESULT(found $python_inc)
PYTHON=$python_bin
PYTHON_INC="-I$python_inc"
PYTHON_LIB=$python_lib
if test "x$PYTHON_SITE" = "x"; then
PYTHON_SITE=$python_site
fi
BUILD_WRAPPERS="$BUILD_WRAPPERS python"
fi
fi
dnl Check for Perl binary
cs_cv_perl=yes
AC_ARG_ENABLE(perl, [ --disable-perl Disables building of perl module],
[if test $enableval = no; then
cs_cv_perl=no;
AC_MSG_RESULT(Disabling perl module)
fi])
AC_ARG_WITH(perl, [ --with-perl=path Set location of Perl binary], [cs_cv_perl_path="$withval"], [cs_cv_perl_path=no])
if test $cs_cv_perl = yes; then
AC_MSG_CHECKING(for perl >= 5.006)
perl_path=no
perl_search_path="/neo/opt /usr/local /usr"
if test $cs_cv_perl_path != "no" -a -x $cs_cv_perl_path; then
perl_path=$cs_cv_perl_path
else
for path in $perl_search_path; do
if test -x $path/bin/perl; then
require_error=`$path/bin/perl -e 'require 5.006' 2>&1`
if test "x$require_error" = "x"; then
perl_path=$path/bin/perl
break
fi
fi
done
fi
if test "x$perl_path" = "xno"; then
AC_MSG_RESULT(not found)
PERL=
else
AC_MSG_RESULT(found $perl_path)
PERL="$perl_path"
BUILD_WRAPPERS="$BUILD_WRAPPERS perl"
fi
fi
dnl Check for Ruby binary
cs_cv_ruby=yes
AC_ARG_ENABLE(ruby, [ --disable-ruby Disables building of ruby module],
[if test $enableval = no; then
cs_cv_ruby=no;
AC_MSG_RESULT(Disabling ruby module)
fi])
AC_ARG_WITH(ruby, [ --with-ruby=path Set location of Ruby binary], [cs_cv_ruby_path="$withval"], [cs_cv_ruby_path=no])
if test $cs_cv_ruby = yes; then
AC_MSG_CHECKING(for ruby)
ruby_path=no
ruby_search_path="/neo/opt /usr/local /usr"
if test $cs_cv_ruby_path != "no" -a -x $cs_cv_ruby_path; then
ruby_path=$cs_cv_ruby_path
else
for path in $ruby_search_path; do
if test -x $path/bin/ruby; then
ruby_path=$path/bin/ruby
break
fi
done
fi
if test "x$ruby_path" = "xno"; then
AC_MSG_RESULT(not found)
RUBY=
else
AC_MSG_RESULT(found $ruby_path)
RUBY="$ruby_path"
BUILD_WRAPPERS="$BUILD_WRAPPERS ruby"
fi
fi
dnl Check for Java library/includes
cs_cv_java=yes
AC_ARG_ENABLE(java, [ --disable-java Disables building of java module],
[if test $enableval = no; then
cs_cv_java=no;
AC_MSG_RESULT(Disabling java module)
fi])
AC_ARG_WITH(java, [ --with-java=path Set location of J2SDK], [cs_cv_java_path="$withval"], [cs_cv_java_path=no])
if test $cs_cv_java = yes; then
AC_MSG_CHECKING(for j2sdk path)
java_path=no
if test $cs_cv_java_path != "no" -a -d $cs_cv_java_path; then
java_path=$cs_cv_java_path
else
java_search_path="/neo/opt /usr/local /usr /usr/lib"
for path in $java_search_path; do
if test -d $path/java/j2sdk; then
java_path=$path/java/j2sdk
break
fi
if test -d $path/j2sdk; then
java_path=$path/j2sdk
break
fi
possible="$path/java/j2sdk*"
for pos_path in $possible; do
if test -d $pos_path; then
java_path=$pos_path
break 2
fi
done
possible="$path/j2sdk*"
for pos_path in $possible; do
if test -d $pos_path; then
java_path=$pos_path
break 2
fi
done
done
fi
if test "x$java_path" = "xno"; then
AC_MSG_RESULT(not found)
JAVA_PATH=
JAVA_INCLUDE_PATH=
else
AC_MSG_RESULT(found $java_path)
JAVA_PATH="$java_path"
JAVAC="$java_path/bin/javac"
_ACJNI_JAVAC=$JAVAC
AC_JNI_INCLUDE_DIR
for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS
do
JAVA_INCLUDE_PATH="$JAVA_INCLUDE_PATH -I$JNI_INCLUDE_DIR"
done
BUILD_WRAPPERS="$BUILD_WRAPPERS java-jni"
fi
fi
dnl Check for C# library/includes
cs_cv_csharp=yes
AC_ARG_ENABLE(csharp, [ --disable-csharp Disables building of csharp module],
[if test $enableval = no; then
cs_cv_csharp=no;
AC_MSG_RESULT(Disabling csharp module)
fi])
AC_ARG_WITH(csharp, [ --with-csharp=path Set location of csharp], [cs_cv_csharp_path="$withval"], [cs_cv_csharp_path=no])
if test $cs_cv_csharp = yes; then
AC_MSG_CHECKING(for csharp path)
csharp_path=no
if test $cs_cv_csharp_path != "no" -a -d $cs_cv_csharp_path; then
csharp_path=$cs_cv_csharp_path
else
csharp_search_path="/neo/opt /usr/local /usr"
for path in $csharp_search_path; do
if test -f $path/bin/mcs; then
csharp_path=$path
break
fi
done
fi
if test "x$csharp_path" = "xno"; then
AC_MSG_RESULT(not found)
CSHARP_PATH=
else
AC_MSG_RESULT(found $csharp_path/bin/mcs)
CSHARP_PATH="$csharp_path"
BUILD_WRAPPERS="$BUILD_WRAPPERS dso csharp"
fi
fi
AC_ARG_ENABLE(gettext, [ --enable-gettext Enables gettext message translation],
[if test $enableval = yes; then
dnl Check for gettext
AC_CHECK_FUNC(gettext, [
cs_cv_libintl=no
AC_CHECK_HEADER(libintl.h, [cs_cv_libintl=yes])
if test $cs_cv_libintl = yes; then
AC_DEFINE(ENABLE_GETTEXT)
AC_MSG_RESULT(Enabling gettext message translation)
else
AC_MSG_RESULT(not found)
fi
])
fi])
AC_SUBST(RANLIB)
AC_SUBST(AR)
AC_SUBST(USE_MINGW32)
AC_SUBST(APXS_PATH)
AC_SUBST(PERL)
AC_SUBST(RUBY)
AC_SUBST(BUILD_WRAPPERS)
AC_SUBST(JAVA_PATH)
AC_SUBST(JAVA_INCLUDE_PATH)
AC_SUBST(PYTHON)
AC_SUBST(PYTHON_INC)
AC_SUBST(PYTHON_LIB)
AC_SUBST(PYTHON_SITE)
AC_SUBST(EXTRA_UTL_SRC)
AC_SUBST(EXTRA_UTL_OBJS)
AC_SUBST(CSHARP_PATH)
AC_OUTPUT(rules.mk)
clearsilver-0.10.5/cs_config.h.in 0000644 0012117 0011610 00000014015 10540411115 013525 0000000 0000000 /* cs_config.h.in. Generated from configure.in by autoheader. */
/*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
/*
* config file
*/
#ifndef __CS_CONFIG_H_
#define __CS_CONFIG_H_ 1
/* Enable support for HTML Compression (still must be enabled at run time) */
#undef HTML_COMPRESSION
/* Enable support for X Remote CGI Debugging */
#undef ENABLE_REMOTE_DEBUG
/********* SYSTEM CONFIG ***************************************************/
/* autoconf/configure should figure all of these out for you */
/* Does your system have the snprintf() call? */
#undef HAVE_SNPRINTF
/* Does your system have the vsnprintf() call? */
#undef HAVE_VSNPRINTF
/* Does your system have the strtok_r() call? */
#undef HAVE_STRTOK_R
/* Does your system have the localtime_r() call? */
#undef HAVE_LOCALTIME_R
/* Does your system have the gmtime_r() call? */
#undef HAVE_GMTIME_R
/* Does your system have the mkstemp() call? */
#undef HAVE_MKSTEMP
/* Does your system have regex.h */
#undef HAVE_REGEX
/* Does your system have pthreads? */
#undef HAVE_PTHREADS
/* Does your system have lockf ? */
#undef HAVE_LOCKF
/* Does your system have Berkeley DB v2 ? */
#undef HAVE_DB2
/* Enable support for gettext message translation */
#undef ENABLE_GETTEXT
/* Define to 1 if you have the header file, and it defines `DIR'.
*/
#undef HAVE_DIRENT_H
/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
#undef HAVE_DOPRNT
/* Define to 1 if you have the `drand48' function. */
#undef HAVE_DRAND48
/* Define to 1 if you have the header file. */
#undef HAVE_FCNTL_H
/* Define to 1 if you have the header file. */
#undef HAVE_FEATURES_H
/* Define to 1 if you have the `gettimeofday' function. */
#undef HAVE_GETTIMEOFDAY
/* Define to 1 if you have the `gmtime_r' function. */
#undef HAVE_GMTIME_R
/* Define to 1 if you have the header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the header file. */
#undef HAVE_LIMITS_H
/* Define to 1 if you have the `localtime_r' function. */
#undef HAVE_LOCALTIME_R
/* Define to 1 if you have the header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the `mktime' function. */
#undef HAVE_MKTIME
/* Define to 1 if you have the header file, and it defines `DIR'. */
#undef HAVE_NDIR_H
/* Define to 1 if you have the `putenv' function. */
#undef HAVE_PUTENV
/* Define to 1 if you have the `rand' function. */
#undef HAVE_RAND
/* Define to 1 if you have the `random' function. */
#undef HAVE_RANDOM
/* Define to 1 if you have the header file. */
#undef HAVE_STDARG_H
/* Define to 1 if you have the header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the `strerror' function. */
#undef HAVE_STRERROR
/* Define to 1 if you have the `strftime' function. */
#undef HAVE_STRFTIME
/* Define to 1 if you have the header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the `strspn' function. */
#undef HAVE_STRSPN
/* Define to 1 if you have the `strtod' function. */
#undef HAVE_STRTOD
/* Define to 1 if you have the `strtok_r' function. */
#undef HAVE_STRTOK_R
/* Define to 1 if you have the `strtol' function. */
#undef HAVE_STRTOL
/* Define to 1 if you have the `strtoul' function. */
#undef HAVE_STRTOUL
/* Define to 1 if `tm_zone' is member of `struct tm'. */
#undef HAVE_STRUCT_TM_TM_ZONE
/* Define to 1 if you have the header file, and it defines `DIR'.
*/
#undef HAVE_SYS_DIR_H
/* Define to 1 if you have the header file. */
#undef HAVE_SYS_IOCTL_H
/* Define to 1 if you have the header file, and it defines `DIR'.
*/
#undef HAVE_SYS_NDIR_H
/* Define to 1 if you have the header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the header file. */
#undef HAVE_SYS_TIME_H
/* Define to 1 if you have the header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have that is POSIX.1 compatible. */
#undef HAVE_SYS_WAIT_H
/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use
`HAVE_STRUCT_TM_TM_ZONE' instead. */
#undef HAVE_TM_ZONE
/* Define to 1 if you don't have `tm_zone' but do have the external array
`tzname'. */
#undef HAVE_TZNAME
/* Define to 1 if you have the header file. */
#undef HAVE_UNISTD_H
/* Define to 1 if you have the header file. */
#undef HAVE_VARARGS_H
/* Define to 1 if you have the `vprintf' function. */
#undef HAVE_VPRINTF
/* Define to 1 if you have the `wait3' system call. Deprecated, you should no
longer depend upon `wait3'. */
#undef HAVE_WAIT3
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* Define as the return type of signal handlers (`int' or `void'). */
#undef RETSIGTYPE
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Define to 1 if you can safely include both and . */
#undef TIME_WITH_SYS_TIME
/* Define to 1 if your declares `struct tm'. */
#undef TM_IN_SYS_TIME
/* Define to empty if `const' does not conform to ANSI C. */
#undef const
/* Define to `int' if does not define. */
#undef mode_t
/* Define to `long' if does not define. */
#undef off_t
/* Define to `int' if does not define. */
#undef pid_t
/* Define to `unsigned' if does not define. */
#undef size_t
#endif /* __CS_CONFIG_H_ */
clearsilver-0.10.5/mkinstalldirs 0000755 0012117 0011610 00000001330 10261037512 013624 0000000 0000000 #! /bin/sh
# mkinstalldirs --- make directory hierarchy
# Author: Noah Friedman
# Created: 1993-05-16
# Public domain
# $Id: mkinstalldirs,v 1.1 2003/04/02 23:07:26 blong Exp $
errstatus=0
for file
do
set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'`
shift
pathcomp=
for d
do
pathcomp="$pathcomp$d"
case "$pathcomp" in
-* ) pathcomp=./$pathcomp ;;
esac
if test ! -d "$pathcomp"; then
echo "mkdir $pathcomp" 1>&2
mkdir "$pathcomp" || lasterr=$?
if test ! -d "$pathcomp"; then
errstatus=$lasterr
fi
fi
pathcomp="$pathcomp/"
done
done
exit $errstatus
# mkinstalldirs ends here
clearsilver-0.10.5/install-sh 0000755 0012117 0011610 00000011244 10261037512 013027 0000000 0000000 #! /bin/sh
#
# install - install a program, script, or datafile
# This comes from X11R5.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch.
#
# set DOITPROG to echo to test this script
# Don't use :- since 4.3BSD and earlier shells don't like it.
doit="${DOITPROG-}"
# put in absolute paths if you don't have them in your path; or use env. vars.
mvprog="${MVPROG-mv}"
cpprog="${CPPROG-cp}"
chmodprog="${CHMODPROG-chmod}"
chownprog="${CHOWNPROG-chown}"
chgrpprog="${CHGRPPROG-chgrp}"
stripprog="${STRIPPROG-strip}"
rmprog="${RMPROG-rm}"
mkdirprog="${MKDIRPROG-mkdir}"
tranformbasename=""
transform_arg=""
instcmd="$mvprog"
chmodcmd="$chmodprog 0755"
chowncmd=""
chgrpcmd=""
stripcmd=""
rmcmd="$rmprog -f"
mvcmd="$mvprog"
src=""
dst=""
dir_arg=""
while [ x"$1" != x ]; do
case $1 in
-c) instcmd="$cpprog"
shift
continue;;
-d) dir_arg=true
shift
continue;;
-m) chmodcmd="$chmodprog $2"
shift
shift
continue;;
-o) chowncmd="$chownprog $2"
shift
shift
continue;;
-g) chgrpcmd="$chgrpprog $2"
shift
shift
continue;;
-s) stripcmd="$stripprog"
shift
continue;;
-t=*) transformarg=`echo $1 | sed 's/-t=//'`
shift
continue;;
-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
shift
continue;;
*) if [ x"$src" = x ]
then
src=$1
else
# this colon is to work around a 386BSD /bin/sh bug
:
dst=$1
fi
shift
continue;;
esac
done
if [ x"$src" = x ]
then
echo "install: no input file specified"
exit 1
else
true
fi
if [ x"$dir_arg" != x ]; then
dst=$src
src=""
if [ -d $dst ]; then
instcmd=:
else
instcmd=mkdir
fi
else
# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if [ -f $src -o -d $src ]
then
true
else
echo "install: $src does not exist"
exit 1
fi
if [ x"$dst" = x ]
then
echo "install: no destination specified"
exit 1
else
true
fi
# If destination is a directory, append the input filename; if your system
# does not like double slashes in filenames, you may need to add some logic
if [ -d $dst ]
then
dst="$dst"/`basename $src`
else
true
fi
fi
## this sed command emulates the dirname command
dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
# Make sure that the destination directory exists.
# this part is taken from Noah Friedman's mkinstalldirs script
# Skip lots of stat calls in the usual case.
if [ ! -d "$dstdir" ]; then
defaultIFS='
'
IFS="${IFS-${defaultIFS}}"
oIFS="${IFS}"
# Some sh's can't handle IFS=/ for some reason.
IFS='%'
set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
IFS="${oIFS}"
pathcomp=''
while [ $# -ne 0 ] ; do
pathcomp="${pathcomp}${1}"
shift
if [ ! -d "${pathcomp}" ] ;
then
$mkdirprog "${pathcomp}"
else
true
fi
pathcomp="${pathcomp}/"
done
fi
if [ x"$dir_arg" != x ]
then
$doit $instcmd $dst &&
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
else
# If we're going to rename the final executable, determine the name now.
if [ x"$transformarg" = x ]
then
dstfile=`basename $dst`
else
dstfile=`basename $dst $transformbasename |
sed $transformarg`$transformbasename
fi
# don't allow the sed command to completely eliminate the filename
if [ x"$dstfile" = x ]
then
dstfile=`basename $dst`
else
true
fi
# Make a temp file name in the proper directory.
dsttmp=$dstdir/#inst.$$#
# Move or copy the file name to the temp name
$doit $instcmd $src $dsttmp &&
trap "rm -f ${dsttmp}" 0 &&
# and set any options; do chmod last to preserve setuid bits
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $instcmd $src $dsttmp" command.
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
# Now rename the file to the real destination.
$doit $rmcmd -f $dstdir/$dstfile &&
$doit $mvcmd $dsttmp $dstdir/$dstfile
fi &&
exit 0
clearsilver-0.10.5/ClearSilver.h 0000644 0012117 0011610 00000003353 10261037503 013411 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __CLEARSILVER_H_
#define __CLEARSILVER_H_ 1
#include "cs_config.h"
/* If you need these backward compatible definitions, define CS_COMPAT */
/* These changed after v0.9.1 */
#define CS_COMPAT 0
#if defined(CS_COMPAT) || !defined(HASH)
#define HASH NE_HASH
#define HASHNODE NE_HASHNODE
#define hash_init ne_hash_init
#define hash_destroy ne_hash_destroy
#define hash_lookup ne_hash_lookup
#define hash_has_key ne_hash_has_key
#define hash_remove ne_hash_remove
#define hash_next ne_hash_next
#define hash_str_comp ne_hash_str_comp
#define hash_str_hash ne_hash_str_hash
#endif /* CS_COMPAT */
#include
#include
/* Base libraries */
#include "util/neo_misc.h"
#include "util/neo_err.h"
#include "util/neo_date.h"
#include "util/neo_files.h"
#include "util/neo_hash.h"
#include "util/neo_hdf.h"
#include "util/neo_rand.h"
#include "util/neo_net.h"
#include "util/neo_server.h"
#include "util/neo_str.h"
#include "util/ulist.h"
#include "util/wildmat.h"
#include "util/filter.h"
#ifdef HAVE_LOCKF
# include "util/ulocks.h"
# include "util/rcfs.h"
/* These are dependent on the pthread locking code in ulocks */
# ifdef HAVE_PTHREADS
# include "util/skiplist.h"
# include "util/dict.h"
# endif
#endif
/* This is dependent on Berkeley DB v2 */
#ifdef HAVE_DB2
# include "util/wdb.h"
#endif
/* The ClearSilver Template language */
#include "cs/cs.h"
/* The ClearSilver CGI connector */
#include "cgi/cgi.h"
#include "cgi/cgiwrap.h"
#include "cgi/date.h"
#include "cgi/html.h"
#endif /* __CLEARSILVER_H_ */
clearsilver-0.10.5/util/ 0000755 0012117 0011610 00000000000 10645505044 012064 5 0000000 0000000 clearsilver-0.10.5/util/Makefile 0000644 0012117 0011610 00000001264 10344021620 013434 0000000 0000000
ifeq ($(NEOTONIC_ROOT),)
NEOTONIC_ROOT = ..
endif
include $(NEOTONIC_ROOT)/rules.mk
UTL_LIB = $(LIB_DIR)libneo_utl.a
UTL_SRC = neo_err.c neo_files.c neo_misc.c neo_rand.c ulist.c neo_hdf.c \
neo_str.c neo_date.c wildmat.c neo_hash.c $(EXTRA_UTL_SRC)
UTL_OBJ = $(UTL_SRC:%.c=%.o) $(EXTRA_UTL_OBJS)
UTL_HDR = $(UTL_SRC:%.c=%.h)
TARGETS = $(UTL_LIB)
all: $(TARGETS)
$(UTL_LIB): $(UTL_OBJ)
$(AR) $@ $(UTL_OBJ)
$(RANLIB) $@
install: all
$(NEOTONIC_ROOT)/mkinstalldirs $(DESTDIR)$(cs_includedir)/util
$(INSTALL) -m 644 $(UTL_HDR) $(DESTDIR)$(cs_includedir)/util
$(INSTALL) -m 644 $(UTL_LIB) $(DESTDIR)$(libdir)
clean:
$(RM) *.o
distclean:
$(RM) Makefile.depends $(TARGETS) *.o
clearsilver-0.10.5/util/dict.c 0000644 0012117 0011610 00000031666 10261111332 013072 0000000 0000000 /*
*
* Thread-safe Dictionary Using String Identifiers
* Copyright 1998-2000 Scott Shambarger (scott@shambarger.net)
*
* This software is open source. Permission to use, copy, modify, and
* distribute this software for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies. No
* warranty of any kind is expressed or implied. Use at your own risk.
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "dict.h"
#include "skiplist.h"
#include "ulocks.h"
typedef struct dictValue {
void *value; /* value to set/update */
dictNewValueCB new; /* new value callback (value is NULL) */
dictUpdateValueCB update; /* update value callback (value is NULL) */
void *rock; /* rock to pass to callbacks */
} *dictValuePtr;
typedef struct dictItem {
struct dictItem *next; /* pointer to next value */
char *id; /* string id */
void *value; /* value */
} *dictItemPtr;
typedef struct dictEntry {
dictItemPtr first; /* first item in entry */
BOOL deleted; /* TRUE if entry has been passed to skipDelete */
} *dictEntryPtr;
typedef UINT32 (*dictHashFunc)(const char *str);
typedef int (*dictCompFunc)(const char *s1, const char *s2);
struct _dictCtx {
pthread_mutex_t mList; /* list update mutex */
skipList list; /* skip list */
dictHashFunc hash; /* hash function */
dictCompFunc comp; /* id compare function */
BOOL useCase;
BOOL threaded; /* TRUE if threaded */
dictFreeValueFunc freeValue; /* free value callback */
void *freeRock; /* context for freeValue */
};
#undef DO_DEBUG
#ifdef DO_DEBUG
#include
#define DICT_LOCK(dict) \
do { if((dict)->threaded) { sched_yield(); \
mLock(&(dict)->mList); } } while(0)
#define DICT_HASH_BITS 16
#else
#define DICT_LOCK(dict) \
if((dict)->threaded) mLock(&(dict)->mList)
#define DICT_HASH_BITS 65536
#endif
#define DICT_UNLOCK(dict) \
if((dict)->threaded) mUnlock(&(dict)->mList)
/* entry is locked, so item may be added */
static NEOERR *dictNewItem(dictCtx dict, dictEntryPtr entry,
const char *id, dictValuePtr newval, dictItemPtr *item)
{
dictItemPtr my_item;
if (item != NULL)
*item = NULL;
/* check if we can set a new value */
if(! (newval->value || newval->new))
return nerr_raise(NERR_ASSERT, "value or new are NULL");
if(! (my_item = calloc(1, sizeof(struct dictItem))))
return nerr_raise(NERR_NOMEM, "Unable to allocate new dictItem");
if(! (my_item->id = strdup(id))) {
free(my_item);
return nerr_raise(NERR_NOMEM, "Unable to allocate new id for dictItem");
}
/* set new value */
if(newval->value) {
my_item->value = newval->value;
}
else {
NEOERR *err = STATUS_OK;
err = newval->new(id, newval->rock, &(my_item->value));
if (err != STATUS_OK)
{
/* new item callback failed, cleanup */
free(my_item->id);
free(my_item);
return nerr_pass(err);
}
}
my_item->next = entry->first;
entry->first = my_item;
if (item != NULL)
*item = my_item;
return STATUS_OK;
}
static void dictFreeItem(dictCtx dict, dictItemPtr item) {
if(dict->freeValue)
dict->freeValue(item->value, dict->freeRock);
free(item->id);
free(item);
return;
}
/* list locked, so safe to walk entry */
static dictItemPtr dictFindItem(dictCtx dict, dictEntryPtr entry,
const char *id, BOOL unlink) {
dictItemPtr *prev, item;
prev = &entry->first;
for(item = entry->first; item; item = item->next) {
if(! dict->comp(item->id, id)) {
if(unlink)
*prev = item->next;
return item;
}
prev = &item->next;
}
return NULL;
}
static NEOERR *dictUpdate(dictCtx dict, dictEntryPtr entry, const char *id,
dictValuePtr newval, void *lock) {
NEOERR *err = STATUS_OK;
dictItemPtr item = NULL;
void *newValue;
/* check for entry (maybe not found...) */
if(! entry)
return nerr_raise(NERR_NOT_FOUND, "Entry is NULL");
/* only use entry if not deleted */
if(! entry->deleted) {
/* find item */
if((item = dictFindItem(dict, entry, id, FALSE))) {
if(newval->value) {
if(dict->freeValue)
dict->freeValue(item->value, dict->freeRock);
item->value = newval->value;
}
else if(newval->update) {
/* track error (if update fails) */
err = newval->update(id, item->value, newval->rock);
}
else if((err = newval->new(id, newval->rock, &newValue)) == STATUS_OK) {
if(dict->freeValue)
dict->freeValue(item->value, dict->freeRock);
item->value = newValue;
}
else {
/* new item failed (don't remove old), indicate that update failed */
item = NULL;
}
}
else {
/* add new item to entry */
err = dictNewItem(dict, entry, id, newval, &item);
}
}
/* release entry lock */
skipRelease(dict->list, lock);
return nerr_pass(err);
}
static NEOERR *dictInsert(dictCtx dict, UINT32 hash, const char *id,
dictValuePtr newval) {
dictEntryPtr entry;
void *lock;
NEOERR *err = STATUS_OK;
/* create new item and insert entry */
entry = calloc(1, sizeof(struct dictEntry));
if (entry == NULL)
return nerr_raise(NERR_NOMEM, "Unable to allocate memory for dictEntry");
/* create/insert item (or cleanup) */
err = dictNewItem(dict, entry, id, newval, NULL);
if (err != STATUS_OK) return nerr_pass(err);
/* if we insert, we're done */
if((err = skipInsert(dict->list, hash, entry, FALSE)) == STATUS_OK)
return STATUS_OK;
/* failed to insert, cleanup */
if(dict->freeValue && ! newval->value)
dict->freeValue(entry->first->value, dict->freeRock);
free(entry->first->id);
free(entry->first);
free(entry);
/* check err */
if (!nerr_handle(&err, NERR_DUPLICATE))
return nerr_pass(err);
/* cool, someone already inserted the entry before we got the lock */
entry = skipSearch(dict->list, hash, &lock);
/* update entry as normal (handles entry not found) */
return nerr_pass(dictUpdate(dict, entry, id, newval, lock));
}
static UINT32 dictHash(dictCtx dict, const char *id) {
UINT32 hash;
hash = dict->hash(id) % DICT_HASH_BITS;
/* ensure hash is valid for skiplist (modify consistently if not) */
if(! (hash && (hash != (UINT32)-1)))
hash = 1;
return hash;
}
static NEOERR *dictModify(dictCtx dict, const char *id, dictValuePtr newval)
{
NEOERR *err;
UINT32 hash;
dictEntryPtr entry;
void *lock = NULL;
hash = dictHash(dict, id);
/* find entry in list */
entry = skipSearch(dict->list, hash, &lock);
DICT_LOCK(dict);
if((err = dictUpdate(dict, entry, id, newval, lock)) != STATUS_OK)
{
/* insert new entry */
nerr_ignore(&err);
err = dictInsert(dict, hash, id, newval);
}
DICT_UNLOCK(dict);
return nerr_pass(err);
}
NEOERR *dictSetValue(dictCtx dict, const char *id, void *value) {
struct dictValue newval;
assert(value);
newval.value = value;
return dictModify(dict, id, &newval);
}
NEOERR *dictModifyValue(dictCtx dict, const char *id, dictNewValueCB new,
dictUpdateValueCB update, void *rock) {
struct dictValue newval;
if(! (new || update))
return FALSE;
newval.value = NULL;
newval.new = new;
newval.update = update;
newval.rock = rock;
return dictModify(dict, id, &newval);
}
void dictReleaseLock(dictCtx dict, void *lock) {
/* release entry */
DICT_UNLOCK(dict);
/* release skip entry */
skipRelease(dict->list, lock);
return;
}
void dictCleanup(dictCtx dict, dictCleanupFunc cleanup, void *rock) {
dictItemPtr *prev, item, next;
dictEntryPtr entry;
UINT32 key = 0;
void *lock;
while((entry = skipNext(dict->list, &key, &lock))) {
DICT_LOCK(dict);
prev = &entry->first;
for(item = entry->first; item; item = next) {
next = item->next;
if(cleanup(item->id, item->value, rock)) {
/* remove item */
*prev = item->next;
dictFreeItem(dict, item);
}
else {
/* update reference pointer */
prev = &item->next;
}
}
/* delete entry if last item removed */
if(! entry->first) {
entry->deleted = TRUE;
skipDelete(dict->list, key);
}
dictReleaseLock(dict, lock);
}
return;
}
void *dictSearch(dictCtx dict, const char *id, void **plock) {
dictEntryPtr entry;
dictItemPtr item;
UINT32 hash;
void *lock;
void *value;
hash = dictHash(dict, id);
/* find entry in list */
if(! (entry = skipSearch(dict->list, hash, &lock)))
return NULL;
/* lock entry */
DICT_LOCK(dict);
/* find item */
if((item = dictFindItem(dict, entry, id, FALSE))) {
value = item->value;
if(plock)
*plock = lock;
else
dictReleaseLock(dict, lock);
return value;
}
dictReleaseLock(dict, lock);
return NULL;
}
void *dictNext (dictCtx dict, char **id, void **plock)
{
dictEntryPtr entry;
dictItemPtr item;
UINT32 hash;
void *lock;
void *value;
/* Handle the first one special case */
if (*id == NULL)
{
hash = 0;
/* find entry in list */
if(! (entry = skipNext (dict->list, &hash, &lock)))
return NULL;
/* lock entry */
DICT_LOCK(dict);
/* Take first item in list */
item = entry->first;
if (item != NULL)
{
value = item->value;
*id = item->id;
if(plock)
*plock = lock;
else
dictReleaseLock(dict, lock);
return value;
}
dictReleaseLock(dict, lock);
return NULL;
}
else
{
hash = dictHash(dict, *id);
/* find entry in list */
entry = skipSearch (dict->list, hash, &lock);
if (entry == NULL)
{
entry = skipNext (dict->list, &hash, &lock);
/* Not found, we're at the end of the dict */
if (entry == NULL)
return NULL;
}
/* lock entry */
DICT_LOCK(dict);
item = dictFindItem(dict, entry, *id, FALSE);
if (item != NULL)
{
if (item->next != NULL)
{
item = item->next;
}
else
{
/* we have to move to the next skip entry */
entry = skipNext (dict->list, &hash, &lock);
/* Not found, we're at the end of the dict */
item = entry?entry->first:NULL;
if(! item) {
dictReleaseLock(dict, lock);
return NULL;
}
}
value = item->value;
*id = item->id;
if(plock)
*plock = lock;
else
dictReleaseLock(dict, lock);
return value;
}
dictReleaseLock(dict, lock);
}
return NULL;
}
BOOL dictRemove(dictCtx dict, const char *id) {
dictEntryPtr entry;
dictItemPtr item;
UINT32 hash;
void *lock;
hash = dictHash(dict, id);
/* find entry in list */
if(! (entry = skipSearch(dict->list, hash, &lock)))
return FALSE;
/* lock entry */
DICT_LOCK(dict);
/* find/unlink/free item */
if((item = dictFindItem(dict, entry, id, TRUE)))
dictFreeItem(dict, item);
dictReleaseLock(dict, lock);
return item ? TRUE : FALSE;
}
/* called by skipList when safe to destroy entry */
static void dictDestroyEntry(void *value, void *ctx) {
dictItemPtr item, next;
dictEntryPtr entry;
entry = value;
for(item = entry->first; item; item = next) {
next = item->next;
dictFreeItem(ctx, item);
item = next;
}
free(value);
return;
}
NEOERR *dictCreate(dictCtx *rdict, BOOL threaded, UINT32 root, UINT32 maxLevel,
UINT32 flushLimit, BOOL useCase, dictFreeValueFunc freeValue, void *freeRock)
{
NEOERR *err;
dictCtx dict;
*rdict = NULL;
do {
if(! (dict = calloc(1, sizeof(struct _dictCtx))))
return nerr_raise (NERR_NOMEM, "Unable to allocate memory for dictCtx");
dict->useCase = useCase;
dict->hash = python_string_hash;
if(useCase) {
dict->comp = strcmp;
}
else {
/* dict->hash = uhashUpper; */
dict->comp = strcasecmp;
}
dict->threaded = threaded;
dict->freeValue = freeValue;
dict->freeRock = freeRock;
err = skipNewList(&(dict->list), threaded, root, maxLevel,
flushLimit, dictDestroyEntry, dict);
if (err != STATUS_OK) break;
if (threaded)
{
err = mCreate(&(dict->mList));
if (err != STATUS_OK) break;
}
*rdict = dict;
return STATUS_OK;
} while(FALSE);
dictDestroy(dict);
return nerr_pass(err);
}
void dictDestroy(dictCtx dict) {
if(! dict)
return;
skipFreeList(dict->list);
mDestroy(&dict->mList);
free(dict);
return;
}
clearsilver-0.10.5/util/dict.h 0000644 0012117 0011610 00000015264 10261111216 013074 0000000 0000000 /*
*
* Thread-safe Dictionary Using String Identifiers
* Copyright 1998-2000 Scott Shambarger (scott@shambarger.net)
*
* This software is open source. Permission to use, copy, modify, and
* distribute this software for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies. No
* warranty of any kind is expressed or implied. Use at your own risk.
*
*/
#ifndef __DICT_H_
#define __DICT_H_
__BEGIN_DECLS
typedef struct _dictCtx *dictCtx;
typedef BOOL (*dictCleanupFunc)(char *id, void *value, void *rock);
typedef void (*dictFreeValueFunc)(void *value, void *rock);
NEOERR *dictCreate(dictCtx *dict, BOOL threaded, UINT32 root, UINT32 maxLevel,
UINT32 flushLimit, BOOL useCase,
dictFreeValueFunc freeValue, void *freeRock);
/*
* Function: dictCreate - create new dictionary.
* Description: Returns a dictionary. If is true, list is
* multi-thread safe. , , and
* act as for skipNewList() (see skiplist.h)
* Input: threaded - true if list should be thread-safe.
* root - performance parameter (see above).
* maxLevel - performance parameter (see above).
* flushLimit - max deleted items to keep cached before
* forcing a flush.
* useCase - true to be case sensitive in identifiers
* freeValue - callback when freeing a value
* freeRock - context for freeValue callback
* Output: None.
* Return: New dictionary, NULL on error.
* MT-Level: Safe.
*/
void dictDestroy(dictCtx dict);
/*
* Function: dictDestroy - destroy dictionary.
* Description: Release all resources used by .
* Input: dict - dictionary to destroy
* Output: None.
* Return: None.
* MT-Level: Safe for unique .
*/
BOOL dictRemove(dictCtx dict, const char *id);
/*
* Function: dictRemove - remove item from dictionary.
* Description: Removes item identified by from .
* Input: dict - dictionary to search in.
* id - identifier of item to remove.
* Output: None.
* Return: true if item found, false if not.
* MT-Level: Safe if thread-safe.
*/
void *dictSearch(dictCtx dict, const char *id, void **plock);
/*
* Function: dictSearch - search for value in dictionary.
* Description: Searches for in , and returns value if
* found, or NULL if not. If is non-NULL, then
* the lock returned in will be associated with
* the returned value. Until this lock is passed to
* dictReleaseLock(), the value will not be passed to the
* dictCleanupFunc callback (see dictCleanup()).
* Input: dict - dictionary to search in.
* id - identifier of item to find.
* plock - place for value lock (or NULL).
* Output: plock - set to value lock.
* Return: Value associated with , or NULL if not found.
* MT-Level: Safe if thread-safe.
*/
void *dictNext(dictCtx dict, char **id, void **plock);
/*
* Function: dictNext - search for next value in dictionary.
* Description: Can be used to iterate through values in the dictionary.
* The order is the order of the hash of the ids, which
* isn't usefully externally. Will return the value if
* found, or NULL if not. If is non-NULL, then
* the lock returned in will be associated with
* the returned value. Until this lock is passed to
* dictReleaseLock(), the value will not be passed to the
* dictCleanupFunc callback (see dictCleanup()).
* Input: dict - dictionary to iterate over.
* id - pointer to identifier of last item found, or
* pointer to NULL to retrieve first.
* plock - place for value lock (or NULL).
* Output: plock - set to value lock.
* id - pointer to id of found value
* Return: Value associated with , or NULL if not found.
* MT-Level: Safe if thread-safe.
*/
void dictReleaseLock(dictCtx dict, void *lock);
/*
* Function: dictReleaseLock - release lock on value.
* Description: Releases the lock on the value associated with . Once
* the lock is released, the dictCleanupFunc callback can
* be called for the value (see dictCleanup()).
* Input: dict - dictionary containing value to release.
* lock - lock to release.
* Output: None.
* Return: None.
* MT-Level: Safe if thread-safe.
*/
NEOERR *dictSetValue(dictCtx dict, const char *id, void *value);
/*
* Function: dictSetValue - set/reset an items value.
* Description: Updates the / pair into .
* If is not in , it is created.
* Input: dict - dictionary to add pair to.
* id - identifier to insert/update
* value - value to store (may NOT be NULL)
* Output: None.
* Return: true if inserted/updated, false if error
* MT-Level: Safe if thread-safe.
*/
typedef NEOERR *(*dictNewValueCB)(const char *id, void *rock, void **new_val);
typedef NEOERR *(*dictUpdateValueCB)(const char *id, void *value, void *rock);
NEOERR *dictModifyValue(dictCtx dict, const char *id, dictNewValueCB new_cb,
dictUpdateValueCB update, void *rock);
/*
* Function: dictModifyValue - create/modify an item.
* Description: Finds 's value and calls . If is
* not in , calls to obtain a new value.
* Input: dict - dictionary to add pair to.
* id - identifier of value
* new - function to call to create new value (may be NULL)
* update - function to call to modify value (if NULL, the old
* value is freed, and is used)
* rock - context to pass to or .
* Output: None.
* Return: true if inserted/updated, false if error
* MT-Level: Safe if thread-safe.
*/
void dictCleanup(dictCtx dict, dictCleanupFunc cleanup, void *rock);
/*
* Function: dictCleanup - cleanup dictionary
* Description: Calls for every item in . If
* returns true, then item is removed from .
* Input: dict - dictionary to cleanup
* cleanup - cleanup callback
* rock - to pass to
* Output: None.
* Return: None.
* MT-Level: Safe if thread-safe.
*/
__END_DECLS
#endif /* __DICT_H_ */
clearsilver-0.10.5/util/filter.c 0000644 0012117 0011610 00000010312 10336774137 013442 0000000 0000000 /* based on concepts from the mutt filter code...
*
* This code basically does what popen should have been... and what
* popen2/popen3/popen4 in python do... it allows you access to
* as many of stdin/stdout/stderr for a sub program as you want, instead
* of just one (which is what popen is).
*/
#include "cs_config.h"
#include
#include
#include
#include
#include "util/neo_misc.h"
#include "util/neo_err.h"
#include "util/filter.h"
NEOERR *filter_wait (pid_t pid, int options, int *exitcode)
{
int r;
pid_t rpid;
rpid = waitpid (pid, &r, options);
if (WIFEXITED(r))
{
r = WEXITSTATUS(r);
if (exitcode)
{
*exitcode = r;
/* If they're asking for the exit code, we don't generate an error */
return STATUS_OK;
}
if (r == 0) return STATUS_OK;
else return nerr_raise(NERR_SYSTEM, "Child %d returned status %d:", rpid,
r);
}
if (WIFSIGNALED(r))
{
r = WTERMSIG(r);
return nerr_raise(NERR_SYSTEM, "Child %d died on signal %d:", rpid, r);
}
if (WIFSTOPPED(r))
{
r = WSTOPSIG(r);
return nerr_raise(NERR_SYSTEM, "Child %d stopped on signal %d:", rpid, r);
}
return nerr_raise(NERR_ASSERT, "ERROR: waitpid(%d, %d) returned (%d, %d)",
pid, options, rpid, r);
}
NEOERR *filter_create_fd (const char *cmd, int *fdin, int *fdout, int *fderr,
pid_t *pid)
{
int pi[2]={-1,-1}, po[2]={-1,-1}, pe[2]={-1,-1};
int rpid;
*pid = 0;
if (fdin)
{
*fdin = 0;
if (pipe (pi) == -1)
return nerr_raise_errno(NERR_SYSTEM,
"Unable to open in pipe for command: %s", cmd);
}
if (fdout)
{
*fdout = 0;
if (pipe (po) == -1)
{
if (fdin)
{
close (pi[0]);
close (pi[1]);
}
return nerr_raise_errno(NERR_SYSTEM,
"Unable to open out pipe for command: %s", cmd);
}
}
if (fderr)
{
*fderr = 0;
if (pipe (pe) == -1)
{
if (fdin)
{
close (pi[0]);
close (pi[1]);
}
if (fdout)
{
close (po[0]);
close (po[1]);
}
return nerr_raise_errno(NERR_SYSTEM, "Unable to open err pipe for command: %s", cmd);
}
}
/* block signals */
if ((rpid = fork ()) == 0)
{
/* unblock signals */
if (fdin)
{
close (pi[1]);
dup2 (pi[0], 0);
close (pi[0]);
}
if (fdout)
{
close (po[0]);
dup2 (po[1], 1);
close (po[1]);
}
if (fderr)
{
close (pe[0]);
dup2 (pe[1], 2);
close (pe[1]);
}
execl ("/bin/sh", "sh", "-c", cmd, (void *)NULL);
_exit (127);
}
else if (rpid == -1)
{
/* unblock signals */
if (fdin)
{
close (pi[0]);
close (pi[1]);
}
if (fdout)
{
close (po[0]);
close (po[1]);
}
if (fderr)
{
close (pe[0]);
close (pe[1]);
}
return nerr_raise_errno(NERR_SYSTEM, "Unable to fork for command: %s", cmd);
}
if (fdout)
{
close (po[1]);
*fdout = po[0];
}
if (fdin)
{
close (pi[0]);
*fdin = pi[1];
}
if (fderr)
{
close (pe[1]);
*fderr = pe[0];
}
*pid = rpid;
return STATUS_OK;
}
NEOERR *filter_create_fp(const char *cmd, FILE **in, FILE **out, FILE **err,
pid_t *pid)
{
NEOERR *nerr;
int fdin = 0, fdout = 0, fderr = 0;
int *pfdin = NULL, *pfdout = NULL, *pfderr = NULL;
if (in) pfdin = &fdin;
if (out) pfdout = &fdout;
if (err) pfderr = &fderr;
nerr = filter_create_fd(cmd, pfdin, pfdout, pfderr, pid);
if (nerr) return nerr_pass(nerr);
if (in)
{
*in = fdopen (fdin, "w");
if (*in == NULL)
return nerr_raise_errno(NERR_IO, "Unable to fdopen in for command: %s",
cmd);
}
if (out)
{
*out = fdopen (fdout, "r");
if (*out == NULL)
{
if (in) fclose(*in);
return nerr_raise_errno(NERR_IO, "Unable to fdopen out for command: %s",
cmd);
}
}
if (err)
{
*err = fdopen (fderr, "r");
if (*err == NULL)
{
if (in) fclose(*in);
if (out) fclose(*out);
return nerr_raise_errno(NERR_IO, "Unable to fdopen err for command: %s",
cmd);
}
}
return STATUS_OK;
}
clearsilver-0.10.5/util/filter.h 0000644 0012117 0011610 00000007375 10261040275 013450 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_FILTER_H_
#define __NEO_FILTER_H_ 1
__BEGIN_DECLS
#include
#include
#include "util/neo_misc.h"
#include "util/neo_err.h"
/*
* Function: filter_wait - wrap waitpid to decode the exitcode and why
* your filter quit
* Description: filter_wait wraps the waitpid call and raises an error
* (with description) if the call failed. Note that if the
* ask for the exitcode and the process exited with a code
* other than zero, we don't raise an error. If you don't
* ask for the exitcode, and it is non-zero, we raise an
* error
* Input: pid -> the process identifier to wait for
* options -> the options to pass to waitpid (see wait(2))
* Output: exitcode -> the exitcode if the process existed normally
* Returns: NERR_SYSTEM, NERR_ASSERT
*/
NEOERR *filter_wait(pid_t pid, int options, int *exitcode);
/*
* Function: filter_create_fd - Create a sub process and return the
* requested pipes
* Description: filter_create_fd and filter_create_fp are what popen
* should have been: a mechanism to create sub processes
* and have pipes to all their input/output. The concept
* was taken from mutt, though python has something similar
* with popen3/popen4. You control which pipes the
* function returns by the fdin/fdout/fderr arguments. A
* NULL value means "don't create a pipe", a pointer to an
* int will cause the pipes to be created and the value
* of the file descriptor stored in the int. You will have
* to close(2) the file descriptors yourself.
* Input: cmd -> the sub command to execute. Will be executed with
* /bin/sh -c
* fdin -> pointer to return the stdin pipe, or NULL if you don't
* want the stdin pipe
* fdout -> pointer to return the stdout pipe, or NULL if you don't
* want the stdout pipe
* fderr -> pointer to return the stderr pipe, or NULL if you don't
* want the stderr pipe
* Output: fdin -> the stdin file descriptor of the sub process
* fdout -> the stdout file descriptor of the sub process
* fderr -> the stderr file descriptor of the sub process
* pid -> the pid of the sub process
* Returns: NERR_SYSTEM
*/
NEOERR *filter_create_fd(const char *cmd, int *fdin, int *fdout, int *fderr,
pid_t *pid);
/*
* Function: filter_create_fp - similar to filter_create_fd except with
* buffered FILE*
* Description: filter_create_fp is identical to filter_create_fd,
* except each of the pipes is wrapped in a buffered stdio FILE
* Input: cmd -> the sub command to execute. Will be executed with
* /bin/sh -c
* in -> pointer to return the stdin pipe, or NULL if you don't
* want the stdin pipe
* out -> pointer to return the stdout pipe, or NULL if you don't
* want the stdout pipe
* err -> pointer to return the stderr pipe, or NULL if you don't
* want the stderr pipe
* Output: in -> the stdin FILE of the sub process
* out -> the stdout FILE of the sub process
* err -> the stderr FILE of the sub process
* pid -> the pid of the sub process
* Returns: NERR_SYSTEM, NERR_IO
*/
NEOERR *filter_create_fp(const char *cmd, FILE **in, FILE **out, FILE **err,
pid_t *pid);
__END_DECLS
#endif /* __NEO_FILTER_H_ */
clearsilver-0.10.5/util/missing.c 0000644 0012117 0011610 00000003637 10261037516 013630 0000000 0000000 /* Missing Functions
*
* The functions included here are provided as replacements for system
* library functions that are missing (or broken).
*
* Yes, configure usually tries to get you to have a single file for
* each function, but pppbbbttthhhhh.
*
* To my knowledge, each of these replacement functions are available as
* free code... if not, I'll have to steal them from somewhere else that
* is free (hmm, FreeBSD libc?)
*/
#include "cs_config.h"
#ifndef HAVE_STRTOK_R
#include
/* from glibc */
/* Parse S into tokens separated by characters in DELIM.
If S is NULL, the saved pointer in SAVE_PTR is used as
the next starting point. For example:
char s[] = "-abc-=-def";
char *sp;
x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
x = strtok_r(NULL, "=", &sp); // x = NULL
// s = "abc\0-def\0"
*/
char * strtok_r (char *s,const char * delim, char **save_ptr)
{
char *token;
if (s == NULL)
s = *save_ptr;
/* Scan leading delimiters. */
s += strspn (s, delim);
if (*s == '\0')
{
*save_ptr = s;
return NULL;
}
/* Find the end of the token. */
token = s;
s = strpbrk (token, delim);
if (s == NULL)
/* This token finishes the string. */
/**save_ptr = __rawmemchr (token, '\0');*/
*save_ptr = strchr (token, '\0');
else
{
/* Terminate the token and make
* *SAVE_PTR point past it. */
*s = '\0';
*save_ptr = s + 1;
}
return token;
}
#endif
#include
#ifndef HAVE_LOCALTIME_R
struct tm *localtime_r (const time_t *timep, struct tm *ttm)
{
ttm = localtime(timep);
return ttm;
}
#endif
#ifndef HAVE_GMTIME_R
struct tm *gmtime_r(const time_t *timep, struct tm *ttm)
{
ttm = gmtime(timep);
return ttm;
}
#endif
#ifndef HAVE_MKSTEMP
#include
int mkstemp(char *path)
{
return open(mktemp(path),O_RDWR);
}
#endif
clearsilver-0.10.5/util/neo_date.c 0000644 0012117 0011610 00000005104 10405130065 013715 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include "util/neo_misc.h"
#include "neo_date.h"
/* This is pretty much a HACK. Eventually, we might bring the parsing
* and stuff into this library (we can use the public domain source code
* from ftp://elsie.nci.nih.gov/pub/ as a base)
*
* For now, we just do a putenv(TZ)... which sucks, especially since
* many versions of putenv do a strdup... and then leak the memory the
* next time you putenv the same var.
*/
/* Since this is set to a partial filename and TZ=, it can't be bigger
* than this */
static char TzBuf[_POSIX_PATH_MAX + 4];
static int time_set_tz (const char *mytimezone)
{
snprintf (TzBuf, sizeof(TzBuf), "TZ=%s", mytimezone);
putenv(TzBuf);
tzset();
return 0;
}
void neo_time_expand (const time_t tt, const char *mytimezone, struct tm *ttm)
{
const char *cur_tz = getenv("TZ");
int change_back = 0;
if (cur_tz == NULL || strcmp(mytimezone, cur_tz)) {
time_set_tz (mytimezone);
change_back = 1;
}
localtime_r (&tt, ttm);
if (cur_tz && change_back) {
time_set_tz(cur_tz);
}
}
time_t neo_time_compact (struct tm *ttm, const char *mytimezone)
{
time_t r;
int save_isdst = ttm->tm_isdst;
const char *cur_tz = getenv("TZ");
int change_back = 0;
if (cur_tz == NULL || strcmp(mytimezone, cur_tz)) {
time_set_tz (mytimezone);
change_back = 1;
}
ttm->tm_isdst = -1;
r = mktime(ttm);
ttm->tm_isdst = save_isdst;
if (cur_tz && change_back) {
time_set_tz(cur_tz);
}
return r;
}
/* Hefted from NCSA HTTPd src/util.c -- What a pain in the ass. */
long neo_tz_offset(struct tm *ttm) {
/* We assume here that HAVE_TM_ZONE implies HAVE_TM_GMTOFF and
* HAVE_TZNAME implies HAVE_TIMEZONE since AC_STRUCT_TIMEZONE defines
* the former and not the latter */
#if defined(HAVE_TM_ZONE)
return ttm->tm_gmtoff;
#elif defined(HAVE_TZNAME)
long tz;
#ifndef __CYGWIN__
tz = - timezone;
#else
tz = - _timezone;
#endif
if(ttm->tm_isdst)
tz += 3600;
return tz;
#else
long tz;
struct tm loc_tm, gmt_tm;
time_t tt;
/* We probably shouldn't use the _r versions here since this
* is for older platforms... */
tt = time(NULL);
localtime_r(&tt, &loc_tm);
gmtime_r(&tt, &gmt_tm);
tz = mktime(&loc_tm) - mktime(&gmt_tm);
return tz;
#endif /* GMT OFFSet Crap */
}
clearsilver-0.10.5/util/neo_date.h 0000644 0012117 0011610 00000001221 10261040350 013713 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_DATE_H_
#define __NEO_DATE_H_ 1
#include
__BEGIN_DECLS
/* UTC time_t -> struct tm in local timezone */
void neo_time_expand (const time_t tt, const char *timezone, struct tm *ttm);
/* local timezone struct tm -> time_t UTC */
time_t neo_time_compact (struct tm *ttm, const char *timezone);
/* To be portable... in seconds */
long neo_tz_offset(struct tm *ttm);
__END_DECLS
#endif /* __NEO_DATE_H_ */
clearsilver-0.10.5/util/neo_err.c 0000644 0012117 0011610 00000023337 10403370145 013603 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "ulist.h"
#include "ulocks.h"
int NERR_PASS = -1;
int NERR_ASSERT = 0;
int NERR_NOT_FOUND = 0;
int NERR_DUPLICATE = 0;
int NERR_NOMEM = 0;
int NERR_PARSE = 0;
int NERR_OUTOFRANGE = 0;
int NERR_SYSTEM = 0;
int NERR_IO = 0;
int NERR_LOCK = 0;
int NERR_DB = 0;
int NERR_EXISTS = 0;
static NEOERR *FreeList = NULL;
static ULIST *Errors = NULL;
static int Inited = 0;
#ifdef HAVE_PTHREADS
/* In multi-threaded environments, we have to init thread safely */
static pthread_mutex_t InitLock = PTHREAD_MUTEX_INITIALIZER;
#endif
/* Set this to 1 to enable non-thread safe re-use of NEOERR data
* structures. This was a premature performance optimization that isn't
* thread safe, if we want it thread safe we need to add mutex code...
* which has its own performance penalties...
*/
static int UseFreeList = 0;
static NEOERR *_err_alloc(void)
{
NEOERR *err;
if (!UseFreeList || FreeList == NULL)
{
err = (NEOERR *)calloc (1, sizeof (NEOERR));
if (err == NULL)
{
ne_warn ("INTERNAL ERROR: Unable to allocate memory for NEOERR");
return INTERNAL_ERR;
}
return err;
}
else
{
err = FreeList;
FreeList = FreeList->next;
}
err->flags |= NE_IN_USE;
err->next = NULL;
return err;
}
static int _err_free (NEOERR *err)
{
if (err == NULL || err == INTERNAL_ERR)
return 0;
if (err->next != NULL)
_err_free(err->next);
if (UseFreeList)
{
err->next = FreeList;
FreeList = err;
err->flags = 0;
err->desc[0] = '\0';
}
else
{
free(err);
}
return 0;
}
NEOERR *nerr_raisef (const char *func, const char *file, int lineno, int error,
const char *fmt, ...)
{
NEOERR *err;
va_list ap;
err = _err_alloc();
if (err == INTERNAL_ERR)
return err;
va_start(ap, fmt);
vsnprintf (err->desc, sizeof(err->desc), fmt, ap);
va_end(ap);
err->error = error;
err->func = func;
err->file = file;
err->lineno = lineno;
return err;
}
NEOERR *nerr_raise_errnof (const char *func, const char *file, int lineno,
int error, const char *fmt, ...)
{
NEOERR *err;
va_list ap;
int l;
err = _err_alloc();
if (err == INTERNAL_ERR)
return err;
va_start(ap, fmt);
vsnprintf (err->desc, sizeof(err->desc), fmt, ap);
va_end(ap);
l = strlen(err->desc);
snprintf (err->desc + l, sizeof(err->desc)-l, ": [%d] %s", errno,
strerror (errno));
err->error = error;
err->func = func;
err->file = file;
err->lineno = lineno;
return err;
}
NEOERR *nerr_passf (const char *func, const char *file, int lineno, NEOERR *err)
{
NEOERR *nerr;
if (err == STATUS_OK)
return err;
nerr = _err_alloc();
if (nerr == INTERNAL_ERR)
return err;
nerr->error = NERR_PASS;
nerr->func = func;
nerr->file = file;
nerr->lineno = lineno;
nerr->next = err;
return nerr;
}
NEOERR *nerr_pass_ctxf (const char *func, const char *file, int lineno,
NEOERR *err, const char *fmt, ...)
{
NEOERR *nerr;
va_list ap;
if (err == STATUS_OK)
return err;
nerr = _err_alloc();
if (nerr == INTERNAL_ERR)
return err;
va_start(ap, fmt);
vsnprintf (nerr->desc, sizeof(nerr->desc), fmt, ap);
va_end(ap);
nerr->error = NERR_PASS;
nerr->func = func;
nerr->file = file;
nerr->lineno = lineno;
nerr->next = err;
return nerr;
}
/* In the future, we'll allow someone to register an error handler */
void nerr_log_error (NEOERR *err)
{
NEOERR *more;
char buf[1024];
char *err_name;
if (err == STATUS_OK)
return;
if (err == INTERNAL_ERR)
{
ne_warn ("Internal error");
return;
}
more = err;
fprintf (stderr, "Traceback (innermost last):\n");
while (more && more != INTERNAL_ERR)
{
err = more;
more = err->next;
if (err->error != NERR_PASS)
{
NEOERR *r;
if (err->error == 0)
{
err_name = buf;
snprintf (buf, sizeof (buf), "Unknown Error");
}
else
{
r = uListGet (Errors, err->error - 1, (void *)&err_name);
if (r != STATUS_OK)
{
err_name = buf;
snprintf (buf, sizeof (buf), "Error %d", err->error);
}
}
fprintf (stderr, " File \"%s\", line %d, in %s()\n%s: %s\n", err->file,
err->lineno, err->func, err_name, err->desc);
}
else
{
fprintf (stderr, " File \"%s\", line %d, in %s()\n", err->file,
err->lineno, err->func);
if (err->desc[0])
{
fprintf (stderr, " %s\n", err->desc);
}
}
}
}
void nerr_error_string (NEOERR *err, STRING *str)
{
NEOERR *more;
char buf[1024];
char *err_name;
if (err == STATUS_OK)
return;
if (err == INTERNAL_ERR)
{
string_append (str, "Internal error");
return;
}
more = err;
while (more && more != INTERNAL_ERR)
{
err = more;
more = err->next;
if (err->error != NERR_PASS)
{
NEOERR *r;
if (err->error == 0)
{
err_name = buf;
snprintf (buf, sizeof (buf), "Unknown Error");
}
else
{
r = uListGet (Errors, err->error - 1, (void *)&err_name);
if (r != STATUS_OK)
{
err_name = buf;
snprintf (buf, sizeof (buf), "Error %d", err->error);
}
}
string_appendf(str, "%s: %s", err_name, err->desc);
return;
}
}
}
void nerr_error_traceback (NEOERR *err, STRING *str)
{
NEOERR *more;
char buf[1024];
char buf2[1024];
char *err_name;
if (err == STATUS_OK)
return;
if (err == INTERNAL_ERR)
{
string_append (str, "Internal error");
return;
}
more = err;
string_append (str, "Traceback (innermost last):\n");
while (more && more != INTERNAL_ERR)
{
err = more;
more = err->next;
if (err->error != NERR_PASS)
{
NEOERR *r;
if (err->error == 0)
{
err_name = buf;
snprintf (buf, sizeof (buf), "Unknown Error");
}
else
{
r = uListGet (Errors, err->error - 1, (void *)&err_name);
if (r != STATUS_OK)
{
err_name = buf;
snprintf (buf, sizeof (buf), "Error %d", err->error);
}
}
snprintf (buf2, sizeof(buf2),
" File \"%s\", line %d, in %s()\n%s: %s\n", err->file,
err->lineno, err->func, err_name, err->desc);
string_append(str, buf2);
}
else
{
snprintf (buf2, sizeof(buf2), " File \"%s\", line %d, in %s()\n",
err->file, err->lineno, err->func);
string_append(str, buf2);
if (err->desc[0])
{
snprintf (buf2, sizeof(buf2), " %s\n", err->desc);
string_append(str, buf2);
}
}
}
}
void nerr_ignore (NEOERR **err)
{
_err_free (*err);
*err = STATUS_OK;
}
int nerr_handle (NEOERR **err, int etype)
{
NEOERR *walk = *err;
while (walk != STATUS_OK && walk != INTERNAL_ERR)
{
if (walk->error == etype)
{
_err_free(*err);
*err = STATUS_OK;
return 1;
}
walk = walk->next;
}
if (walk == STATUS_OK && etype == STATUS_OK_INT)
return 1;
if (walk == STATUS_OK)
return 0;
if (walk == INTERNAL_ERR && etype == INTERNAL_ERR_INT)
{
*err = STATUS_OK;
return 1;
}
if (walk == INTERNAL_ERR)
return 0;
return 0;
}
int nerr_match (NEOERR *err, int etype)
{
while (err != STATUS_OK && err != INTERNAL_ERR)
{
if (err->error == etype)
return 1;
err = err->next;
}
if (err == STATUS_OK && etype == STATUS_OK_INT)
return 1;
if (err == STATUS_OK)
return 0;
if (err == INTERNAL_ERR && etype == INTERNAL_ERR_INT)
return 1;
if (err == INTERNAL_ERR)
return 0;
return 0;
}
NEOERR *nerr_register (int *val, const char *name)
{
NEOERR *err;
err = uListAppend (Errors, (void *) name);
if (err != STATUS_OK) return nerr_pass(err);
*val = uListLength(Errors);
return STATUS_OK;
}
NEOERR *nerr_init (void)
{
NEOERR *err;
if (Inited == 0)
{
#ifdef HAVE_PTHREADS
/* In threaded environments, we have to mutex lock to do this init, but
* we don't want to use a mutex every time to check that it was Inited.
* So, we only lock if our first test of Inited was false */
err = mLock(&InitLock);
if (err != STATUS_OK) return nerr_pass(err);
if (Inited == 0) {
#endif
err = uListInit (&Errors, 10, 0);
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_PASS, "InternalPass");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_ASSERT, "AssertError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_NOT_FOUND, "NotFoundError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_DUPLICATE, "DuplicateError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_NOMEM, "MemoryError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_PARSE, "ParseError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_OUTOFRANGE, "RangeError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_SYSTEM, "SystemError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_IO, "IOError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_LOCK, "LockError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_DB, "DBError");
if (err != STATUS_OK) return nerr_pass(err);
err = nerr_register (&NERR_EXISTS, "ExistsError");
if (err != STATUS_OK) return nerr_pass(err);
Inited = 1;
#ifdef HAVE_PTHREADS
}
err = mUnlock(&InitLock);
if (err != STATUS_OK) return nerr_pass(err);
#endif
}
return STATUS_OK;
}
clearsilver-0.10.5/util/neo_err.h 0000644 0012117 0011610 00000017450 10645315525 013620 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_ERR_H_
#define __NEO_ERR_H_ 1
#include "util/neo_misc.h"
/* For compilers (well, cpp actually) which don't define __PRETTY_FUNCTION__ */
#ifndef __GNUC__
#define __PRETTY_FUNCTION__ "unknown_function"
#endif
__BEGIN_DECLS
/* For 64 bit systems which don't like mixing ints and pointers, we have the
* _INT version for doing that comparison */
#define STATUS_OK ((NEOERR *)0)
#define STATUS_OK_INT 0
#define INTERNAL_ERR ((NEOERR *)1)
#define INTERNAL_ERR_INT 1
/* NEOERR flags */
#define NE_IN_USE (1<<0)
typedef int NERR_TYPE;
/* Predefined Error Types - These are all registered in nerr_init */
extern NERR_TYPE NERR_PASS;
extern NERR_TYPE NERR_ASSERT;
extern NERR_TYPE NERR_NOT_FOUND;
extern NERR_TYPE NERR_DUPLICATE;
extern NERR_TYPE NERR_NOMEM;
extern NERR_TYPE NERR_PARSE;
extern NERR_TYPE NERR_OUTOFRANGE;
extern NERR_TYPE NERR_SYSTEM;
extern NERR_TYPE NERR_IO;
extern NERR_TYPE NERR_LOCK;
extern NERR_TYPE NERR_DB;
extern NERR_TYPE NERR_EXISTS;
typedef struct _neo_err
{
int error;
int err_stack;
int flags;
char desc[256];
const char *file;
const char *func;
int lineno;
/* internal use only */
struct _neo_err *next;
} NEOERR;
/* Technically, we could do this in configure and detect what their compiler
* can handle, but for now... */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define USE_C99_VARARG_MACROS 1
#elif __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 4) || defined (S_SPLINT_S)
#define USE_GNUC_VARARG_MACROS 1
#else
#error The compiler is missing support for variable-argument macros.
#endif
/*
* function: nerr_raise
* description: Use this method to create an error "exception" for
* return up the call chain
* arguments: using the macro, the function name, file, and lineno are
* automagically recorded for you. You just provide the
* error (from those listed above) and the printf-style
* reason. THIS IS A PRINTF STYLE FUNCTION, DO NOT PASS
* UNKNOWN STRING DATA AS THE FORMAT STRING.
* returns: a pointer to a NEOERR, or INTERNAL_ERR if allocation of
* NEOERR fails
*/
#if defined(USE_C99_VARARG_MACROS)
#define nerr_raise(e,f,...) \
nerr_raisef(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,__VA_ARGS__)
#elif defined(USE_GNUC_VARARG_MACROS)
#define nerr_raise(e,f,a...) \
nerr_raisef(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,##a)
#endif
NEOERR *nerr_raisef (const char *func, const char *file, int lineno,
NERR_TYPE error, const char *fmt, ...)
ATTRIBUTE_PRINTF(5,6);
#if defined(USE_C99_VARARG_MACROS)
#define nerr_raise_errno(e,f,...) \
nerr_raise_errnof(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,__VA_ARGS__)
#elif defined(USE_GNUC_VARARG_MACROS)
#define nerr_raise_errno(e,f,a...) \
nerr_raise_errnof(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,##a)
#endif
NEOERR *nerr_raise_errnof (const char *func, const char *file, int lineno,
int error, const char *fmt, ...)
ATTRIBUTE_PRINTF(5,6);
/* function: nerr_pass
* description: this function is used to pass an error up a level in the
* call chain (ie, if the error isn't handled at the
* current level). This allows us to track the traceback
* of the error.
* arguments: with the macro, the function name, file and lineno are
* automagically recorded. Just pass the error.
* returns: a pointer to an error
*/
#define nerr_pass(e) \
nerr_passf(__PRETTY_FUNCTION__,__FILE__,__LINE__,e)
NEOERR *nerr_passf (const char *func, const char *file, int lineno,
NEOERR *err);
/* function: nerr_pass_ctx
* description: this function is used to pass an error up a level in the
* call chain (ie, if the error isn't handled at the
* current level). This allows us to track the traceback
* of the error.
* This version includes context information about lower
* errors
* arguments: with the macro, the function name, file and lineno are
* automagically recorded. Just pass the error and
* a printf format string giving more information about where
* the error is occuring.
* returns: a pointer to an error
*/
#if defined(USE_C99_VARARG_MACROS)
#define nerr_pass_ctx(e,f,...) \
nerr_pass_ctxf(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,__VA_ARGS__)
#elif defined(USE_GNUC_VARARG_MACROS)
#define nerr_pass_ctx(e,f,a...) \
nerr_pass_ctxf(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,##a)
#endif
NEOERR *nerr_pass_ctxf (const char *func, const char *file, int lineno,
NEOERR *err, const char *fmt, ...)
ATTRIBUTE_PRINTF(5,6);
/* function: nerr_log_error
* description: currently, this prints out the error to stderr, and
* free's the error chain
*/
void nerr_log_error (NEOERR *err);
#include "util/neo_str.h"
/* function: nerr_error_string
* description: returns the string associated with an error (the bottom
* level of the error chain)
* arguments: err - error
* str - string to which the data is appended
* returns: None - errors appending to the string are ignored
*/
void nerr_error_string (NEOERR *err, STRING *str);
/* function: nerr_error_traceback
* description: returns the full traceback of the error chain
* arguments: err - error
* str - string to which the data is appended
* returns: None - errors appending to the string are ignored
*/
void nerr_error_traceback (NEOERR *err, STRING *str);
/* function: nerr_ignore
* description: you should only call this if you actually handle the
* error (should I rename it?). Free's the error chain.
*/
void nerr_ignore (NEOERR **err);
/* function: nerr_register
* description: register an error type. This will assign a numeric value
* to the type, and keep track of the "pretty name" for it.
* arguments: err - pointer to a NERR_TYPE
* name - pretty name for the error type
* returns: NERR_NOMEM on no memory
*/
NEOERR *nerr_register (NERR_TYPE *err, const char *name);
/* function: nerr_init
* description: initialize the NEOERR system. Can be called more than once.
* Is not thread safe. This registers all of the built in
* error types as defined at the top of this file. If you don't
* call this, all exceptions will be returned as UnknownError.
* arguments: None
* returns: possibly NERR_NOMEM, but somewhat unlikely. Possibly an
* UnknownError if NERR_NOMEM hasn't been registered yet.
*/
NEOERR *nerr_init (void);
/* function: nerr_match
* description: nerr_match is used to walk the NEOERR chain and match
* the error against a specific error type. In exception
* parlance, this would be the equivalent of "catch".
* Typically, you can just compare a NEOERR against STATUS_OK
* or just test for true if you are checking for any error.
* arguments: err - the NEOERR that has an error.
* type - the NEOERR type, as registered with nerr_register
* returns: true on match
*/
int nerr_match (NEOERR *err, NERR_TYPE type);
/* function: nerr_handle
* description: nerr_handle is a convenience function. It is the equivalent
* of nerr_match, but it will also deallocate the error chain
* on a match.
* arguments: err - pointer to a pointer NEOERR
* type - the NEOERR type, as registered with nerr_register
* returns: true on match
*/
int nerr_handle (NEOERR **err, NERR_TYPE type);
__END_DECLS
#endif /* __NEO_ERR_H_ */
clearsilver-0.10.5/util/neo_files.c 0000644 0012117 0011610 00000012613 10645307177 014125 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_files.h"
#include "wildmat.h"
NEOERR *ne_mkdirs (const char *path, mode_t mode)
{
char mypath[_POSIX_PATH_MAX];
int x;
int r;
strncpy (mypath, path, sizeof(mypath));
x = strlen(mypath);
if ((x < sizeof(mypath)) && (mypath[x-1] != '/'))
{
mypath[x] = '/';
mypath[x+1] = '\0';
}
for (x = 1; mypath[x]; x++)
{
if (mypath[x] == '/')
{
mypath[x] = '\0';
#ifdef __MINGW32__
/* Braindead MINGW32 doesn't just have a dummy argument for mode */
r = mkdir (mypath);
#else
r = mkdir (mypath, mode);
#endif
if (r == -1 && errno != EEXIST)
{
return nerr_raise_errno(NERR_SYSTEM, "ne_mkdirs: mkdir(%s, %x) failed", mypath, mode);
}
mypath[x] = '/';
}
}
return STATUS_OK;
}
NEOERR *ne_load_file_len (const char *path, char **str, int *out_len)
{
struct stat s;
int fd;
int len;
int bytes_read;
*str = NULL;
if (out_len) *out_len = 0;
if (stat(path, &s) == -1)
{
if (errno == ENOENT)
return nerr_raise (NERR_NOT_FOUND, "File %s not found", path);
return nerr_raise_errno (NERR_SYSTEM, "Unable to stat file %s", path);
}
fd = open (path, O_RDONLY);
if (fd == -1)
{
return nerr_raise_errno (NERR_SYSTEM, "Unable to open file %s", path);
}
len = s.st_size;
*str = (char *) malloc (len + 1);
if (*str == NULL)
{
close(fd);
return nerr_raise (NERR_NOMEM,
"Unable to allocate memory (%d) to load file %s", len + 1, path);
}
if ((bytes_read = read (fd, *str, len)) == -1)
{
close(fd);
free(*str);
return nerr_raise_errno (NERR_SYSTEM, "Unable to read file %s", path);
}
(*str)[bytes_read] = '\0';
close(fd);
if (out_len) *out_len = bytes_read;
return STATUS_OK;
}
NEOERR *ne_load_file (const char *path, char **str) {
return ne_load_file_len (path, str, NULL);
}
NEOERR *ne_save_file (const char *path, char *str)
{
NEOERR *err;
int fd;
int w, l;
fd = open (path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );
if (fd == -1)
{
return nerr_raise_errno (NERR_IO, "Unable to create file %s", path);
}
l = strlen(str);
w = write (fd, str, l);
if (w != l)
{
err = nerr_raise_errno (NERR_IO, "Unable to write file %s", path);
close (fd);
return err;
}
close (fd);
return STATUS_OK;
}
NEOERR *ne_remove_dir (const char *path)
{
NEOERR *err;
DIR *dp;
struct stat s;
struct dirent *de;
char npath[_POSIX_PATH_MAX];
if (stat(path, &s) == -1)
{
if (errno == ENOENT) return STATUS_OK;
return nerr_raise_errno (NERR_SYSTEM, "Unable to stat file %s", path);
}
if (!S_ISDIR(s.st_mode))
{
return nerr_raise (NERR_ASSERT, "Path %s is not a directory", path);
}
dp = opendir(path);
if (dp == NULL)
return nerr_raise_errno (NERR_IO, "Unable to open directory %s", path);
while ((de = readdir (dp)) != NULL)
{
if (strcmp(de->d_name, ".") && strcmp(de->d_name, ".."))
{
snprintf (npath, sizeof(npath), "%s/%s", path, de->d_name);
if (stat(npath, &s) == -1)
{
if (errno == ENOENT) continue;
closedir(dp);
return nerr_raise_errno (NERR_SYSTEM, "Unable to stat file %s", npath);
}
if (S_ISDIR(s.st_mode))
{
err = ne_remove_dir(npath);
if (err) break;
}
else
{
if (unlink(npath) == -1)
{
if (errno == ENOENT) continue;
closedir(dp);
return nerr_raise_errno (NERR_SYSTEM, "Unable to unlink file %s",
npath);
}
}
}
}
closedir(dp);
if (rmdir(path) == -1)
{
return nerr_raise_errno (NERR_SYSTEM, "Unable to rmdir %s", path);
}
return STATUS_OK;
}
NEOERR *ne_listdir(const char *path, ULIST **files)
{
return nerr_pass(ne_listdir_fmatch(path, files, NULL, NULL));
}
static int _glob_match(void *rock, const char *filename)
{
return wildmat(filename, rock);
}
NEOERR *ne_listdir_match(const char *path, ULIST **files, const char *match)
{
return nerr_pass(ne_listdir_fmatch(path, files, _glob_match, (void *)match));
}
NEOERR *ne_listdir_fmatch(const char *path, ULIST **files, MATCH_FUNC fmatch,
void *rock)
{
DIR *dp;
struct dirent *de;
ULIST *myfiles = NULL;
NEOERR *err = STATUS_OK;
if (files == NULL)
return nerr_raise(NERR_ASSERT, "Invalid call to ne_listdir_fmatch");
if (*files == NULL)
{
err = uListInit(&myfiles, 10, 0);
if (err) return nerr_pass(err);
}
else
{
myfiles = *files;
}
if ((dp = opendir (path)) == NULL)
{
return nerr_raise_errno(NERR_IO, "Unable to opendir %s", path);
}
while ((de = readdir (dp)) != NULL)
{
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
continue;
if (fmatch != NULL && !fmatch(rock, de->d_name))
continue;
err = uListAppend(myfiles, strdup(de->d_name));
if (err) break;
}
closedir(dp);
if (err && *files == NULL)
{
uListDestroy(&myfiles, ULIST_FREE);
}
else if (*files == NULL)
{
*files = myfiles;
}
return nerr_pass(err);
}
clearsilver-0.10.5/util/neo_files.h 0000644 0012117 0011610 00000001724 10261040677 014124 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_FILES_H_
#define __NEO_FILES_H_ 1
__BEGIN_DECLS
#include
#include
#include "util/ulist.h"
typedef int (* MATCH_FUNC)(void *rock, const char *filename);
NEOERR *ne_mkdirs (const char *path, mode_t mode);
NEOERR *ne_load_file (const char *path, char **str);
NEOERR *ne_load_file_len (const char *path, char **str, int *len);
NEOERR *ne_save_file (const char *path, char *str);
NEOERR *ne_remove_dir (const char *path);
NEOERR *ne_listdir(const char *path, ULIST **files);
NEOERR *ne_listdir_match(const char *path, ULIST **files, const char *match);
NEOERR *ne_listdir_fmatch(const char *path, ULIST **files, MATCH_FUNC fmatch,
void *rock);
__END_DECLS
#endif /* __NEO_FILES_H_ */
clearsilver-0.10.5/util/neo_hash.c 0000644 0012117 0011610 00000012765 10515537544 013755 0000000 0000000 /*
* Copyright 2003-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_hash.h"
static NEOERR *_hash_resize(NE_HASH *hash);
static NE_HASHNODE **_hash_lookup_node (NE_HASH *hash, void *key, UINT32 *hashv);
NEOERR *ne_hash_init (NE_HASH **hash, NE_HASH_FUNC hash_func, NE_COMP_FUNC comp_func)
{
NE_HASH *my_hash = NULL;
my_hash = (NE_HASH *) calloc(1, sizeof(NE_HASH));
if (my_hash == NULL)
return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NE_HASH");
my_hash->size = 256;
my_hash->num = 0;
my_hash->hash_func = hash_func;
my_hash->comp_func = comp_func;
my_hash->nodes = (NE_HASHNODE **) calloc (my_hash->size, sizeof(NE_HASHNODE *));
if (my_hash->nodes == NULL)
{
free(my_hash);
return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NE_HASHNODES");
}
*hash = my_hash;
return STATUS_OK;
}
void ne_hash_destroy (NE_HASH **hash)
{
NE_HASH *my_hash;
NE_HASHNODE *node, *next;
int x;
if (hash == NULL || *hash == NULL)
return;
my_hash = *hash;
for (x = 0; x < my_hash->size; x++)
{
node = my_hash->nodes[x];
while (node)
{
next = node->next;
free(node);
node = next;
}
}
free(my_hash->nodes);
my_hash->nodes = NULL;
free(my_hash);
*hash = NULL;
}
NEOERR *ne_hash_insert(NE_HASH *hash, void *key, void *value)
{
UINT32 hashv;
NE_HASHNODE **node;
node = _hash_lookup_node(hash, key, &hashv);
if (*node)
{
(*node)->value = value;
}
else
{
*node = (NE_HASHNODE *) malloc(sizeof(NE_HASHNODE));
if (node == NULL)
return nerr_raise(NERR_NOMEM, "Unable to allocate NE_HASHNODE");
(*node)->hashv = hashv;
(*node)->key = key;
(*node)->value = value;
(*node)->next = NULL;
}
hash->num++;
return _hash_resize(hash);
}
void *ne_hash_lookup(NE_HASH *hash, void *key)
{
NE_HASHNODE *node;
node = *_hash_lookup_node(hash, key, NULL);
return (node) ? node->value : NULL;
}
void *ne_hash_remove(NE_HASH *hash, void *key)
{
NE_HASHNODE **node, *remove;
void *value = NULL;
node = _hash_lookup_node(hash, key, NULL);
if (*node)
{
remove = *node;
*node = remove->next;
value = remove->value;
free(remove);
hash->num--;
}
return value;
}
int ne_hash_has_key(NE_HASH *hash, void *key)
{
NE_HASHNODE *node;
node = *_hash_lookup_node(hash, key, NULL);
if (node) return 1;
return 0;
}
void *ne_hash_next(NE_HASH *hash, void **key)
{
NE_HASHNODE **node = 0;
UINT32 hashv, bucket;
if (*key)
{
node = _hash_lookup_node(hash, key, NULL);
if (*node)
{
bucket = (*node)->hashv & (hash->size - 1);
}
else
{
hashv = hash->hash_func(*key);
bucket = hashv & (hash->size - 1);
}
}
else
{
bucket = 0;
}
if (*node)
{
if ((*node)->next)
{
*key = (*node)->next->key;
return (*node)->next->value;
}
bucket++;
}
while (bucket < hash->size)
{
if (hash->nodes[bucket])
{
*key = hash->nodes[bucket]->key;
return hash->nodes[bucket]->value;
}
bucket++;
}
return NULL;
}
static NE_HASHNODE **_hash_lookup_node (NE_HASH *hash, void *key, UINT32 *o_hashv)
{
UINT32 hashv, bucket;
NE_HASHNODE **node;
hashv = hash->hash_func(key);
if (o_hashv) *o_hashv = hashv;
bucket = hashv & (hash->size - 1);
/* ne_warn("Lookup %s %d %d", key, hashv, bucket); */
node = &(hash->nodes[bucket]);
if (hash->comp_func)
{
while (*node && !(hash->comp_func((*node)->key, key)))
node = &(*node)->next;
}
else
{
/* No comp_func means we're doing pointer comparisons */
while (*node && (*node)->key != key)
node = &(*node)->next;
}
/* ne_warn("Node %x", node); */
return node;
}
/* Ok, we're doing some weirdness here... */
static NEOERR *_hash_resize(NE_HASH *hash)
{
NE_HASHNODE **new_nodes;
NE_HASHNODE *entry, *prev;
int x, next_bucket;
int orig_size = hash->size;
UINT32 hash_mask;
if (hash->size > hash->num)
return STATUS_OK;
/* We always double in size */
new_nodes = (NE_HASHNODE **) realloc (hash->nodes, (hash->size*2) * sizeof(NE_HASHNODE));
if (new_nodes == NULL)
return nerr_raise(NERR_NOMEM, "Unable to allocate memory to resize NE_HASH");
hash->nodes = new_nodes;
orig_size = hash->size;
hash->size = hash->size*2;
/* Initialize new parts */
for (x = orig_size; x < hash->size; x++)
{
hash->nodes[x] = NULL;
}
hash_mask = hash->size - 1;
for (x = 0; x < orig_size; x++)
{
prev = NULL;
next_bucket = x + orig_size;
for (entry = hash->nodes[x];
entry;
entry = prev ? prev->next : hash->nodes[x])
{
if ((entry->hashv & hash_mask) != x)
{
if (prev)
{
prev->next = entry->next;
}
else
{
hash->nodes[x] = entry->next;
}
entry->next = hash->nodes[next_bucket];
hash->nodes[next_bucket] = entry;
}
else
{
prev = entry;
}
}
}
return STATUS_OK;
}
int ne_hash_str_comp(const void *a, const void *b)
{
return !strcmp((const char *)a, (const char *)b);
}
UINT32 ne_hash_str_hash(const void *a)
{
return ne_crc((unsigned char *)a, strlen((const char *)a));
}
int ne_hash_int_comp(const void *a, const void *b)
{
if (a == b) return 1;
return 0;
}
UINT32 ne_hash_int_hash(const void *a)
{
return (UINT32)(long)(a);
}
clearsilver-0.10.5/util/neo_hash.h 0000644 0012117 0011610 00000002432 10261037517 013741 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_HASH_H_
#define __NEO_HASH_H_ 1
__BEGIN_DECLS
#include
#include "util/neo_misc.h"
typedef UINT32 (*NE_HASH_FUNC)(const void *);
typedef int (*NE_COMP_FUNC)(const void *, const void *);
typedef struct _NE_HASHNODE
{
void *key;
void *value;
UINT32 hashv;
struct _NE_HASHNODE *next;
} NE_HASHNODE;
typedef struct _HASH
{
UINT32 size;
UINT32 num;
NE_HASHNODE **nodes;
NE_HASH_FUNC hash_func;
NE_COMP_FUNC comp_func;
} NE_HASH;
NEOERR *ne_hash_init (NE_HASH **hash, NE_HASH_FUNC hash_func, NE_COMP_FUNC comp_func);
void ne_hash_destroy (NE_HASH **hash);
NEOERR *ne_hash_insert(NE_HASH *hash, void *key, void *value);
void *ne_hash_lookup(NE_HASH *hash, void *key);
int ne_hash_has_key(NE_HASH *hash, void *key);
void *ne_hash_remove(NE_HASH *hash, void *key);
void *ne_hash_next(NE_HASH *hash, void **key);
int ne_hash_str_comp(const void *a, const void *b);
UINT32 ne_hash_str_hash(const void *a);
int ne_hash_int_comp(const void *a, const void *b);
UINT32 ne_hash_int_hash(const void *a);
__END_DECLS
#endif /* __NEO_HASH_H_ */
clearsilver-0.10.5/util/neo_hdf.c 0000644 0012117 0011610 00000115073 10645304545 013564 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_rand.h"
#include "neo_hdf.h"
#include "neo_str.h"
#include "neo_files.h"
#include "ulist.h"
/* Ok, in order to use the hash, we have to support n-len strings
* instead of null terminated strings (since in set_value and walk_hdf
* we are merely using part of the HDF name for lookup, and that might
* be a const, and we don't want the overhead of allocating/copying
* that data out...)
*
* Since HASH doesn't maintain any data placed in it, merely pointers to
* it, we use the HDF node itself as the key, and have specific
* comp/hash functions which just use the name/name_len as the key.
*/
static int hash_hdf_comp(const void *a, const void *b)
{
HDF *ha = (HDF *)a;
HDF *hb = (HDF *)b;
return (ha->name_len == hb->name_len) && !strncmp(ha->name, hb->name, ha->name_len);
}
static UINT32 hash_hdf_hash(const void *a)
{
HDF *ha = (HDF *)a;
return ne_crc((UINT8 *)(ha->name), ha->name_len);
}
static NEOERR *_alloc_hdf (HDF **hdf, const char *name, size_t nlen,
const char *value, int dup, int wf, HDF *top)
{
*hdf = calloc (1, sizeof (HDF));
if (*hdf == NULL)
{
return nerr_raise (NERR_NOMEM, "Unable to allocate memory for hdf element");
}
(*hdf)->top = top;
if (name != NULL)
{
(*hdf)->name_len = nlen;
(*hdf)->name = (char *) malloc (nlen + 1);
if ((*hdf)->name == NULL)
{
free((*hdf));
(*hdf) = NULL;
return nerr_raise (NERR_NOMEM,
"Unable to allocate memory for hdf element: %s", name);
}
strncpy((*hdf)->name, name, nlen);
(*hdf)->name[nlen] = '\0';
}
if (value != NULL)
{
if (dup)
{
(*hdf)->alloc_value = 1;
(*hdf)->value = strdup(value);
if ((*hdf)->value == NULL)
{
free((*hdf)->name);
free((*hdf));
(*hdf) = NULL;
return nerr_raise (NERR_NOMEM,
"Unable to allocate memory for hdf element %s", name);
}
}
else
{
(*hdf)->alloc_value = wf;
/* We're overriding the const of value here for the set_buf case
* where we overrode the char * to const char * earlier, since
* alloc_value actually keeps track of the const-ness for us */
(*hdf)->value = (char *)value;
}
}
return STATUS_OK;
}
static void _dealloc_hdf_attr(HDF_ATTR **attr)
{
HDF_ATTR *next;
while ((*attr) != NULL)
{
next = (*attr)->next;
if ((*attr)->key) free((*attr)->key);
if ((*attr)->value) free((*attr)->value);
free(*attr);
*attr = next;
}
*attr = NULL;
}
static void _dealloc_hdf (HDF **hdf)
{
HDF *myhdf = *hdf;
HDF *next = NULL;
if (myhdf == NULL) return;
if (myhdf->child != NULL)
_dealloc_hdf(&(myhdf->child));
/* This was easier recursively, but dangerous on long lists, so we
* walk it ourselves */
next = myhdf->next;
while (next != NULL)
{
myhdf->next = next->next;
next->next = NULL;
_dealloc_hdf(&next);
next = myhdf->next;
}
if (myhdf->name != NULL)
{
free (myhdf->name);
myhdf->name = NULL;
}
if (myhdf->value != NULL)
{
if (myhdf->alloc_value)
free (myhdf->value);
myhdf->value = NULL;
}
if (myhdf->attr != NULL)
{
_dealloc_hdf_attr(&(myhdf->attr));
}
if (myhdf->hash != NULL)
{
ne_hash_destroy(&myhdf->hash);
}
free(myhdf);
*hdf = NULL;
}
NEOERR* hdf_init (HDF **hdf)
{
NEOERR *err;
HDF *my_hdf;
*hdf = NULL;
err = nerr_init();
if (err != STATUS_OK)
return nerr_pass (err);
err = _alloc_hdf (&my_hdf, NULL, 0, NULL, 0, 0, NULL);
if (err != STATUS_OK)
return nerr_pass (err);
my_hdf->top = my_hdf;
*hdf = my_hdf;
return STATUS_OK;
}
void hdf_destroy (HDF **hdf)
{
if (*hdf == NULL) return;
if ((*hdf)->top == (*hdf))
{
_dealloc_hdf(hdf);
}
}
static int _walk_hdf (HDF *hdf, const char *name, HDF **node)
{
HDF *parent = NULL;
HDF *hp = hdf;
HDF hash_key;
int x = 0;
const char *s, *n;
int r;
*node = NULL;
if (hdf == NULL) return -1;
if (name == NULL || name[0] == '\0')
{
*node = hdf;
return 0;
}
if (hdf->link)
{
r = _walk_hdf (hdf->top, hdf->value, &hp);
if (r) return r;
if (hp)
{
parent = hp;
hp = hp->child;
}
}
else
{
parent = hdf;
hp = hdf->child;
}
if (hp == NULL)
{
return -1;
}
n = name;
s = strchr (n, '.');
x = (s == NULL) ? strlen(n) : s - n;
while (1)
{
if (parent && parent->hash)
{
hash_key.name = (char *)n;
hash_key.name_len = x;
hp = ne_hash_lookup(parent->hash, &hash_key);
}
else
{
while (hp != NULL)
{
if (hp->name && (x == hp->name_len) && !strncmp(hp->name, n, x))
{
break;
}
else
{
hp = hp->next;
}
}
}
if (hp == NULL)
{
return -1;
}
if (s == NULL) break;
if (hp->link)
{
r = _walk_hdf (hp->top, hp->value, &hp);
if (r) {
return r;
}
parent = hp;
hp = hp->child;
}
else
{
parent = hp;
hp = hp->child;
}
n = s + 1;
s = strchr (n, '.');
x = (s == NULL) ? strlen(n) : s - n;
}
if (hp->link)
{
return _walk_hdf (hp->top, hp->value, node);
}
*node = hp;
return 0;
}
int hdf_get_int_value (HDF *hdf, const char *name, int defval)
{
HDF *node;
int v;
char *n;
if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL))
{
v = strtol (node->value, &n, 10);
if (node->value == n) v = defval;
return v;
}
return defval;
}
/* This should return a const char *, but changing this would have big
* repurcussions for any C code using this function, so no change for now */
char* hdf_get_value (HDF *hdf, const char *name, const char *defval)
{
HDF *node;
if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL))
{
return node->value;
}
return (char *)defval;
}
char* hdf_get_valuevf (HDF *hdf, const char *namefmt, va_list ap)
{
HDF *node;
char *name;
name = vsprintf_alloc(namefmt, ap);
if (name == NULL) return NULL;
if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL))
{
free(name);
return node->value;
}
free(name);
return NULL;
}
char* hdf_get_valuef (HDF *hdf, const char *namefmt, ...)
{
char *val;
va_list ap;
va_start(ap, namefmt);
val = hdf_get_valuevf(hdf, namefmt, ap);
va_end(ap);
return val;
}
NEOERR* hdf_get_copy (HDF *hdf, const char *name, char **value,
const char *defval)
{
HDF *node;
if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL))
{
*value = strdup(node->value);
if (*value == NULL)
{
return nerr_raise (NERR_NOMEM, "Unable to allocate copy of %s", name);
}
}
else
{
if (defval == NULL)
*value = NULL;
else
{
*value = strdup(defval);
if (*value == NULL)
{
return nerr_raise (NERR_NOMEM, "Unable to allocate copy of %s", name);
}
}
}
return STATUS_OK;
}
HDF* hdf_get_obj (HDF *hdf, const char *name)
{
HDF *obj;
_walk_hdf(hdf, name, &obj);
return obj;
}
HDF* hdf_get_child (HDF *hdf, const char *name)
{
HDF *obj;
_walk_hdf(hdf, name, &obj);
if (obj != NULL) return obj->child;
return obj;
}
HDF_ATTR* hdf_get_attr (HDF *hdf, const char *name)
{
HDF *obj;
_walk_hdf(hdf, name, &obj);
if (obj != NULL) return obj->attr;
return NULL;
}
NEOERR* hdf_set_attr (HDF *hdf, const char *name, const char *key,
const char *value)
{
HDF *obj;
HDF_ATTR *attr, *last;
_walk_hdf(hdf, name, &obj);
if (obj == NULL)
return nerr_raise(NERR_ASSERT, "Unable to set attribute on none existant node");
if (obj->attr != NULL)
{
attr = obj->attr;
last = attr;
while (attr != NULL)
{
if (!strcmp(attr->key, key))
{
if (attr->value) free(attr->value);
/* a set of NULL deletes the attr */
if (value == NULL)
{
if (attr == obj->attr)
obj->attr = attr->next;
else
last->next = attr->next;
free(attr->key);
free(attr);
return STATUS_OK;
}
attr->value = strdup(value);
if (attr->value == NULL)
return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value);
return STATUS_OK;
}
last = attr;
attr = attr->next;
}
last->next = (HDF_ATTR *) calloc(1, sizeof(HDF_ATTR));
if (last->next == NULL)
return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value);
attr = last->next;
}
else
{
if (value == NULL) return STATUS_OK;
obj->attr = (HDF_ATTR *) calloc(1, sizeof(HDF_ATTR));
if (obj->attr == NULL)
return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value);
attr = obj->attr;
}
attr->key = strdup(key);
attr->value = strdup(value);
if (attr->key == NULL || attr->value == NULL)
return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value);
return STATUS_OK;
}
HDF* hdf_obj_child (HDF *hdf)
{
HDF *obj;
if (hdf == NULL) return NULL;
if (hdf->link)
{
if (_walk_hdf(hdf->top, hdf->value, &obj))
return NULL;
return obj->child;
}
return hdf->child;
}
HDF* hdf_obj_next (HDF *hdf)
{
if (hdf == NULL) return NULL;
return hdf->next;
}
HDF* hdf_obj_top (HDF *hdf)
{
if (hdf == NULL) return NULL;
return hdf->top;
}
HDF_ATTR* hdf_obj_attr (HDF *hdf)
{
if (hdf == NULL) return NULL;
return hdf->attr;
}
char* hdf_obj_name (HDF *hdf)
{
if (hdf == NULL) return NULL;
return hdf->name;
}
char* hdf_obj_value (HDF *hdf)
{
int count = 0;
if (hdf == NULL) return NULL;
while (hdf->link && count < 100)
{
if (_walk_hdf (hdf->top, hdf->value, &hdf))
return NULL;
count++;
}
return hdf->value;
}
void _merge_attr (HDF_ATTR *dest, HDF_ATTR *src)
{
HDF_ATTR *da, *ld;
HDF_ATTR *sa, *ls;
BOOL found;
sa = src;
ls = src;
while (sa != NULL)
{
da = dest;
ld = da;
found = 0;
while (da != NULL)
{
if (!strcmp(da->key, sa->key))
{
if (da->value) free(da->value);
da->value = sa->value;
sa->value = NULL;
found = 1;
break;
}
ld = da;
da = da->next;
}
if (!found)
{
ld->next = sa;
ls->next = sa->next;
if (src == sa) src = sa->next;
ld->next->next = NULL;
sa = ls->next;
}
else
{
ls = sa;
sa = sa->next;
}
}
_dealloc_hdf_attr(&src);
}
NEOERR* _hdf_hash_level(HDF *hdf)
{
NEOERR *err;
HDF *child;
err = ne_hash_init(&(hdf->hash), hash_hdf_hash, hash_hdf_comp);
if (err) return nerr_pass(err);
child = hdf->child;
while (child)
{
err = ne_hash_insert(hdf->hash, child, child);
if (err) return nerr_pass(err);
child = child->next;
}
return STATUS_OK;
}
static NEOERR* _set_value (HDF *hdf, const char *name, const char *value,
int dup, int wf, int link, HDF_ATTR *attr,
HDF **set_node)
{
NEOERR *err;
HDF *hn, *hp, *hs;
HDF hash_key;
int x = 0;
const char *s = name;
const char *n = name;
int count = 0;
if (set_node != NULL) *set_node = NULL;
if (hdf == NULL)
{
return nerr_raise(NERR_ASSERT, "Unable to set %s on NULL hdf", name);
}
/* HACK: allow setting of this node by passing an empty name */
if (name == NULL || name[0] == '\0')
{
/* handle setting attr first */
if (hdf->attr == NULL)
{
hdf->attr = attr;
}
else
{
_merge_attr(hdf->attr, attr);
}
/* if we're setting ourselves to ourselves... */
if (hdf->value == value)
{
if (set_node != NULL) *set_node = hdf;
return STATUS_OK;
}
if (hdf->alloc_value)
{
free(hdf->value);
hdf->value = NULL;
}
if (value == NULL)
{
hdf->alloc_value = 0;
hdf->value = NULL;
}
else if (dup)
{
hdf->alloc_value = 1;
hdf->value = strdup(value);
if (hdf->value == NULL)
return nerr_raise (NERR_NOMEM, "Unable to duplicate value %s for %s",
value, name);
}
else
{
hdf->alloc_value = wf;
hdf->value = (char *)value;
}
if (set_node != NULL) *set_node = hdf;
return STATUS_OK;
}
n = name;
s = strchr (n, '.');
x = (s != NULL) ? s - n : strlen(n);
if (x == 0)
{
return nerr_raise(NERR_ASSERT, "Unable to set Empty component %s", name);
}
if (hdf->link)
{
char *new_name = (char *) malloc(strlen(hdf->value) + 1 + strlen(name) + 1);
if (new_name == NULL)
{
return nerr_raise(NERR_NOMEM, "Unable to allocate memory");
}
strcpy(new_name, hdf->value);
strcat(new_name, ".");
strcat(new_name, name);
err = _set_value (hdf->top, new_name, value, dup, wf, link, attr, set_node);
free(new_name);
return nerr_pass(err);
}
else
{
hn = hdf;
}
while (1)
{
/* examine cache to see if we have a match */
count = 0;
hp = hn->last_hp;
hs = hn->last_hs;
if ((hs == NULL && hp == hn->child) || (hs && hs->next == hp))
{
if (hp && hp->name && (x == hp->name_len) && !strncmp (hp->name, n, x))
{
goto skip_search;
}
}
hp = hn->child;
hs = NULL;
/* Look for a matching node at this level */
if (hn->hash != NULL)
{
hash_key.name = (char *)n;
hash_key.name_len = x;
hp = ne_hash_lookup(hn->hash, &hash_key);
hs = hn->last_child;
}
else
{
while (hp != NULL)
{
if (hp->name && (x == hp->name_len) && !strncmp(hp->name, n, x))
{
break;
}
hs = hp;
hp = hp->next;
count++;
}
}
/* save in cache any value we found */
if (hp) {
hn->last_hp = hp;
hn->last_hs = hs;
}
skip_search:
if (hp == NULL)
{
/* If there was no matching node at this level, we need to
* allocate an intersitial node (or the actual node if we're
* at the last part of the HDF name) */
if (s != NULL)
{
/* intersitial */
err = _alloc_hdf (&hp, n, x, NULL, 0, 0, hdf->top);
}
else
{
err = _alloc_hdf (&hp, n, x, value, dup, wf, hdf->top);
if (link) hp->link = 1;
else hp->link = 0;
hp->attr = attr;
}
if (err != STATUS_OK)
return nerr_pass (err);
if (hn->child == NULL)
hn->child = hp;
else
hs->next = hp;
hn->last_child = hp;
/* This is the point at which we convert to a hash table
* at this level, if we're over the count */
if (count > FORCE_HASH_AT && hn->hash == NULL)
{
err = _hdf_hash_level(hn);
if (err) return nerr_pass(err);
}
else if (hn->hash != NULL)
{
err = ne_hash_insert(hn->hash, hp, hp);
if (err) return nerr_pass(err);
}
}
else if (s == NULL)
{
/* If there is a matching node and we're at the end of the HDF
* name, then we update the value of the node */
/* handle setting attr first */
if (hp->attr == NULL)
{
hp->attr = attr;
}
else
{
_merge_attr(hp->attr, attr);
}
if (hp->value != value)
{
if (hp->alloc_value)
{
free(hp->value);
hp->value = NULL;
}
if (value == NULL)
{
hp->alloc_value = 0;
hp->value = NULL;
}
else if (dup)
{
hp->alloc_value = 1;
hp->value = strdup(value);
if (hp->value == NULL)
return nerr_raise (NERR_NOMEM, "Unable to duplicate value %s for %s",
value, name);
}
else
{
hp->alloc_value = wf;
hp->value = (char *)value;
}
}
if (link) hp->link = 1;
else hp->link = 0;
}
else if (hp->link)
{
char *new_name = (char *) malloc(strlen(hp->value) + strlen(s) + 1);
if (new_name == NULL)
{
return nerr_raise(NERR_NOMEM, "Unable to allocate memory");
}
strcpy(new_name, hp->value);
strcat(new_name, s);
err = _set_value (hdf->top, new_name, value, dup, wf, link, attr, set_node);
free(new_name);
return nerr_pass(err);
}
/* At this point, we're done if there is not more HDF name space to
* traverse */
if (s == NULL)
break;
/* Otherwise, we need to find the next part of the namespace */
n = s + 1;
s = strchr (n, '.');
x = (s != NULL) ? s - n : strlen(n);
if (x == 0)
{
return nerr_raise(NERR_ASSERT, "Unable to set Empty component %s", name);
}
hn = hp;
}
if (set_node != NULL) *set_node = hp;
return STATUS_OK;
}
NEOERR* hdf_set_value (HDF *hdf, const char *name, const char *value)
{
return nerr_pass(_set_value (hdf, name, value, 1, 1, 0, NULL, NULL));
}
NEOERR* hdf_set_value_attr (HDF *hdf, const char *name, const char *value,
HDF_ATTR *attr)
{
return nerr_pass(_set_value (hdf, name, value, 1, 1, 0, attr, NULL));
}
NEOERR* hdf_set_symlink (HDF *hdf, const char *src, const char *dest)
{
return nerr_pass(_set_value (hdf, src, dest, 1, 1, 1, NULL, NULL));
}
NEOERR* hdf_set_int_value (HDF *hdf, const char *name, int value)
{
char buf[256];
snprintf (buf, sizeof(buf), "%d", value);
return nerr_pass(_set_value (hdf, name, buf, 1, 1, 0, NULL, NULL));
}
NEOERR* hdf_set_buf (HDF *hdf, const char *name, char *value)
{
return nerr_pass(_set_value (hdf, name, value, 0, 1, 0, NULL, NULL));
}
NEOERR* hdf_set_copy (HDF *hdf, const char *dest, const char *src)
{
HDF *node;
if ((_walk_hdf(hdf, src, &node) == 0) && (node->value != NULL))
{
return nerr_pass(_set_value (hdf, dest, node->value, 0, 0, 0, NULL, NULL));
}
return nerr_raise (NERR_NOT_FOUND, "Unable to find %s", src);
}
NEOERR* hdf_set_valuevf (HDF *hdf, const char *fmt, va_list ap)
{
NEOERR *err;
char *k;
char *v;
k = vsprintf_alloc(fmt, ap);
if (k == NULL)
{
return nerr_raise(NERR_NOMEM, "Unable to allocate memory for format string");
}
v = strchr(k, '=');
if (v == NULL)
{
err = nerr_raise(NERR_ASSERT, "No equals found: %s", k);
free(k);
return err;
}
*v++ = '\0';
err = hdf_set_value(hdf, k, v);
free(k);
return nerr_pass(err);
}
NEOERR* hdf_set_valuef (HDF *hdf, const char *fmt, ...)
{
NEOERR *err;
va_list ap;
va_start(ap, fmt);
err = hdf_set_valuevf(hdf, fmt, ap);
va_end(ap);
return nerr_pass(err);
}
NEOERR* hdf_get_node (HDF *hdf, const char *name, HDF **ret)
{
_walk_hdf(hdf, name, ret);
if (*ret == NULL)
{
return nerr_pass(_set_value (hdf, name, NULL, 0, 1, 0, NULL, ret));
}
return STATUS_OK;
}
/* Ok, this version avoids the bubble sort by walking the level once to
* load them all into a ULIST, qsort'ing the list, and then dumping them
* back out... */
NEOERR *hdf_sort_obj (HDF *h, int (*compareFunc)(const void *, const void *))
{
NEOERR *err = STATUS_OK;
ULIST *level = NULL;
HDF *p, *c;
int x;
if (h == NULL) return STATUS_OK;
c = h->child;
if (c == NULL) return STATUS_OK;
do {
err = uListInit(&level, 40, 0);
if (err) return nerr_pass(err);
for (p = c; p; p = p->next) {
err = uListAppend(level, p);
if (err) break;
}
err = uListSort(level, compareFunc);
if (err) break;
uListGet(level, 0, (void *)&c);
h->child = c;
for (x = 1; x < uListLength(level); x++)
{
uListGet(level, x, (void *)&p);
c->next = p;
p->next = NULL;
c = p;
}
h->last_child = c;
} while (0);
uListDestroy(&level, 0);
return nerr_pass(err);
}
NEOERR* hdf_remove_tree (HDF *hdf, const char *name)
{
HDF *hp = hdf;
HDF *lp = NULL, *ln = NULL; /* last parent, last node */
int x = 0;
const char *s = name;
const char *n = name;
if (hdf == NULL) return STATUS_OK;
hp = hdf->child;
if (hp == NULL)
{
return STATUS_OK;
}
lp = hdf;
ln = NULL;
n = name;
s = strchr (n, '.');
x = (s == NULL) ? strlen(n) : s - n;
while (1)
{
while (hp != NULL)
{
if (hp->name && (x == hp->name_len) && !strncmp(hp->name, n, x))
{
break;
}
else
{
ln = hp;
hp = hp->next;
}
}
if (hp == NULL)
{
return STATUS_OK;
}
if (s == NULL) break;
lp = hp;
ln = NULL;
hp = hp->child;
n = s + 1;
s = strchr (n, '.');
x = (s == NULL) ? strlen(n) : s - n;
}
if (lp->hash != NULL)
{
ne_hash_remove(lp->hash, hp);
}
if (ln)
{
ln->next = hp->next;
/* check to see if we are the last parent's last_child, if so
* repoint so hash table inserts will go to the right place */
if (hp == lp->last_child)
lp->last_child = ln;
hp->next = NULL;
}
else
{
lp->child = hp->next;
hp->next = NULL;
}
_dealloc_hdf (&hp);
return STATUS_OK;
}
static NEOERR * _copy_attr (HDF_ATTR **dest, HDF_ATTR *src)
{
HDF_ATTR *copy, *last = NULL;
*dest = NULL;
while (src != NULL)
{
copy = (HDF_ATTR *)malloc(sizeof(HDF_ATTR));
if (copy == NULL)
{
_dealloc_hdf_attr(dest);
return nerr_raise(NERR_NOMEM, "Unable to allocate copy of HDF_ATTR");
}
copy->key = strdup(src->key);
copy->value = strdup(src->value);
copy->next = NULL;
if ((copy->key == NULL) || (copy->value == NULL))
{
_dealloc_hdf_attr(dest);
return nerr_raise(NERR_NOMEM, "Unable to allocate copy of HDF_ATTR");
}
if (last) {
last->next = copy;
}
else
{
*dest = copy;
}
last = copy;
src = src->next;
}
return STATUS_OK;
}
static NEOERR * _copy_nodes (HDF *dest, HDF *src)
{
NEOERR *err = STATUS_OK;
HDF *dt, *st;
HDF_ATTR *attr_copy;
st = src->child;
while (st != NULL)
{
err = _copy_attr(&attr_copy, st->attr);
if (err) return nerr_pass(err);
err = _set_value(dest, st->name, st->value, 1, 1, 0, attr_copy, &dt);
if (err) {
_dealloc_hdf_attr(&attr_copy);
return nerr_pass(err);
}
if (src->child)
{
err = _copy_nodes (dt, st);
if (err) return nerr_pass(err);
}
st = st->next;
}
return STATUS_OK;
}
NEOERR* hdf_copy (HDF *dest, const char *name, HDF *src)
{
NEOERR *err;
HDF *node;
if (_walk_hdf(dest, name, &node) == -1)
{
err = _set_value (dest, name, NULL, 0, 0, 0, NULL, &node);
if (err) return nerr_pass (err);
}
return nerr_pass (_copy_nodes (node, src));
}
/* BUG: currently, this only prints something if there is a value...
* but we now allow attributes on nodes with no value... */
static void gen_ml_break(char *ml, size_t len)
{
int nlen;
int x = 0;
ml[x++] = '\n';
nlen = 2 + neo_rand(len-5);
if (nlen == 0)
{
nlen = len / 2;
}
while (nlen)
{
ml[x++] = ('A' + neo_rand(26));
nlen--;
}
ml[x++] = '\n';
ml[x] = '\0';
}
typedef NEOERR *(*DUMPF_CB)(void *rock, const char *fmt, ...);
static NEOERR *_fp_dump_cb (void *rock, const char *fmt, ...)
{
FILE *fp = (FILE *)rock;
va_list ap;
va_start (ap, fmt);
vfprintf(fp, fmt, ap);
va_end(ap);
return STATUS_OK;
}
static NEOERR *_string_dump_cb (void *rock, const char *fmt, ...)
{
NEOERR *err;
STRING *str = (STRING *)rock;
va_list ap;
va_start (ap, fmt);
err = string_appendvf(str, fmt, ap);
va_end(ap);
return nerr_pass(err);
}
#define DUMP_TYPE_DOTTED 0
#define DUMP_TYPE_COMPACT 1
#define DUMP_TYPE_PRETTY 2
static NEOERR* hdf_dump_cb(HDF *hdf, const char *prefix, int dtype, int lvl,
void *rock, DUMPF_CB dump_cbf)
{
NEOERR *err;
char *p, op;
char ml[10] = "\nEOM\n";
int ml_len = strlen(ml);
char whsp[256] = "";
if (dtype == DUMP_TYPE_PRETTY)
{
memset(whsp, ' ', 256);
if (lvl > 127)
lvl = 127;
whsp[lvl*2] = '\0';
}
if (hdf != NULL) hdf = hdf->child;
while (hdf != NULL)
{
op = '=';
if (hdf->value)
{
if (hdf->link) op = ':';
if (prefix && (dtype == DUMP_TYPE_DOTTED))
{
err = dump_cbf(rock, "%s.%s", prefix, hdf->name);
}
else
{
err = dump_cbf(rock, "%s%s", whsp, hdf->name);
}
if (err) return nerr_pass (err);
if (hdf->attr)
{
HDF_ATTR *attr = hdf->attr;
char *v = NULL;
err = dump_cbf(rock, " [");
if (err) return nerr_pass(err);
while (attr != NULL)
{
if (attr->value == NULL || !strcmp(attr->value, "1"))
err = dump_cbf(rock, "%s", attr->key);
else
{
v = repr_string_alloc(attr->value);
if (v == NULL)
return nerr_raise(NERR_NOMEM, "Unable to repr attr %s value %s", attr->key, attr->value);
err = dump_cbf(rock, "%s=%s", attr->key, v);
free(v);
}
if (err) return nerr_pass(err);
if (attr->next)
{
err = dump_cbf(rock, ", ");
if (err) return nerr_pass(err);
}
attr = attr->next;
}
err = dump_cbf(rock, "] ");
if (err) return nerr_pass(err);
}
if (strchr (hdf->value, '\n'))
{
int vlen = strlen(hdf->value);
while (strstr(hdf->value, ml) || ((vlen > ml_len) && !strncmp(hdf->value + vlen - ml_len + 1, ml, strlen(ml) - 1)))
{
gen_ml_break(ml, sizeof(ml));
ml_len = strlen(ml);
}
if (hdf->value[strlen(hdf->value)-1] != '\n')
err = dump_cbf(rock, " << %s%s%s", ml+1, hdf->value, ml);
else
err = dump_cbf(rock, " << %s%s%s", ml+1, hdf->value, ml+1);
}
else
{
err = dump_cbf(rock, " %c %s\n", op, hdf->value);
}
if (err) return nerr_pass (err);
}
if (hdf->child)
{
if (prefix && (dtype == DUMP_TYPE_DOTTED))
{
p = (char *) malloc (strlen(hdf->name) + strlen(prefix) + 2);
sprintf (p, "%s.%s", prefix, hdf->name);
err = hdf_dump_cb (hdf, p, dtype, lvl+1, rock, dump_cbf);
free(p);
}
else
{
if (hdf->name && (dtype != DUMP_TYPE_DOTTED))
{
err = dump_cbf(rock, "%s%s {\n", whsp, hdf->name);
if (err) return nerr_pass (err);
err = hdf_dump_cb (hdf, hdf->name, dtype, lvl+1, rock, dump_cbf);
if (err) return nerr_pass (err);
err = dump_cbf(rock, "%s}\n", whsp);
}
else
{
err = hdf_dump_cb (hdf, hdf->name, dtype, lvl+1, rock, dump_cbf);
}
}
if (err) return nerr_pass (err);
}
hdf = hdf->next;
}
return STATUS_OK;
}
NEOERR* hdf_dump_str (HDF *hdf, const char *prefix, int dtype, STRING *str)
{
return nerr_pass(hdf_dump_cb(hdf, prefix, dtype, 0, str, _string_dump_cb));
}
NEOERR* hdf_dump(HDF *hdf, const char *prefix)
{
return nerr_pass(hdf_dump_cb(hdf, prefix, DUMP_TYPE_DOTTED, 0, stdout, _fp_dump_cb));
}
NEOERR* hdf_dump_format (HDF *hdf, int lvl, FILE *fp)
{
return nerr_pass(hdf_dump_cb(hdf, "", DUMP_TYPE_PRETTY, 0, fp, _fp_dump_cb));
}
NEOERR *hdf_write_file (HDF *hdf, const char *path)
{
NEOERR *err;
FILE *fp;
fp = fopen(path, "w");
if (fp == NULL)
return nerr_raise_errno (NERR_IO, "Unable to open %s for writing", path);
err = hdf_dump_format (hdf, 0, fp);
fclose (fp);
if (err)
{
unlink(path);
}
return nerr_pass(err);
}
NEOERR *hdf_write_file_atomic (HDF *hdf, const char *path)
{
NEOERR *err;
FILE *fp;
char tpath[_POSIX_PATH_MAX];
static int count = 0;
snprintf(tpath, sizeof(tpath), "%s.%5.5f.%d", path, ne_timef(), count++);
fp = fopen(tpath, "w");
if (fp == NULL)
return nerr_raise_errno (NERR_IO, "Unable to open %s for writing", tpath);
err = hdf_dump_format (hdf, 0, fp);
fclose (fp);
if (err)
{
unlink(tpath);
return nerr_pass(err);
}
if (rename(tpath, path) == -1)
{
unlink (tpath);
return nerr_raise_errno (NERR_IO, "Unable to rename file %s to %s",
tpath, path);
}
return STATUS_OK;
}
NEOERR *hdf_write_string (HDF *hdf, char **s)
{
STRING str;
NEOERR *err;
*s = NULL;
string_init (&str);
err = hdf_dump_str (hdf, NULL, 1, &str);
if (err)
{
string_clear (&str);
return nerr_pass(err);
}
if (str.buf == NULL)
{
*s = strdup("");
if (*s == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate empty string");
}
else
{
*s = str.buf;
}
return STATUS_OK;
}
#define SKIPWS(s) while (*s && isspace(*s)) s++;
static int _copy_line (const char **s, char *buf, size_t buf_len)
{
int x = 0;
const char *st = *s;
while (*st && x < buf_len-1)
{
buf[x++] = *st;
if (*st++ == '\n') break;
}
buf[x] = '\0';
*s = st;
return x;
}
/* Copy the characters in the file (up to the next newline) into line
* and advance s to the next line */
static NEOERR *_copy_line_advance(const char **s, STRING *line)
{
NEOERR *err;
int x = 0;
const char *st = *s;
const char *nl;
nl = strchr(st, '\n');
if (nl == NULL)
{
x = strlen(st);
err = string_appendn(line, st, x);
if (err) return nerr_pass(err);
*s = st + x;
}
else
{
x = nl - st;
err = string_appendn(line, st, x);
if (err) return nerr_pass(err);
*s = nl + 1;
}
return STATUS_OK;
}
char *_strndup(const char *s, int len) {
int x;
char *dup;
if (s == NULL) return NULL;
dup = (char *) malloc(len+1);
if (dup == NULL) return NULL;
for (x = 0; x < len && s[x]; x++)
{
dup[x] = s[x];
}
dup[x] = '\0';
dup[len] = '\0';
return dup;
}
/* attributes are of the form [key1, key2, key3=value, key4="repr"] */
static NEOERR* parse_attr(char **str, HDF_ATTR **attr)
{
NEOERR *err = STATUS_OK;
char *s = *str;
char *k, *v;
int k_l, v_l;
STRING buf;
char c;
HDF_ATTR *ha, *hal = NULL;
*attr = NULL;
string_init(&buf);
while (*s && *s != ']')
{
k = s;
k_l = 0;
v = NULL;
v_l = 0;
while (*s && isalnum(*s)) s++;
k_l = s-k;
if (*s == '\0' || k_l == 0)
{
_dealloc_hdf_attr(attr);
return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str);
}
SKIPWS(s);
if (*s == '=')
{
s++;
SKIPWS(s);
if (*s == '"')
{
s++;
while (*s && *s != '"')
{
if (*s == '\\')
{
if (isdigit(*(s+1)))
{
s++;
c = *s - '0';
if (isdigit(*(s+1)))
{
s++;
c = (c * 8) + (*s - '0');
if (isdigit(*(s+1)))
{
s++;
c = (c * 8) + (*s - '0');
}
}
}
else
{
s++;
if (*s == 'n') c = '\n';
else if (*s == 't') c = '\t';
else if (*s == 'r') c = '\r';
else c = *s;
}
err = string_append_char(&buf, c);
}
else
{
err = string_append_char(&buf, *s);
}
if (err)
{
string_clear(&buf);
_dealloc_hdf_attr(attr);
return nerr_pass(err);
}
s++;
}
if (*s == '\0')
{
_dealloc_hdf_attr(attr);
string_clear(&buf);
return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str);
}
s++;
v = buf.buf;
v_l = buf.len;
}
else
{
v = s;
while (*s && *s != ' ' && *s != ',' && *s != ']') s++;
if (*s == '\0')
{
_dealloc_hdf_attr(attr);
return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str);
}
v_l = s-v;
}
}
else
{
v = "1";
}
ha = (HDF_ATTR*) calloc (1, sizeof(HDF_ATTR));
if (ha == NULL)
{
_dealloc_hdf_attr(attr);
string_clear(&buf);
return nerr_raise(NERR_NOMEM, "Unable to load attributes: %s", s);
}
if (*attr == NULL) *attr = ha;
ha->key = _strndup(k, k_l);
if (v)
ha->value = _strndup(v, v_l);
else
ha->value = strdup("");
if (ha->key == NULL || ha->value == NULL)
{
_dealloc_hdf_attr(attr);
string_clear(&buf);
return nerr_raise(NERR_NOMEM, "Unable to load attributes: %s", s);
}
if (hal != NULL) hal->next = ha;
hal = ha;
string_clear(&buf);
SKIPWS(s);
if (*s == ',')
{
s++;
SKIPWS(s);
}
}
if (*s == '\0')
{
_dealloc_hdf_attr(attr);
return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str);
}
*str = s+1;
return STATUS_OK;
}
#define INCLUDE_ERROR 0
#define INCLUDE_IGNORE 1
#define INCLUDE_FILE 2
static NEOERR* _hdf_read_string (HDF *hdf, const char **str, STRING *line,
const char *path, int *lineno, int include_handle)
{
NEOERR *err;
HDF *lower;
char *s;
char *name, *value;
HDF_ATTR *attr = NULL;
while (**str != '\0')
{
/* Reset string length, but don't free the reserved buffer */
line->len = 0;
err = _copy_line_advance(str, line);
if (err) return nerr_pass(err);
attr = NULL;
(*lineno)++;
s = line->buf;
SKIPWS(s);
if (!strncmp(s, "#include ", 9))
{
if (include_handle == INCLUDE_ERROR)
{
return nerr_raise (NERR_PARSE,
"[%d]: #include not supported in string parse",
*lineno);
}
else if (include_handle == INCLUDE_FILE)
{
int l;
s += 9;
name = neos_strip(s);
l = strlen(name);
if (name[0] == '"' && name[l-1] == '"')
{
name[l-1] = '\0';
name++;
}
err = hdf_read_file(hdf, name);
if (err != STATUS_OK)
{
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
}
}
else if (s[0] == '#')
{
/* comment: pass */
}
else if (s[0] == '}') /* up */
{
s = neos_strip(s);
if (strcmp(s, "}"))
{
err = nerr_raise(NERR_PARSE,
"[%s:%d] Trailing garbage on line following }: %s", path, *lineno,
line->buf);
return err;
}
return STATUS_OK;
}
else if (s[0])
{
/* Valid hdf name is [0-9a-zA-Z_.]+ */
name = s;
while (*s && (isalnum(*s) || *s == '_' || *s == '.')) s++;
SKIPWS(s);
if (s[0] == '[') /* attributes */
{
*s = '\0';
name = neos_strip(name);
s++;
err = parse_attr(&s, &attr);
if (err)
{
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
SKIPWS(s);
}
if (s[0] == '=') /* assignment */
{
*s = '\0';
name = neos_strip(name);
s++;
value = neos_strip(s);
err = _set_value (hdf, name, value, 1, 1, 0, attr, NULL);
if (err != STATUS_OK)
{
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
}
else if (s[0] == ':' && s[1] == '=') /* copy */
{
*s = '\0';
name = neos_strip(name);
s+=2;
value = neos_strip(s);
value = hdf_get_value(hdf->top, value, "");
err = _set_value (hdf, name, value, 1, 1, 0, attr, NULL);
if (err != STATUS_OK)
{
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
}
else if (s[0] == ':') /* link */
{
*s = '\0';
name = neos_strip(name);
s++;
value = neos_strip(s);
err = _set_value (hdf, name, value, 1, 1, 1, attr, NULL);
if (err != STATUS_OK)
{
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
}
else if (s[0] == '{') /* deeper */
{
*s = '\0';
name = neos_strip(name);
lower = hdf_get_obj (hdf, name);
if (lower == NULL)
{
err = _set_value (hdf, name, NULL, 1, 1, 0, attr, &lower);
}
else
{
err = _set_value (lower, NULL, lower->value, 1, 1, 0, attr, NULL);
}
if (err != STATUS_OK)
{
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
err = _hdf_read_string (lower, str, line, path, lineno, include_handle);
if (err != STATUS_OK)
{
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
}
else if (s[0] == '<' && s[1] == '<') /* multi-line assignment */
{
char *m;
int msize = 0;
int mmax = 128;
int l;
*s = '\0';
name = neos_strip(name);
s+=2;
value = neos_strip(s);
l = strlen(value);
if (l == 0)
{
err = nerr_raise(NERR_PARSE,
"[%s:%d] No multi-assignment terminator given: %s", path, *lineno,
line->buf);
return err;
}
m = (char *) malloc (mmax * sizeof(char));
if (m == NULL)
{
return nerr_raise(NERR_NOMEM,
"[%s:%d] Unable to allocate memory for multi-line assignment to %s",
path, *lineno, name);
}
while (_copy_line (str, m+msize, mmax-msize) != 0)
{
(*lineno)++;
if (!strncmp(value, m+msize, l) && isspace(m[msize+l]))
{
m[msize] = '\0';
break;
}
msize += strlen(m+msize);
if (msize + l + 10 > mmax)
{
mmax += 128;
m = (char *) realloc (m, mmax * sizeof(char));
if (m == NULL)
{
return nerr_raise(NERR_NOMEM,
"[%s:%d] Unable to allocate memory for multi-line assignment to %s: size=%d",
path, *lineno, name, mmax);
}
}
}
err = _set_value (hdf, name, m, 0, 1, 0, attr, NULL);
if (err != STATUS_OK)
{
free (m);
return nerr_pass_ctx(err, "In file %s:%d", path, *lineno);
}
}
else
{
err = nerr_raise(NERR_PARSE, "[%s:%d] Unable to parse line %s", path,
*lineno, line->buf);
return err;
}
}
}
return STATUS_OK;
}
NEOERR * hdf_read_string (HDF *hdf, const char *str)
{
NEOERR *err;
int lineno = 0;
STRING line;
string_init(&line);
err = _hdf_read_string(hdf, &str, &line, "", &lineno, INCLUDE_ERROR);
string_clear(&line);
return nerr_pass(err);
}
NEOERR * hdf_read_string_ignore (HDF *hdf, const char *str, int ignore)
{
NEOERR *err;
int lineno = 0;
STRING line;
string_init(&line);
err = _hdf_read_string(hdf, &str, &line, "", &lineno,
(ignore ? INCLUDE_IGNORE : INCLUDE_ERROR));
string_clear(&line);
return nerr_pass(err);
}
/* The search path is part of the HDF by convention */
NEOERR* hdf_search_path (HDF *hdf, const char *path, char *full)
{
HDF *paths;
struct stat s;
for (paths = hdf_get_child (hdf, "hdf.loadpaths");
paths;
paths = hdf_obj_next (paths))
{
snprintf (full, _POSIX_PATH_MAX, "%s/%s", hdf_obj_value(paths), path);
errno = 0;
if (stat (full, &s) == -1)
{
if (errno != ENOENT)
return nerr_raise_errno (NERR_SYSTEM, "Stat of %s failed", full);
}
else
{
return STATUS_OK;
}
}
strncpy (full, path, _POSIX_PATH_MAX);
if (stat (full, &s) == -1)
{
if (errno != ENOENT)
return nerr_raise_errno (NERR_SYSTEM, "Stat of %s failed", full);
}
else return STATUS_OK;
return nerr_raise (NERR_NOT_FOUND, "Path %s not found", path);
}
NEOERR* hdf_read_file (HDF *hdf, const char *path)
{
NEOERR *err;
int lineno = 0;
char fpath[_POSIX_PATH_MAX];
char *ibuf = NULL;
const char *ptr = NULL;
HDF *top = hdf->top;
STRING line;
string_init(&line);
if (path == NULL)
return nerr_raise(NERR_ASSERT, "Can't read NULL file");
if (top->fileload)
{
err = top->fileload(top->fileload_ctx, hdf, path, &ibuf);
}
else
{
if (path[0] != '/')
{
err = hdf_search_path (hdf, path, fpath);
if (err != STATUS_OK) return nerr_pass(err);
path = fpath;
}
err = ne_load_file (path, &ibuf);
}
if (err) return nerr_pass(err);
ptr = ibuf;
err = _hdf_read_string(hdf, &ptr, &line, path, &lineno, INCLUDE_FILE);
free(ibuf);
string_clear(&line);
return nerr_pass(err);
}
void hdf_register_fileload(HDF *hdf, void *ctx, HDFFILELOAD fileload)
{
if (hdf == NULL) return;
if (hdf->top != NULL) hdf = hdf->top;
hdf->fileload_ctx = ctx;
hdf->fileload = fileload;
}
clearsilver-0.10.5/util/neo_hdf.h 0000644 0012117 0011610 00000052572 10645311324 013566 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_HDF_H_
#define __NEO_HDF_H_ 1
__BEGIN_DECLS
#include
#include "util/neo_err.h"
#include "util/neo_hash.h"
#define FORCE_HASH_AT 10
typedef struct _hdf HDF;
/* HDFFILELOAD is a callback function to intercept file load requests and
* provide templates via another mechanism. This way you can load templates
* that you compiled-into your binary, from in-memory caches, or from a
* zip file, etc. The HDF is provided so you can choose to use the
* hdf_search_path function to find the file. contents should return
* a full malloc copy of the contents of the file, which the parser will
* own and free. Use hdf_register_fileload to set this function for
* your top level HDF node.
* NOTE: Technically, we shouldn't need a separate copy for each parse, but
* using the separate copy makes this equivalent to the CSFILELOAD function. We
* can change this if we really want to save that copy at the expense of
* slightly more complicated code. */
typedef NEOERR* (*HDFFILELOAD)(void *ctx, HDF *hdf, const char *filename,
char **contents);
typedef struct _attr
{
char *key;
char *value;
struct _attr *next;
} HDF_ATTR;
struct _hdf
{
int link;
int alloc_value;
char *name;
int name_len;
char *value;
struct _attr *attr;
struct _hdf *top;
struct _hdf *next;
struct _hdf *child;
/* the following fields are used to implement a cache */
struct _hdf *last_hp;
struct _hdf *last_hs;
/* the following HASH is used when we reach more than FORCE_HASH_AT
* elements */
NE_HASH *hash;
/* When using the HASH, we need to know where to append new children */
struct _hdf *last_child;
/* Should only be set on the head node, used to override the default file
* load method */
void *fileload_ctx;
HDFFILELOAD fileload;
};
/*
* Function: hdf_init - Initialize an HDF data set
* Description: hdf_init initializes an HDF data set and returns the
* pointer to the top node in the data set.
* Input: hdf - pointer to an HDF pointer
* Output: hdf - allocated hdf node
* Returns: NERR_NOMEM - unable to allocate memory for dataset
*/
NEOERR* hdf_init (HDF **hdf);
/*
* Function: hdf_destroy - deallocate an HDF data set
* Description: hdf_destroy is used to deallocate all memory associated
* with an hdf data set. Although you can pass an HDF node
* as an argument to this function, you are likely to cause
* a segfault if you continue to access the data set. In
* the future, we may restrict hdf_destroy so it only works
* on the top level node.
* Input: hdf - pointer to an HDF data set allocated with hdf_init
* Output: None
* Returns: None
*/
void hdf_destroy (HDF **hdf);
/*
* Function: hdf_get_int_value - Return the integer value of a point in
* the data set
* Description: hdf_get_int_value walks the HDF data set pointed to by
* hdf to name, and returns the value of that node
* converted to an integer. If that node does not exist,
* or it does not contain a number, the defval is returned.
* Input: hdf -> a node in an HDF data set
* name -> the name of a node to walk to in the data set
* defval -> value to return in case of error or if the node
* doesn't exist
* Output: None
* Returns: The integer value of the node, or the defval
*/
int hdf_get_int_value (HDF *hdf, const char *name, int defval);
/*
* Function: hdf_get_value - Return the value of a node in the data set
* Description: hdf_get_value walks the data set pointed to by hdf via
* name and returns the string value located there, or
* defval if the node doesn't exist
* Input: hdf -> the dataset node to start from
* name -> the name to walk the data set to
* defval -> the default value to return if the node doesn't
* exist
* Output: None
* Returns: A pointer to the string stored in the data set, or defval.
* The data set maintains ownership of the string, if you want
* a copy you either have to call strdup yourself, or use
* hdf_get_copy
*/
char *hdf_get_value (HDF *hdf, const char *name, const char *defval);
/*
* Function: hdf_get_valuevf - Return the value of a node in the data set
* Description: hdf_get_valuevf walks the data set pointed to by hdf via
* namefmt printf expanded with varargs ap, and returns the
* string value located there, or NULL if it doesn't exist.
* This differs from hdf_get_value in that there is no
* default value possible.
* Input: hdf -> the dataset node to start from
* namefmt -> the format string
* ap -> va_list of varargs
* Output: None
* Returns: A pointer to the string stored in the data set, or NULL.
* The data set maintains ownership of the string, if you want
* a copy you either have to call strdup yourself.
*/
char* hdf_get_valuevf (HDF *hdf, const char *namefmt, va_list ap);
/*
* Function: hdf_get_valuef - Return the value of a node in the data set
* Description: hdf_get_valuef walks the data set pointed to by hdf via
* namefmt printf expanded with varargs, and returns the
* string value located there, or NULL if it doesn't exist.
* This differs from hdf_get_value in that there is no
* default value possible.
* Input: hdf -> the dataset node to start from
* namefmt -> the printf-style format string
* ... -> arguments to fill out namefmt
* Output: None
* Returns: A pointer to the string stored in the data set, or NULL.
* The data set maintains ownership of the string, if you want
* a copy you either have to call strdup yourself.
*/
char* hdf_get_valuef (HDF *hdf, const char *namefmt, ...)
ATTRIBUTE_PRINTF(2,3);
/*
* Function: hdf_get_copy - Returns a copy of a string in the HDF data set
* Description: hdf_get_copy is similar to hdf_get_value, except that it
* returns an malloc'd copy of the string.
* Input: hdf -> the dataset node to start from
* name -> the name to walk the data set to
* defval -> the default value to return if the node doesn't
* exist
* Output: value -> the allocated string (if defval = NULL, then value
* will be NULL if defval is used)
* Returns: NERR_NOMEM if unable to allocate the new copy
*/
NEOERR* hdf_get_copy (HDF *hdf, const char *name, char **value,
const char *defval);
/*
* Function: hdf_get_obj - return the HDF data set node at a named location
* Description: hdf_get_obj walks the dataset given by hdf to the node
* named name, and then returns the pointer to that node
* Input: hdf -> the dataset node to start from
* name -> the name to walk to
* Output: None
* Returns: the pointer to the named node, or NULL if it doesn't exist
*/
HDF* hdf_get_obj (HDF *hdf, const char *name);
/*
* Function: hdf_get_node - Similar to hdf_get_obj except all the nodes
* are created if the don't exist.
* Description: hdf_get_node is similar to hdf_get_obj, except instead
* of stopping if it can't find a node in the tree, it will
* create all of the nodes necessary to hand you back the
* node you ask for. Nodes are created with no value.
* Input: hdf -> the dataset node to start from
* name -> the name to walk to
* Output: ret -> the dataset node you asked for
* Returns: NERR_NOMEM - unable to allocate new nodes
*/
NEOERR * hdf_get_node (HDF *hdf, const char *name, HDF **ret);
/*
* Function: hdf_get_child - return the first child of the named node
* Description: hdf_get_child will walk the dataset starting at hdf to
* name, and return the first child of that node
* Input: hdf -> the dataset node to start from
* name -> the name to walk to
* Output: None
* Returns: The first child of the named dataset node or NULL if the
* node is not found (or it has no children)
*/
HDF* hdf_get_child (HDF *hdf, const char *name);
/*
* Function: hdf_get_attr -
* Description:
* Input:
* Output:
* Returns:
*/
HDF_ATTR* hdf_get_attr (HDF *hdf, const char *name);
/*
* Function: hdf_set_attr -
* Description:
* Input:
* Output:
* Returns:
*/
NEOERR* hdf_set_attr (HDF *hdf, const char *name, const char *key,
const char *value);
/*
* Function: hdf_obj_child - Return the first child of a dataset node
* Description: hdf_obj_child and the other hdf_obj_ functions are
* accessors to the HDF dataset. Although we do not
* currently "hide" the HDF struct implementation, we
* recommend you use the accessor functions instead of
* accessing the values directly.
* Input: hdf -> the hdf dataset node
* Output: None
* Returns: The pointer to the first child, or NULL if there is none
*/
HDF* hdf_obj_child (HDF *hdf);
/*
* Function: hdf_obj_next - Return the next node of a dataset level
* Description: hdf_obj_next is an accessor function for the HDF struct
* Input: hdf -> the hdf dataset node
* Output: None
* Returns: The pointer to the next node, or NULL if there is none
*/
HDF* hdf_obj_next (HDF *hdf);
/*
* Function: hdf_obj_top - Return the pointer to the top dataset node
* Description: hdf_obj_top is an accessor function which returns a
* pointer to the top of the dataset, the node which was
* returned by hdf_init. This is most useful for
* implementations of language wrappers where individual
* nodes are tied garbage colletion wise to the top node of
* the data set
* Input: hdf -> the hdf dataset node
* Output: None
* Returns: The pointer to the top node
*/
HDF* hdf_obj_top (HDF *hdf);
/*
* Function: hdf_obj_attr - Return the HDF Attributes for a node
* Description:
* Input:
* Output:
* Returns:
*/
HDF_ATTR* hdf_obj_attr (HDF *hdf);
/*
* Function: hdf_obj_name - Return the name of a node
* Description: hdf_obj_name is an accessor function for a datset node
* which returns the name of the node. This is just the
* local name, and not the full path.
* Input: hdf -> the hdf dataset node
* Output: None
* Returns: The name of the node. If this is the top node, the name is
* NULL.
*/
char* hdf_obj_name (HDF *hdf);
/*
* Function: hdf_obj_value - Return the value of a node
* Description: hdf_obj_value is an accessor function for a dataset node
* which returns the value of the node, or NULL if the node
* has no value. This is not a copy of the value, so the
* node retains ownership of the value
* Input: hdf -> the hdf dataset node
* Output: None
* Returns: The value of the node, or NULL if it has no value
*/
char* hdf_obj_value (HDF *hdf);
/*
* Function: hdf_set_value - Set the value of a named node
* Description: hdf_set_value will set the value of a named node. All
* of the interstitial nodes which don't exist will be
* created with a value of NULL. Existing nodes are not
* modified. New nodes are created at the end of the list.
* If a list of nodes exceeds FORCE_HASH_AT, then a HASH
* will be created at that level and all of the nodes will
* be added to the hash for faster lookup times.
* The copy of the value will be made which the dataset
* will own.
* Input: hdf -> the pointer to the hdf dataset
* name -> the named node to walk to
* value -> the value to set the node to
* Output: None
* Returns: NERR_NOMEM
*/
NEOERR* hdf_set_value (HDF *hdf, const char *name, const char *value);
/*
* Function: hdf_set_valuef - Set the value of a named node
* Description: hdf_set_valuef is a convenience function that wraps
* hdf_set_value. Due to limitations of C, the fmt is in
* the format "name=value", where we will first format the
* entire string, and then break it at the first (from the
* left) equal sign (=) and use the left portion as the
* name and the right portion as the value. This function
* is somewhat inefficient in that it first allocates the
* full name=value, and then the call to hdf_set_value
* duplicates the value portion, and then we free the
* name=value.
* Currently, we don't strip whitespace from the key or
* value. In the future, this function might work more
* like reading a single line of an HDF string or file,
* allowing for attributes and symlinks to be specified...
* maybe.
* Input: hdf -> the pointer to the hdf dataset
* fmt -> the name=value printf(3) format string
* Output: None
* Returns: NERR_NOMEM
*/
NEOERR* hdf_set_valuef (HDF *hdf, const char *fmt, ...)
ATTRIBUTE_PRINTF(2,3);
NEOERR* hdf_set_valuevf (HDF *hdf, const char *fmt, va_list ap);
/*
* Function: hdf_set_int_value - Set the value of a named node to a number
* Description: hdf_set_int_value is a helper function that maps an
* integer to a string, and then calls hdf_set_value with
* that string
* Input: hdf -> the pointer to the hdf dataset
* name -> the named node to walk to
* value -> the value to set the node to
* Output: None
* Returns: NERR_NOMEM
*/
NEOERR* hdf_set_int_value (HDF *hdf, const char *name, int value);
/*
* Function: hdf_set_copy -> Copy a value from one location in the
* dataset to another
* Description: hdf_set_copy first walks the hdf dataset to the named src
* node, and then copies that value to the named dest node.
* If the src node is not found, an error is raised.
* Input: hdf -> the pointer to the dataset node
* dest -> the name of the destination node
* src -> the name of the source node
* Output: None
* Returns: NERR_NOMEM, NERR_NOT_FOUND
*/
NEOERR* hdf_set_copy (HDF *hdf, const char *dest, const char *src);
/*
* Function: hdf_set_buf - Set the value of a node without duplicating
* the value
* Description: hdf_set_buf is similar to hdf_set_value, except the
* dataset takes ownership of the value instead of making a
* copy of it. The dataset assumes that value was
* malloc'd, since it will attempt to free it when
* hdf_destroy is called
* Input: hdf -> the hdf dataset node
* name -> the name to walk to
* value -> the malloc'd value
* Output: None
* Returns: NERR_NOMEM - unable to allocate a node
*/
NEOERR* hdf_set_buf (HDF *hdf, const char *name, char *value);
/*
* Function: hdf_set_symlink - Set part of the tree to link to another
* Description: hdf_set_symlink creates a link between two sections of
* an HDF dataset. The link is "by name" hence the term
* "symlink". This means that the destination node does
* not need to exist. Any attempt to access the source
* node will cause the function to walk to the dest node,
* and then continue walking from there. Using symlinks
* can "hide" values in the dataset since you won't be able
* to access any children of the linked node directly,
* though dumps and other things which access the data
* structure directly will bypass the symlink. Use this
* feature sparingly as its likely to surprise you.
* Input: hdf -> the dataset node
* src -> the source node name
* dest -> the destination node name (from the top of the
* dataset, not relative names)
* Output: None
* Returns: NERR_NOMEM
*/
NEOERR *hdf_set_symlink (HDF *hdf, const char *src, const char *dest);
/*
* Function: hdf_sort_obj - sort the children of an HDF node
* Description: hdf_sort_obj will sort the children of an HDF node,
* based on the given comparison function.
* This function works by creating an array of the pointers
* for each child object of h, using qsort to sort that
* array, and then re-ordering the linked list of children
* to the new order. The qsort compare function uses a
* pointer to the value in the array, which in our case is
* a pointer to an HDF struct, so your comparison function
* should work on HDF ** pointers.
* Input: h - HDF node
* compareFunc - function which returns 1,0,-1 depending on some
* criteria. The arguments to this sort function
* are pointers to pointers to HDF elements. For
* example:
* int sortByName(const void *a, const void *b) {
* HDF **ha = (HDF **)a;
* HDF **hb = (HDF **)b;
*
* return strcasecmp(hdf_obj_name(*ha), hdf_obj_name(*hb));
* }
*
* Output: None (h children will be sorted)
* Return: NERR_NOMEM
*/
NEOERR *hdf_sort_obj(HDF *h, int (*compareFunc)(const void *, const void *));
/*
* Function: hdf_read_file - read an HDF data file
* Description:
* Input:
* Output:
* Returns: NERR_IO, NERR_NOMEM, NERR_PARSE
*/
NEOERR* hdf_read_file (HDF *hdf, const char *path);
/*
* Function: hdf_write_file - write an HDF data file
* Description:
* Input:
* Output:
* Returns: NERR_IO
*/
NEOERR* hdf_write_file (HDF *hdf, const char *path);
/*
* Function: hdf_write_file_atomic - write an HDF data file atomically
* Description: hdf_write_file_atomic is similar to hdf_write_file,
* except the new file is created with a unique name and
* then rename(2) is used to atomically replace the old
* file with the new file
* Input:
* Output:
* Returns: NERR_IO
*/
NEOERR* hdf_write_file_atomic (HDF *hdf, const char *path);
/*
* Function: hdf_read_string - read an HDF string
* Description:
* Input:
* Output:
* Returns: NERR_NOMEM, NERR_PARSE
*/
NEOERR* hdf_read_string (HDF *hdf, const char *s);
/*
* Function: hdf_read_string_ignore - Read an HDF string and ignore errors
* Description:
* Input:
* Output:
* Returns: NERR_NOMEM
*/
NEOERR* hdf_read_string_ignore (HDF *hdf, const char *s, int ignore);
/*
* Function: hdf_write_string - serialize an HDF dataset to a string
* Description:
* Input:
* Output:
* Returns: NERR_NOMEM
*/
NEOERR* hdf_write_string (HDF *hdf, char **s);
/*
* Function: hdf_dump - dump an HDF dataset to stdout
* Description:
* Input:
* Output:
* Returns:
*/
NEOERR* hdf_dump (HDF *hdf, const char *prefix);
/*
* Function: hdf_dump_format - dump an HDF dataset to FILE *fp
* Description:
* Input:
* Output:
* Returns:
*/
NEOERR* hdf_dump_format (HDF *hdf, int lvl, FILE *fp);
/*
* Function: hdf_dump_str - dump an HDF dataset to STRING
* Description:
* Input:
* Output:
* Returns:
*/
NEOERR* hdf_dump_str(HDF *hdf, const char *prefix, int compact, STRING *str);
/*
* Function: hdf_remove_tree - delete a subtree of an HDF dataset
* Description:
* Input:
* Output:
* Returns:
*/
NEOERR* hdf_remove_tree (HDF *hdf, const char *name);
/*
* Function: hdf_copy - copy part of an HDF dataset to another
* Description: hdf_copy is a deep copy of an HDF tree pointed to by
* src to the named node of dest. dest and src need not be
* part of the same data set
* Input: dest_hdf -> the destination dataset
* name -> the name of the destination node
* src -> the hdf dataset to copy to the destination
* Output: None
* Returns: NERR_NOMEM, NERR_NOT_FOUND
*/
NEOERR* hdf_copy (HDF *dest_hdf, const char *name, HDF *src);
/*
* Function: hdf_search_path - Find a file given a search path in HDF
* Description: hdf_search_path is a convenience/utility function that
* searches for relative filenames in a search path. The
* search path is the list given by the children of
* hdf.loadpaths.
* Input: hdf -> the hdf dataset to use
* path -> the relative path
* full -> a pointer to a _POSIX_PATH_MAX buffer
* Output: full -> the full path of the file
* Returns: NERR_NOT_FOUND if the file wasn't found in the search path
*/
NEOERR* hdf_search_path (HDF *hdf, const char *path, char *full);
/*
* Function: hdf_register_fileload - register a fileload function
* Description: hdf_register_fileload registers a fileload function that
* overrides the built-in function. The built-in function
* uses hdf_search_path and ne_file_load (based on stat/open/read)
* to find and load the file on every hdf_read_file (including
* #include). You can override this function if you wish to provide
* other file search functions, or load the hdf file
* from an in-memory cache, etc.
* Input: hdf - pointer to a head HDF node
* ctx - pointer that is passed to the HDFFILELOAD function when called
* fileload - a HDFFILELOAD function
* Output: None
* Return: None
*
*/
void hdf_register_fileload(HDF *hdf, void *ctx, HDFFILELOAD fileload);
__END_DECLS
#endif /* __NEO_HDF_H_ */
clearsilver-0.10.5/util/neo_misc.c 0000644 0012117 0011610 00000013736 10345210575 013755 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
void ne_vwarn (const char *fmt, va_list ap)
{
char tbuf[20];
char buf[1024];
struct tm my_tm;
time_t now;
int len;
now = time(NULL);
localtime_r(&now, &my_tm);
strftime(tbuf, sizeof(tbuf), "%m/%d %T", &my_tm);
vsnprintf (buf, sizeof(buf), fmt, ap);
len = strlen(buf);
while (len && isspace (buf[len-1])) buf[--len] = '\0';
fprintf (stderr, "[%s] %s\n", tbuf, buf);
}
void ne_warn (const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
ne_vwarn (fmt, ap);
va_end (ap);
}
static int LogLevel = 0;
void ne_set_log (int level)
{
LogLevel = level;
}
void ne_log (int level, const char *fmt, ...)
{
va_list ap;
if (LogLevel >= level)
{
va_start (ap, fmt);
ne_vwarn (fmt, ap);
va_end (ap);
}
}
UINT32 python_string_hash (const char *s)
{
int len=0;
register UINT32 x;
x = *s << 7;
while(*s != 0) {
x = (1000003*x) ^ *s;
s++;
len++;
}
x ^= len;
if(x == -1) x = -2;
return x;
}
UINT8 *ne_stream4 (UINT8 *dest, UINT32 num)
{
dest[0] = num & 0xFF;
dest[1] = (num >> 8) & 0xFF;
dest[2] = (num >> 16) & 0xFF;
dest[3] = (num >> 24) & 0xFF;
return dest + 4;
}
UINT8 *ne_stream2 (UINT8 *dest, UINT16 num)
{
dest[0] = num & 0xFF;
dest[1] = (num >> 8) & 0xFF;
return dest + 2;
}
UINT8 *ne_unstream4 (UINT32 *pnum, UINT8 *src)
{
*pnum = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
return src + 4;
}
UINT8 *ne_unstream2 (UINT16 *pnum, UINT8 *src)
{
*pnum = src[0] | (src[1] << 8);
return src + 2;
}
/* This handles strings of less than 256 bytes */
UINT8 *ne_unstream_str (char *s, int l, UINT8 *src)
{
UINT8 sl;
sl = src[0];
if (sl > l)
sl = l;
memcpy (s, src+1, sl);
s[l-1] = '\0';
return src+sl+1;
}
UINT8 *ne_stream_str (UINT8 *dest, const char *s, int l)
{
if (l > 255)
{
ne_warn("WARNING: calling ne_stream_str with l>255");
l = 255;
}
dest[0] = l;
memcpy (dest+1, s, l);
return dest+l+1;
}
#ifndef HAVE_GETTIMEOFDAY
/* Ok, if we don't have gettimeofday, they only get second resolution */
double ne_timef (void) {
return time(NULL);
}
#else
double ne_timef (void)
{
double f = 0;
struct timeval tv;
int ret;
ret = gettimeofday(&tv, NULL);
if (ret == 0)
{
f = tv.tv_sec + (tv.tv_usec / 1000000.0);
}
return f;
}
#endif
static const UINT32 CRCTable[256] = {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,
0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,
0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,
0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,
0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
UINT32 ne_crc (UINT8 *data, UINT32 bytes)
{
UINT32 crc, i;
crc = (UINT32)-1;
for(i = 0; i < bytes; i++, data++)
crc = ((crc >> 8) & 0xFFFFFF) ^ CRCTable[((crc ^ *data) & 0xFF)];
crc = ~crc;
return crc;
}
clearsilver-0.10.5/util/neo_misc.h 0000644 0012117 0011610 00000005501 10645311660 013751 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_MISC_H_
#define __NEO_MISC_H_ 1
#include
#include
#include
/* In case they didn't start from ClearSilver.h. */
#ifndef __CS_CONFIG_H_
#include "cs_config.h"
#endif
/* Fix Up for systems that don't define these standard things */
#ifndef __BEGIN_DECLS
#ifdef __cplusplus
#define __BEGIN_DECLS extern "C" {
#define __END_DECLS }
#else
#define __BEGIN_DECLS
#define __END_DECLS
#endif
#endif
#ifndef _POSIX_PATH_MAX
#define _POSIX_PATH_MAX 255
#endif
#ifndef S_IXGRP
#define S_IXGRP S_IXUSR
#endif
#ifndef S_IWGRP
#define S_IWGRP S_IWUSR
#endif
#ifndef S_IRGRP
#define S_IRGRP S_IRUSR
#endif
#ifndef S_IXOTH
#define S_IXOTH S_IXUSR
#endif
#ifndef S_IWOTH
#define S_IWOTH S_IWUSR
#endif
#ifndef S_IROTH
#define S_IROTH S_IRUSR
#endif
/* Format string checking for compilers that support it (GCC style) */
#if __GNUC__ > 2 || __GNUC__ == 2 && __GNUC_MINOR__ > 6
#define ATTRIBUTE_PRINTF(a1,a2) __attribute__((__format__ (__printf__, a1, a2)))
#else
#define ATTRIBUTE_PRINTF(a1,a2)
#endif
__BEGIN_DECLS
#ifndef HAVE_STRTOK_R
char * strtok_r (char *s,const char * delim, char **save_ptr);
#endif
#ifndef HAVE_LOCALTIME_R
struct tm *localtime_r (const time_t *timep, struct tm *ttm);
#endif
#ifndef HAVE_GMTIME_R
struct tm *gmtime_r(const time_t *timep, struct tm *ttm);
#endif
#ifndef HAVE_MKSTEMP
int mkstemp(char *path);
#endif
#ifndef HAVE_SNPRINTF
int snprintf (char *str, size_t count, const char *fmt, ...)
ATTRIBUTE_PRINTF(3,4);
#endif
#ifndef HAVE_VSNPRINTF
int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
#endif
#include
#include
typedef unsigned int UINT32;
typedef int INT32;
typedef unsigned short int UINT16;
typedef short int INT16;
typedef unsigned char UINT8;
typedef char INT8;
typedef char BOOL;
#ifndef MIN
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
void ne_vwarn (const char *fmt, va_list ap);
void ne_warn (const char *fmt, ...)
ATTRIBUTE_PRINTF(1,2);
void ne_set_log (int level);
void ne_log (int level, const char *fmt, ...)
ATTRIBUTE_PRINTF(2,3);
UINT32 python_string_hash (const char *s);
UINT8 *ne_stream4 (UINT8 *dest, UINT32 num);
UINT8 *ne_unstream4 (UINT32 *pnum, UINT8 *src);
UINT8 *ne_stream2 (UINT8 *dest, UINT16 num);
UINT8 *ne_unstream2 (UINT16 *pnum, UINT8 *src);
UINT8 *ne_stream_str (UINT8 *dest, const char *s, int l);
UINT8 *ne_unstream_str (char *s, int l, UINT8 *src);
double ne_timef (void);
UINT32 ne_crc (UINT8 *data, UINT32 bytes);
__END_DECLS
#endif /* __NEO_MISC_H_ */
clearsilver-0.10.5/util/neo_net.c 0000644 0012117 0011610 00000035122 10345210304 013567 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_net.h"
#include "neo_str.h"
static int ShutdownAccept = 0;
void ne_net_shutdown()
{
ShutdownAccept = 1;
}
/* Server side */
NEOERR *ne_net_listen(int port, int *fd)
{
int sfd = 0;
int on = 1;
/* int flags; */
struct sockaddr_in serv_addr;
if ((sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return nerr_raise_errno(NERR_IO, "Unable to create socket");
if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on,
sizeof(on)) == -1)
{
close(sfd);
return nerr_raise_errno(NERR_IO, "Unable to setsockopt(SO_REUSEADDR)");
}
if(setsockopt (sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
sizeof(on)) == -1)
{
close(sfd);
return nerr_raise_errno(NERR_IO, "Unable to setsockopt(SO_KEEPALIVE)");
}
if(setsockopt (sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&on,
sizeof(on)) == -1)
{
close(sfd);
return nerr_raise_errno(NERR_IO, "Unable to setsockopt(TCP_NODELAY)");
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
if (bind(sfd,(struct sockaddr *)&(serv_addr),sizeof(struct sockaddr)) == -1)
{
close(sfd);
return nerr_raise_errno(NERR_IO, "Unable to bind to port %d", port);
}
/* If set non-block, then we have to use select prior to accept...
* typically we don't, so we'll leave this out until we have a need
* for it and then figure out how to work it into the common code */
/*
flags = fcntl(sfd, F_GETFL, 0 );
if (flags == -1)
{
close(sfd);
return nerr_raise_errno(NERR_IO, "Unable to get socket flags for port %d",
port);
}
if (fcntl(sfd, F_SETFL, flags | O_NDELAY) == -1)
{
close(sfd);
return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY for port %d",
port);
}
*/
if (listen(sfd, 100) == -1)
{
close(sfd);
return nerr_raise_errno(NERR_IO, "Unable to listen on port %d", port);
}
*fd = sfd;
return STATUS_OK;
}
NEOERR *ne_net_accept(NSOCK **sock, int sfd, int data_timeout)
{
NSOCK *my_sock;
int fd;
struct sockaddr_in client_addr;
socklen_t len;
len = sizeof(struct sockaddr_in);
while (1)
{
fd = accept(sfd, (struct sockaddr *)&client_addr, &len);
if (fd >= 0) break;
if (ShutdownAccept || errno != EINTR)
{
return nerr_raise_errno(NERR_IO, "accept() returned error");
}
if (errno == EINTR)
{
ne_warn("accept received EINTR");
}
}
my_sock = (NSOCK *) calloc(1, sizeof(NSOCK));
if (my_sock == NULL)
{
close(fd);
return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NSOCK");
}
my_sock->fd = fd;
my_sock->remote_ip = ntohl(client_addr.sin_addr.s_addr);
my_sock->remote_port = ntohs(client_addr.sin_port);
my_sock->data_timeout = data_timeout;
*sock = my_sock;
return STATUS_OK;
}
/* Client side */
NEOERR *ne_net_connect(NSOCK **sock, const char *host, int port,
int conn_timeout, int data_timeout)
{
struct sockaddr_in serv_addr;
struct hostent hp;
struct hostent *php;
int fd;
int r = 0, x;
int flags;
struct timeval tv;
fd_set fds;
int optval;
socklen_t optlen;
NSOCK *my_sock;
/* FIXME: This isn't thread safe... but there's no man entry for the _r
* version? */
php = gethostbyname(host);
if (php == NULL)
{
return nerr_raise(NERR_IO, "Host not found: %s", hstrerror(h_errno));
}
hp = *php;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1)
return nerr_raise_errno(NERR_IO, "Unable to create socket");
flags = fcntl(fd, F_GETFL, 0 );
if (flags == -1)
{
close(fd);
return nerr_raise_errno(NERR_IO, "Unable to get socket flags");
}
if (fcntl(fd, F_SETFL, flags | O_NDELAY) == -1)
{
close(fd);
return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY");
}
x = 0;
while (hp.h_addr_list[x] != NULL)
{
memcpy(&(serv_addr.sin_addr), hp.h_addr_list[x], sizeof(struct in_addr));
errno = 0;
r = connect(fd, (struct sockaddr *) &(serv_addr), sizeof(struct sockaddr_in));
if (r == 0 || errno == EINPROGRESS) break;
x++;
}
if (r != 0)
{
if (errno != EINPROGRESS)
{
close(fd);
return nerr_raise_errno(NERR_IO, "Unable to connect to %s:%d",
host, port);
}
tv.tv_sec = conn_timeout;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(fd, &fds);
r = select(fd+1, NULL, &fds, NULL, &tv);
if (r == 0)
{
close(fd);
return nerr_raise(NERR_IO, "Connection to %s:%d failed: Timeout", host,
port);
}
if (r < 0)
{
close(fd);
return nerr_raise_errno(NERR_IO, "Connection to %s:%d failed", host,
port);
}
optlen = sizeof(optval);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1)
{
close(fd);
return nerr_raise_errno(NERR_IO,
"Unable to getsockopt to determine connection error");
}
if (optval)
{
close(fd);
errno = optval;
return nerr_raise_errno(NERR_IO, "Connection to %s:%d failed", host,
port);
}
}
/* Re-enable blocking... we'll use select on read/write for timeouts
* anyways, and if we want non-blocking version in the future we'll
* add a flag or something.
*/
flags = fcntl(fd, F_GETFL, 0 );
if (flags == -1)
{
close(fd);
return nerr_raise_errno(NERR_IO, "Unable to get socket flags");
}
if (fcntl(fd, F_SETFL, flags & ~O_NDELAY) == -1)
{
close(fd);
return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY");
}
my_sock = (NSOCK *) calloc(1, sizeof(NSOCK));
if (my_sock == NULL)
{
close(fd);
return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NSOCK");
}
my_sock->fd = fd;
my_sock->remote_ip = ntohl(serv_addr.sin_addr.s_addr);
my_sock->remote_port = port;
my_sock->data_timeout = data_timeout;
my_sock->conn_timeout = conn_timeout;
*sock = my_sock;
return STATUS_OK;
}
NEOERR *ne_net_close(NSOCK **sock)
{
NEOERR *err;
if (sock == NULL || *sock == NULL) return STATUS_OK;
err = ne_net_flush(*sock);
close((*sock)->fd);
free((*sock));
*sock = NULL;
return nerr_pass(err);
}
/* Low level data interface ... we are implementing a buffered stream
* here, and the fill and flush are designed for that. More over, our
* buffered stream assumes a certain type of protocol design where we
* flush the write buffer before reading... there are possible protocols
* where this would be grossly inefficient, but I don't expect to use
* anything like that */
/* Also, an annoyance here... what to do with the EOF case? Currently,
* we're just returing with a ol of 0, which means in most cases when
* calling this we have to check that case as well as standard errors.
* We could raise an NERR_EOF or something, but that seems like
* overkill. We should probably have a ret arg for the case... */
static NEOERR *ne_net_fill(NSOCK *sock)
{
NEOERR *err;
struct timeval tv;
fd_set fds;
int r;
/* Ok, we are assuming a model where one side of the connection is the
* consumer and the other the producer... and then it switches. So we
* flush the output buffer (if any) before we read */
if (sock->ol)
{
err = ne_net_flush(sock);
if (err) return nerr_pass(err);
}
/* Ok, we want connections to fail if they don't connect in
* conn_timeout... but with higher listen queues, the connection could
* actually connect, but the remote server won't get to it within the
* conn_timeout, we still want it to fail. We do that by using the
* conn_timeout on the first read ... this isn't quite the same as we
* might actually timeout at almost 2x conn_timeout (if we had to wait
* for connect and the first read) but its still better then waiting
* the full data timeout */
if (sock->conn_timeout)
{
tv.tv_sec = sock->conn_timeout;
sock->conn_timeout = 0;
}
else
{
tv.tv_sec = sock->data_timeout;
}
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(sock->fd, &fds);
r = select(sock->fd+1, &fds, NULL, NULL, &tv);
if (r == 0)
{
return nerr_raise(NERR_IO, "read failed: Timeout");
}
if (r < 0)
{
return nerr_raise_errno(NERR_IO, "select for read failed");
}
sock->ibuf[0] = '\0';
r = read(sock->fd, sock->ibuf, NET_BUFSIZE);
if (r < 0)
{
return nerr_raise_errno(NERR_IO, "read failed");
}
sock->ib = 0;
sock->il = r;
return STATUS_OK;
}
NEOERR *ne_net_flush(NSOCK *sock)
{
fd_set fds;
struct timeval tv;
int r;
int x = 0;
if (sock->conn_timeout)
{
tv.tv_sec = sock->conn_timeout;
}
else
{
tv.tv_sec = sock->data_timeout;
}
tv.tv_usec = 0;
x = 0;
while (x < sock->ol)
{
FD_ZERO(&fds);
FD_SET(sock->fd, &fds);
r = select(sock->fd+1, NULL, &fds, NULL, &tv);
if (r == 0)
{
return nerr_raise(NERR_IO, "write failed: Timeout");
}
if (r < 0)
{
return nerr_raise_errno(NERR_IO, "select for write failed");
}
r = write(sock->fd, sock->obuf + x, sock->ol - x);
if (r < 0)
{
return nerr_raise_errno(NERR_IO, "select for write failed");
}
x += r;
}
sock->ol = 0;
return STATUS_OK;
}
/* hmm, we may need something to know how much we've read here... */
NEOERR *ne_net_read(NSOCK *sock, UINT8 *buf, int buflen)
{
NEOERR *err;
int x = 0;
int l;
x = buflen;
while (x > 0)
{
if (sock->il - sock->ib > 0)
{
if (sock->ib + x <= sock->il)
l = x;
else
l = sock->il - sock->ib;
memcpy(buf + buflen - x, sock->ibuf + sock->ib, l);
sock->ib += l;
x -= l;
}
else
{
err = ne_net_fill(sock);
if (err) return nerr_pass(err);
if (sock->il == 0) return STATUS_OK;
}
}
return STATUS_OK;
}
NEOERR *ne_net_read_line(NSOCK *sock, char **buf)
{
NEOERR *err;
STRING str;
UINT8 *nl;
int l;
string_init(&str);
while (1)
{
if (sock->il - sock->ib > 0)
{
nl = memchr(sock->ibuf + sock->ib, '\n', sock->il - sock->ib);
if (nl == NULL)
{
l = sock->il - sock->ib;
err = string_appendn(&str, (char *)(sock->ibuf + sock->ib), l);
sock->ib += l;
if (err) break;
}
else
{
l = nl - (sock->ibuf + sock->ib);
err = string_appendn(&str, (char *)(sock->ibuf + sock->ib), l);
sock->ib += l;
if (err) break;
*buf = str.buf;
return STATUS_OK;
}
}
else
{
err = ne_net_fill(sock);
if (err) break;
if (sock->il == 0) return STATUS_OK;
}
}
string_clear(&str);
return nerr_pass(err);
}
static NEOERR *_ne_net_read_int(NSOCK *sock, int *i, char end)
{
NEOERR *err;
int x = 0;
char buf[32];
char *ep = NULL;
while (x < sizeof(buf))
{
while (sock->il - sock->ib > 0)
{
buf[x] = sock->ibuf[sock->ib++];
if (buf[x] == end) break;
x++;
if (x == sizeof(buf)) break;
}
if (buf[x] == end) break;
err = ne_net_fill(sock);
if (err) return nerr_pass(err);
if (sock->il == 0) return STATUS_OK;
}
if (x == sizeof(buf))
return nerr_raise(NERR_PARSE, "Format error on stream, expected '%c'", end);
buf[x] = '\0';
*i = strtol(buf, &ep, 10);
if (ep && *ep)
{
return nerr_raise(NERR_PARSE, "Format error on stream, expected number followed by '%c'", end);
}
return STATUS_OK;
}
NEOERR *ne_net_read_binary(NSOCK *sock, UINT8 **b, int *blen)
{
NEOERR *err;
UINT8 *data;
UINT8 buf[5];
int l;
err = _ne_net_read_int(sock, &l, ':');
if (err) return nerr_pass(err);
/* Special case to read a NULL */
if (l < 0)
{
*b = NULL;
if (blen != NULL) *blen = l;
return STATUS_OK;
}
data = (UINT8 *) malloc(l + 1);
if (data == NULL)
{
/* We might want to clear the incoming data here... */
return nerr_raise(NERR_NOMEM,
"Unable to allocate memory for binary data %d" , l);
}
err = ne_net_read(sock, data, l);
if (err)
{
free(data);
return nerr_pass(err);
}
/* check for comma separator */
err = ne_net_read(sock, buf, 1);
if (err)
{
free(data);
return nerr_pass(err);
}
if (buf[0] != ',')
{
free(data);
return nerr_raise(NERR_PARSE, "Format error on stream, expected ','");
}
*b = data;
if (blen != NULL) *blen = l;
return STATUS_OK;
}
NEOERR *ne_net_read_str_alloc(NSOCK *sock, char **s, int *len)
{
NEOERR *err;
int l;
/* just use the binary read and null terminate the string... */
err = ne_net_read_binary(sock, (UINT8 **)s, &l);
if (err) return nerr_pass(err);
if (*s != NULL)
{
(*s)[l] = '\0';
}
if (len != NULL) *len = l;
return STATUS_OK;
}
NEOERR *ne_net_read_int(NSOCK *sock, int *i)
{
return nerr_pass(_ne_net_read_int(sock, i, ','));
}
NEOERR *ne_net_write(NSOCK *sock, const char *b, int blen)
{
NEOERR *err;
int x = 0;
int l;
x = blen;
while (x > 0)
{
if (sock->ol < NET_BUFSIZE)
{
if (sock->ol + x <= NET_BUFSIZE)
{
l = x;
}
else
{
l = NET_BUFSIZE - sock->ol;
}
memcpy(sock->obuf + sock->ol, b + blen - x, l);
sock->ol += l;
x -= l;
}
else
{
err = ne_net_flush(sock);
if (err) return nerr_pass(err);
}
}
return STATUS_OK;
}
NEOERR *ne_net_write_line(NSOCK *sock, const char *s)
{
NEOERR *err;
err = ne_net_write(sock, s, strlen(s));
if (err) return nerr_pass(err);
err = ne_net_write(sock, "\n", 1);
if (err) return nerr_pass(err);
return STATUS_OK;
}
NEOERR *ne_net_write_binary(NSOCK *sock, const char *b, int blen)
{
NEOERR *err;
char buf[32];
if (b == NULL) blen = -1;
snprintf(buf, sizeof(buf), "%d:", blen);
err = ne_net_write(sock, buf, strlen(buf));
if (err) return nerr_pass(err);
if (blen > 0)
{
err = ne_net_write(sock, b, blen);
if (err) return nerr_pass(err);
}
err = ne_net_write(sock, ",", 1);
if (err) return nerr_pass(err);
return STATUS_OK;
}
NEOERR *ne_net_write_str(NSOCK *sock, const char *s)
{
NEOERR *err;
if (s == NULL)
err = ne_net_write_binary(sock, s, -1);
else
err = ne_net_write_binary(sock, s, strlen(s));
return nerr_pass(err);
}
NEOERR *ne_net_write_int(NSOCK *sock, int i)
{
char buf[32];
snprintf(buf, sizeof(buf), "%d,", i);
return nerr_pass(ne_net_write(sock, buf, strlen(buf)));
}
clearsilver-0.10.5/util/neo_net.h 0000644 0012117 0011610 00000002746 10345210356 013611 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_NET_H_
#define __NEO_NET_H_ 1
__BEGIN_DECLS
#define NET_BUFSIZE 4096
typedef struct _neo_sock {
int fd;
int data_timeout;
int conn_timeout;
UINT32 remote_ip;
int remote_port;
/* incoming buffer */
UINT8 ibuf[NET_BUFSIZE];
int ib;
int il;
/* outbound buffer */
UINT8 obuf[NET_BUFSIZE];
int ol;
} NSOCK;
NEOERR *ne_net_listen(int port, int *fd);
NEOERR *ne_net_accept(NSOCK **sock, int fd, int data_timeout);
NEOERR *ne_net_connect(NSOCK **sock, const char *host, int port,
int conn_timeout, int data_timeout);
NEOERR *ne_net_close(NSOCK **sock);
NEOERR *ne_net_read(NSOCK *sock, UINT8 *buf, int buflen);
NEOERR *ne_net_read_line(NSOCK *sock, char **buf);
NEOERR *ne_net_read_binary(NSOCK *sock, UINT8 **b, int *blen);
NEOERR *ne_net_read_str_alloc(NSOCK *sock, char **s, int *len);
NEOERR *ne_net_read_int(NSOCK *sock, int *i);
NEOERR *ne_net_write(NSOCK *sock, const char *b, int blen);
NEOERR *ne_net_write_line(NSOCK *sock, const char *s);
NEOERR *ne_net_write_binary(NSOCK *sock, const char *b, int blen);
NEOERR *ne_net_write_str(NSOCK *sock, const char *s);
NEOERR *ne_net_write_int(NSOCK *sock, int i);
NEOERR *ne_net_flush(NSOCK *sock);
void ne_net_shutdown(void);
__END_DECLS
#endif /* __NEO_NET_H_ */
clearsilver-0.10.5/util/neo_rand.c 0000644 0012117 0011610 00000003623 10261042052 013726 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_rand.h"
#include "ulist.h"
static int RandomInit = 0;
void neo_seed_rand (long int seed)
{
#ifdef HAVE_DRAND48
srand48(seed);
#elif HAVE_RANDOM
srandom(seed);
#else
srand(seed);
#endif
RandomInit = 1;
}
int neo_rand (int max)
{
int r;
if (RandomInit == 0)
{
neo_seed_rand (time(NULL));
}
#ifdef HAVE_DRAND48
r = drand48() * max;
#elif HAVE_RANDOM
r = random() * max;
#else
r = rand() * max;
#endif
return r;
}
int neo_rand_string (char *s, int max)
{
int size;
int x = 0;
size = neo_rand(max-1);
for (x = 0; x < size; x++)
{
s[x] = (char)(32 + neo_rand(127-32));
if (s[x] == '/') s[x] = ' ';
}
s[x] = '\0';
return 0;
}
static ULIST *Words = NULL;
int neo_rand_word (char *s, int max)
{
NEOERR *err;
int x;
char *word;
if (Words == NULL)
{
FILE *fp;
char buf[256];
err = uListInit(&Words, 40000, 0);
if (err)
{
nerr_log_error(err);
return -1;
}
fp = fopen ("/usr/dict/words", "r");
if (fp == NULL) {
fp = fopen ("/usr/share/dict/words", "r");
if (fp == NULL) {
ne_warn("Unable to find dict/words file (looked in /usr/dict/words and /usr/share/dict/words)");
return -1;
}
}
while (fgets (buf, sizeof(buf), fp) != NULL)
{
x = strlen (buf);
if (buf[x-1] == '\n')
buf[x-1] = '\0';
uListAppend(Words, strdup(buf));
}
fclose (fp);
}
x = neo_rand (uListLength(Words));
uListGet(Words, x, (void *)&word);
strncpy (s, word, max);
s[max-1] = '\0';
return 0;
}
clearsilver-0.10.5/util/neo_rand.h 0000644 0012117 0011610 00000000726 10261037520 013740 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_RAND_H_
#define __NEO_RAND_H_ 1
__BEGIN_DECLS
void neo_seed_rand (long int seed);
int neo_rand (int max);
int neo_rand_string (char *s, int slen);
int neo_rand_word (char *s, int slen);
__END_DECLS
#endif /* __NEO_RAND_H_ */
clearsilver-0.10.5/util/neo_server.c 0000644 0012117 0011610 00000011374 10261037520 014316 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
/* Initial version based on multi-proc based server (like apache 1.x)
*
* Parts are:
* 1) server Init
* 2) sub-proc start
* 3) sub-proc init
* 4) sub-proc process request
* 5) sub-proc cleanup
* 6) server cleanup
*
* Parts 1 & 6 aren't part of the framework, and at this point, I don't
* think I need to worry about 3 & 5 either, but maybe in the future.
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_net.h"
#include "ulocks.h"
#include "neo_server.h"
static NEOERR *nserver_child_loop(NSERVER *server, int num)
{
NEOERR *err = STATUS_OK, *clean_err;
int loop = 0;
NSOCK *child_sock;
if (server->init_cb)
{
err = server->init_cb(server->data, num);
if (err) return nerr_pass(err);
}
while (loop++ < server->num_requests)
{
err = fLock(server->accept_lock);
if (err) break;
err = ne_net_accept(&child_sock, server->server_fd, server->data_timeout);
fUnlock(server->accept_lock);
if (err) break;
err = server->req_cb(server->data, num, child_sock);
if (err)
{
ne_net_close(&child_sock);
}
else
{
err = ne_net_close(&child_sock);
}
nerr_log_error(err);
nerr_ignore(&err);
}
ne_warn("nserver child loop handled %d connections", loop-1);
if (server->clean_cb)
{
clean_err = server->clean_cb(server->data, num);
if (clean_err)
{
nerr_log_error(clean_err);
nerr_ignore(&clean_err);
}
}
return nerr_pass(err);
}
static void ignore_pipe(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sigaction(SIGPIPE, &sa, NULL);
}
/* Handle shutdown by accepting a TERM signal and then passing it to our
* program group */
static int ShutdownPending = 0;
static void sig_term(int sig)
{
ShutdownPending = 1;
ne_net_shutdown();
}
static void setup_term(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sig_term;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
}
NEOERR *nserver_proc_start(NSERVER *server, BOOL debug)
{
NEOERR *err;
if (server->req_cb == NULL)
return nerr_raise(NERR_ASSERT, "nserver requires a request callback");
ignore_pipe();
setup_term();
ShutdownPending = 0;
err = fFind(&(server->accept_lock), server->lockfile);
if (err && nerr_handle(&err, NERR_NOT_FOUND))
{
err = fCreate(&(server->accept_lock), server->lockfile);
}
if (err) return nerr_pass(err);
do
{
err = ne_net_listen(server->port, &(server->server_fd));
if (err) break;
if (debug == TRUE)
{
err = nserver_child_loop(server, 0);
break;
}
else
{
/* create children and restart them as necessary */
pid_t child;
int count, status;
for (count = 0; count < server->num_children; count++)
{
child = fork();
if (child == -1)
{
err = nerr_raise_errno(NERR_SYSTEM, "Unable to fork child");
break;
}
if (!child)
{
err = nserver_child_loop(server, count);
if (err) exit(-1);
exit(0);
}
ne_warn("Starting child pid %d", child);
}
if (count < server->num_children) break;
while (!ShutdownPending)
{
child = wait3(&status, 0, NULL);
if (child == -1)
{
ne_warn("wait3 failed [%d] %s", errno, strerror(errno));
continue;
}
if (WIFSTOPPED(status))
{
ne_warn("pid %d stopped on signal %d", child, WSTOPSIG(status));
continue;
}
if (WIFEXITED(status))
{
/* at some point, we might do something here with the
* particular exit value */
ne_warn("pid %d exited, returned %d", child, WEXITSTATUS(status));
}
else if (WIFSIGNALED(status))
{
ne_warn("pid %d exited on signal %d", child, WTERMSIG(status));
}
count++;
child = fork();
if (child == -1)
{
err = nerr_raise_errno(NERR_SYSTEM, "Unable to fork child");
break;
}
if (!child)
{
err = nserver_child_loop(server, count);
if (err) exit(-1);
exit(0);
}
ne_warn("Starting child pid %d", child);
}
/* At some point, we might want to actually maintain information
* on our children, and then we can be more specific here in terms
* of making sure they all shutdown... for now, fergitaboutit */
if (ShutdownPending)
{
killpg(0, SIGTERM);
}
}
}
while (0);
fDestroy(server->accept_lock);
return nerr_pass(err);
}
clearsilver-0.10.5/util/neo_server.h 0000644 0012117 0011610 00000001637 10261037520 014324 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_SERVER_H_
#define __NEO_SERVER_H_ 1
__BEGIN_DECLS
/* hmm, this callback might need a mechanism for telling the child to
* end... */
typedef NEOERR *(*NSERVER_REQ_CB)(void *rock, int num, NSOCK *sock);
typedef NEOERR *(*NSERVER_CB)(void *rock, int num);
typedef struct _nserver {
/* callbacks */
NSERVER_CB init_cb;
NSERVER_REQ_CB req_cb;
NSERVER_CB clean_cb;
void *data;
int num_children;
int num_requests;
int port;
int conn_timeout;
int data_timeout;
char lockfile[_POSIX_PATH_MAX];
/* Internal data */
int accept_lock;
int server_fd;
} NSERVER;
NEOERR *nserver_proc_start(NSERVER *server, BOOL debug);
__END_DECLS
#endif /* __NEO_SERVER_H_ */
clearsilver-0.10.5/util/neo_str.c 0000644 0012117 0011610 00000043611 10645301260 013620 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "neo_str.h"
#include "ulist.h"
#ifndef va_copy
#ifdef __va_copy
# define va_copy(dest,src) __va_copy(dest,src)
#else
# define va_copy(dest,src) ((dest) = (src))
#endif
#endif
char *neos_strip (char *s)
{
int x;
x = strlen(s) - 1;
while (x>=0 && isspace(s[x])) s[x--] = '\0';
while (*s && isspace(*s)) s++;
return s;
}
char *neos_rstrip (char *s)
{
int n = strlen (s)-1;
while (n >= 0 && isspace(s[n]))
{
s[n] = '\0';
n--;
}
return s;
}
void neos_lower(char *s)
{
while(*s != 0) {
*s = tolower(*s);
s++;
}
}
void string_init (STRING *str)
{
str->buf = NULL;
str->len = 0;
str->max = 0;
}
void string_clear (STRING *str)
{
if (str->buf != NULL)
free(str->buf);
string_init(str);
}
static NEOERR* string_check_length (STRING *str, int l)
{
if (str->buf == NULL)
{
if (l * 10 > 256)
str->max = l * 10;
else
str->max = 256;
str->buf = (char *) malloc (sizeof(char) * str->max);
if (str->buf == NULL)
return nerr_raise (NERR_NOMEM, "Unable to allocate render buf of size %d",
str->max);
/* ne_warn("Creating string %x at %d (%5.2fK)", str, str->max, (str->max / 1024.0)); */
}
else if (str->len + l >= str->max)
{
do
{
str->max *= 2;
} while (str->len + l >= str->max);
str->buf = (char *) realloc (str->buf, sizeof(char) * str->max);
if (str->buf == NULL)
return nerr_raise (NERR_NOMEM, "Unable to allocate STRING buf of size %d",
str->max);
/* ne_warn("Growing string %x to %d (%5.2fK)", str, str->max, (str->max / 1024.0)); */
}
return STATUS_OK;
}
NEOERR *string_set (STRING *str, const char *buf)
{
str->len = 0;
return nerr_pass (string_append (str, buf));
}
NEOERR *string_append (STRING *str, const char *buf)
{
NEOERR *err;
int l;
l = strlen(buf);
err = string_check_length (str, l);
if (err != STATUS_OK) return nerr_pass (err);
strcpy(str->buf + str->len, buf);
str->len += l;
return STATUS_OK;
}
NEOERR *string_appendn (STRING *str, const char *buf, int l)
{
NEOERR *err;
err = string_check_length (str, l+1);
if (err != STATUS_OK) return nerr_pass (err);
memcpy(str->buf + str->len, buf, l);
str->len += l;
str->buf[str->len] = '\0';
return STATUS_OK;
}
/* this is much more efficient with C99 snprintfs... */
NEOERR *string_appendvf (STRING *str, const char *fmt, va_list ap)
{
NEOERR *err;
char buf[4096];
int bl, size;
va_list tmp;
va_copy(tmp, ap);
/* determine length */
size = sizeof (buf);
bl = vsnprintf (buf, size, fmt, tmp);
if (bl > -1 && bl < size)
return string_appendn (str, buf, bl);
/* Handle non-C99 snprintfs (requires extra malloc/free and copy) */
if (bl == -1)
{
char *a_buf;
va_copy(tmp, ap);
a_buf = vnsprintf_alloc(size*2, fmt, tmp);
if (a_buf == NULL)
return nerr_raise(NERR_NOMEM,
"Unable to allocate memory for formatted string");
err = string_append(str, a_buf);
free(a_buf);
return nerr_pass(err);
}
err = string_check_length (str, bl+1);
if (err != STATUS_OK) return nerr_pass (err);
va_copy(tmp, ap);
vsprintf (str->buf + str->len, fmt, tmp);
str->len += bl;
str->buf[str->len] = '\0';
return STATUS_OK;
}
NEOERR *string_appendf (STRING *str, const char *fmt, ...)
{
NEOERR *err;
va_list ap;
va_start (ap, fmt);
err = string_appendvf (str, fmt, ap);
va_end (ap);
return nerr_pass(err);
}
NEOERR *string_append_char (STRING *str, char c)
{
NEOERR *err;
err = string_check_length (str, 1);
if (err != STATUS_OK) return nerr_pass (err);
str->buf[str->len] = c;
str->buf[str->len + 1] = '\0';
str->len += 1;
return STATUS_OK;
}
void string_array_init (STRING_ARRAY *arr)
{
arr->entries = NULL;
arr->count = 0;
arr->max = 0;
}
NEOERR *string_array_split (ULIST **list, char *s, const char *sep,
int max)
{
NEOERR *err;
char *p, *n, *f;
int sl;
int x = 0;
if (sep[0] == '\0')
return nerr_raise (NERR_ASSERT, "separator must be at least one character");
err = uListInit (list, 10, 0);
if (err) return nerr_pass(err);
sl = strlen(sep);
p = (sl == 1) ? strchr (s, sep[0]) : strstr (s, sep);
f = s;
while (p != NULL)
{
if (x >= max) break;
*p = '\0';
n = strdup(f);
*p = sep[0];
if (n) err = uListAppend (*list, n);
else err = nerr_raise(NERR_NOMEM,
"Unable to allocate memory to split %s", s);
if (err) goto split_err;
f = p+sl;
p = (sl == 1) ? strchr (f, sep[0]) : strstr (f, sep);
x++;
}
/* Handle remainder */
n = strdup(f);
if (n) err = uListAppend (*list, n);
else err = nerr_raise(NERR_NOMEM,
"Unable to allocate memory to split %s", s);
if (err) goto split_err;
return STATUS_OK;
split_err:
uListDestroy(list, ULIST_FREE);
return err;
}
void string_array_clear (STRING_ARRAY *arr)
{
int x;
for (x = 0; x < arr->count; x++)
{
if (arr->entries[x] != NULL) free (arr->entries[x]);
arr->entries[x] = NULL;
}
free (arr->entries);
arr->entries = NULL;
arr->count = 0;
}
/* Mostly used by vprintf_alloc for non-C99 compliant snprintfs,
* this is like vsprintf_alloc except it takes a "suggested" size */
int vnisprintf_alloc (char **buf, int start_size, const char *fmt, va_list ap)
{
int bl, size;
va_list tmp;
*buf = NULL;
size = start_size;
*buf = (char *) malloc (size * sizeof(char));
if (*buf == NULL) return 0;
while (1)
{
va_copy(tmp, ap);
bl = vsnprintf (*buf, size, fmt, tmp);
if (bl > -1 && bl < size)
return bl;
if (bl > -1)
size = bl + 1;
else
size *= 2;
*buf = (char *) realloc (*buf, size * sizeof(char));
if (*buf == NULL) return 0;
}
}
char *vnsprintf_alloc (int start_size, const char *fmt, va_list ap)
{
char *r;
vnisprintf_alloc(&r, start_size, fmt, ap);
return r;
}
/* This works better with a C99 compliant vsnprintf, but should work ok
* with versions that return a -1 if it overflows the buffer */
int visprintf_alloc (char **buf, const char *fmt, va_list ap)
{
char ibuf[4096];
int bl, size;
va_list tmp;
/* PPC doesn't like you re-using a va_list... and it might not be
* supposed to work at all */
va_copy(tmp, ap);
size = sizeof (ibuf);
bl = vsnprintf (ibuf, sizeof (ibuf), fmt, tmp);
if (bl > -1 && bl < size)
{
*buf = (char *) calloc(bl+1, sizeof(char));
if (*buf == NULL) return 0;
strncpy(*buf, ibuf, bl);
return bl;
}
if (bl > -1)
size = bl + 1;
else
size *= 2;
return vnisprintf_alloc(buf, size, fmt, ap);
}
char *vsprintf_alloc (const char *fmt, va_list ap)
{
char *r;
visprintf_alloc(&r, fmt, ap);
return r;
}
/* technically, sprintf's can have null values, so we need to be able to
* return a length also like real sprintf */
int isprintf_alloc (char **buf, const char *fmt, ...)
{
va_list ap;
int r;
va_start (ap, fmt);
r = visprintf_alloc (buf, fmt, ap);
va_end (ap);
return r;
}
char *sprintf_alloc (const char *fmt, ...)
{
va_list ap;
char *r;
va_start (ap, fmt);
r = vsprintf_alloc (fmt, ap);
va_end (ap);
return r;
}
/* This is mostly just here for completeness, I doubt anyone would use
* this (its more efficient (time-wise) if start_size is bigger than the
* resulting string. Its less efficient than sprintf_alloc if we have a
* C99 snprintf and it doesn't fit in start_size.
* BTW: If you are really worried about the efficiency of these
* functions, maybe you shouldn't be using them in the first place... */
char *nsprintf_alloc (int start_size, const char *fmt, ...)
{
va_list ap;
char *r;
va_start (ap, fmt);
r = vnsprintf_alloc (start_size, fmt, ap);
va_end (ap);
return r;
}
BOOL reg_search (const char *re, const char *str)
{
regex_t search_re;
int errcode;
char buf[256];
if ((errcode = regcomp(&search_re, re, REG_ICASE | REG_EXTENDED | REG_NOSUB)))
{
regerror (errcode, &search_re, buf, sizeof(buf));
ne_warn ("Unable to compile regex %s: %s", re, buf);
return FALSE;
}
errcode = regexec (&search_re, str, 0, NULL, 0);
regfree (&search_re);
if (errcode == 0)
return TRUE;
return FALSE;
}
NEOERR *string_readline (STRING *str, FILE *fp)
{
NEOERR *err;
/* minimum size for a readline is 256 above current position */
err = string_check_length (str, str->len + 256);
if (err != STATUS_OK) return nerr_pass (err);
while (fgets(str->buf + str->len, str->max - str->len, fp) != NULL)
{
str->len = strlen(str->buf);
if (str->buf[str->len-1] == '\n') break;
err = string_check_length (str, str->len + 256);
if (err != STATUS_OK) return nerr_pass (err);
}
return STATUS_OK;
}
NEOERR* neos_escape(UINT8 *buf, int buflen, char esc_char, const char *escape,
char **esc)
{
int nl = 0;
int l = 0;
int x = 0;
char *s;
int match = 0;
while (l < buflen)
{
if (buf[l] == esc_char)
{
nl += 2;
}
else
{
x = 0;
while (escape[x])
{
if (escape[x] == buf[l])
{
nl +=2;
break;
}
x++;
}
}
nl++;
l++;
}
s = (char *) malloc (sizeof(char) * (nl + 1));
if (s == NULL)
return nerr_raise (NERR_NOMEM, "Unable to allocate memory to escape %s",
buf);
nl = 0; l = 0;
while (l < buflen)
{
match = 0;
if (buf[l] == esc_char)
{
match = 1;
}
else
{
x = 0;
while (escape[x])
{
if (escape[x] == buf[l])
{
match = 1;
break;
}
x++;
}
}
if (match)
{
s[nl++] = esc_char;
s[nl++] = "0123456789ABCDEF"[buf[l] / 16];
s[nl++] = "0123456789ABCDEF"[buf[l] % 16];
l++;
}
else
{
s[nl++] = buf[l++];
}
}
s[nl] = '\0';
*esc = s;
return STATUS_OK;
}
UINT8 *neos_unescape (UINT8 *s, int buflen, char esc_char)
{
int i = 0, o = 0;
if (s == NULL) return s;
while (i < buflen)
{
if (s[i] == esc_char && (i+2 < buflen) &&
isxdigit(s[i+1]) && isxdigit(s[i+2]))
{
UINT8 num;
num = (s[i+1] >= 'A') ? ((s[i+1] & 0xdf) - 'A') + 10 : (s[i+1] - '0');
num *= 16;
num += (s[i+2] >= 'A') ? ((s[i+2] & 0xdf) - 'A') + 10 : (s[i+2] - '0');
s[o++] = num;
i+=3;
}
else {
s[o++] = s[i++];
}
}
if (i && o) s[o] = '\0';
return s;
}
char *repr_string_alloc (const char *s)
{
int l,x,i;
int nl = 0;
char *rs;
if (s == NULL)
{
return strdup("NULL");
}
l = strlen(s);
for (x = 0; x < l; x++)
{
if (isprint(s[x]) && s[x] != '"' && s[x] != '\\')
{
nl++;
}
else
{
if (s[x] == '\n' || s[x] == '\t' || s[x] == '\r' || s[x] == '"' ||
s[x] == '\\')
{
nl += 2;
}
else nl += 4;
}
}
rs = (char *) malloc ((nl+3) * sizeof(char));
if (rs == NULL)
return NULL;
i = 0;
rs[i++] = '"';
for (x = 0; x < l; x++)
{
if (isprint(s[x]) && s[x] != '"' && s[x] != '\\')
{
rs[i++] = s[x];
}
else
{
rs[i++] = '\\';
switch (s[x])
{
case '\n':
rs[i++] = 'n';
break;
case '\t':
rs[i++] = 't';
break;
case '\r':
rs[i++] = 'r';
break;
case '"':
rs[i++] = '"';
break;
case '\\':
rs[i++] = '\\';
break;
default:
sprintf(&(rs[i]), "%03o", (s[x] & 0377));
i += 3;
break;
}
}
}
rs[i++] = '"';
rs[i] = '\0';
return rs;
}
// List of all characters that must be escaped
// List based on http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
static char EscapedChars[] = "$&+,/:;=?@ \"<>#%{}|\\^~[]`'";
// Check if a single character needs to be escaped
static BOOL is_reserved_char(char c)
{
int i = 0;
if (c < 32 || c > 122) {
return TRUE;
} else {
while (EscapedChars[i]) {
if (c == EscapedChars[i]) {
return TRUE;
}
++i;
}
}
return FALSE;
}
NEOERR *neos_js_escape (const char *in, char **esc)
{
int nl = 0;
int l = 0;
unsigned char *buf = (unsigned char *)in;
unsigned char *s;
while (buf[l])
{
if (buf[l] == '/' || buf[l] == '"' || buf[l] == '\'' ||
buf[l] == '\\' || buf[l] == '>' || buf[l] == '<' ||
buf[l] == '&' || buf[l] == ';' || buf[l] < 32)
{
nl += 3;
}
nl++;
l++;
}
s = (unsigned char *) malloc (sizeof(unsigned char) * (nl + 1));
if (s == NULL)
return nerr_raise (NERR_NOMEM, "Unable to allocate memory to escape %s",
buf);
nl = 0; l = 0;
while (buf[l])
{
if (buf[l] == '/' || buf[l] == '"' || buf[l] == '\'' ||
buf[l] == '\\' || buf[l] == '>' || buf[l] == '<' ||
buf[l] == '&' || buf[l] == ';' || buf[l] < 32)
{
s[nl++] = '\\';
s[nl++] = 'x';
s[nl++] = "0123456789ABCDEF"[(buf[l] >> 4) & 0xF];
s[nl++] = "0123456789ABCDEF"[buf[l] & 0xF];
l++;
}
else
{
s[nl++] = buf[l++];
}
}
s[nl] = '\0';
*esc = (char *)s;
return STATUS_OK;
}
NEOERR *neos_url_escape (const char *in, char **esc,
const char *other)
{
int nl = 0;
int l = 0;
int x = 0;
unsigned char *buf = (unsigned char *)in;
unsigned char *uother = (unsigned char *)other;
unsigned char *s;
int match = 0;
while (buf[l])
{
if (is_reserved_char(buf[l]))
{
nl += 2;
}
else if (uother)
{
x = 0;
while (uother[x])
{
if (uother[x] == buf[l])
{
nl +=2;
break;
}
x++;
}
}
nl++;
l++;
}
s = (unsigned char *) malloc (sizeof(unsigned char) * (nl + 1));
if (s == NULL)
return nerr_raise (NERR_NOMEM, "Unable to allocate memory to escape %s",
buf);
nl = 0; l = 0;
while (buf[l])
{
match = 0;
if (buf[l] == ' ')
{
s[nl++] = '+';
l++;
}
else
{
if (is_reserved_char(buf[l]))
{
match = 1;
}
else if (uother)
{
x = 0;
while (uother[x])
{
if (uother[x] == buf[l])
{
match = 1;
break;
}
x++;
}
}
if (match)
{
s[nl++] = '%';
s[nl++] = "0123456789ABCDEF"[buf[l] / 16];
s[nl++] = "0123456789ABCDEF"[buf[l] % 16];
l++;
}
else
{
s[nl++] = buf[l++];
}
}
}
s[nl] = '\0';
*esc = (char *)s;
return STATUS_OK;
}
NEOERR *neos_html_escape (const char *src, int slen,
char **out)
{
NEOERR *err = STATUS_OK;
STRING out_s;
int x;
char *ptr;
string_init(&out_s);
err = string_append (&out_s, "");
if (err) return nerr_pass (err);
*out = NULL;
x = 0;
while (x < slen)
{
ptr = strpbrk(src + x, "&<>\"'\r");
if (ptr == NULL || (ptr-src >= slen))
{
err = string_appendn (&out_s, src + x, slen-x);
x = slen;
}
else
{
err = string_appendn (&out_s, src + x, (ptr - src) - x);
if (err != STATUS_OK) break;
x = ptr - src;
if (src[x] == '&')
err = string_append (&out_s, "&");
else if (src[x] == '<')
err = string_append (&out_s, "<");
else if (src[x] == '>')
err = string_append (&out_s, ">");
else if (src[x] == '"')
err = string_append (&out_s, """);
else if (src[x] == '\'')
err = string_append (&out_s, "'");
else if (src[x] != '\r')
err = nerr_raise (NERR_ASSERT, "src[x] == '%c'", src[x]);
x++;
}
if (err != STATUS_OK) break;
}
if (err)
{
string_clear (&out_s);
return nerr_pass (err);
}
*out = out_s.buf;
return STATUS_OK;
}
char *URL_PROTOCOLS[] = {"http://", "https://", "ftp://", "mailto:"};
NEOERR *neos_url_validate (const char *in, char **esc)
{
NEOERR *err = STATUS_OK;
STRING out_s;
int valid = 0;
size_t i;
size_t inlen;
int num_protocols = sizeof(URL_PROTOCOLS) / sizeof(char*);
void* slashpos;
void* colonpos;
inlen = strlen(in);
/*
* or are allowed by browsers
* and ":" is treated as part of the path, while
* is an invalid url
* and ":" is treated as a scheme separator.
*
* Hence allow for ":" in the path part of a url (after /)
*/
slashpos = memchr(in, '/', inlen);
if (slashpos == NULL) {
i = inlen;
}
else {
i = (size_t)((char*)slashpos - in);
}
colonpos = memchr(in, ':', i);
if (colonpos == NULL) {
// no scheme in 'in': so this is a relative url
valid = 1;
}
else {
for (i = 0; i < num_protocols; i++)
{
if ((inlen >= strlen(URL_PROTOCOLS[i])) &&
strncmp(in, URL_PROTOCOLS[i], strlen(URL_PROTOCOLS[i])) == 0) {
// 'in' starts with one of the allowed protocols
valid = 1;
break;
}
}
}
if (valid)
return neos_html_escape(in, inlen, esc);
// 'in' contains an unsupported scheme, replace with '#'
string_init(&out_s);
err = string_append (&out_s, "#");
if (err) return nerr_pass (err);
*esc = out_s.buf;
return STATUS_OK;
}
NEOERR *neos_var_escape (NEOS_ESCAPE context,
const char *in,
char **esc)
{
/* Just dup and return if we do nothing. */
if (context == NEOS_ESCAPE_NONE ||
context == NEOS_ESCAPE_FUNCTION)
{
*esc = strdup(in);
return STATUS_OK;
}
/* Now we escape based on context. This is the order of precedence:
* url > script > style > html
*/
if (context & NEOS_ESCAPE_URL)
return nerr_pass(neos_url_escape(in, esc, NULL));
else if (context & NEOS_ESCAPE_SCRIPT)
return nerr_pass(neos_js_escape(in, esc));
else if (context & NEOS_ESCAPE_HTML)
return nerr_pass(neos_html_escape(in, strlen(in), esc));
return nerr_raise(NERR_ASSERT, "unknown escape context supplied: %d",
context);
}
clearsilver-0.10.5/util/neo_str.h 0000644 0012117 0011610 00000007064 10645311453 013634 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
#ifndef __NEO_STR_H_
#define __NEO_STR_H_ 1
__BEGIN_DECLS
#include
#include
#include "util/neo_misc.h"
/* This modifies the string its called with by replacing all the white
* space on the end with \0, and returns a pointer to the first
* non-white space character in the string
*/
char *neos_strip (char *s);
void neos_lower (char *s);
char *sprintf_alloc (const char *fmt, ...) ATTRIBUTE_PRINTF(1,2);
char *nsprintf_alloc (int start_size, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3);
char *vsprintf_alloc (const char *fmt, va_list ap);
char *vnsprintf_alloc (int start_size, const char *fmt, va_list ap);
/* Versions of the above which actually return a length, necessary if
* you expect embedded NULLs */
int vnisprintf_alloc (char **buf, int start_size, const char *fmt, va_list ap);
int visprintf_alloc (char **buf, const char *fmt, va_list ap);
int isprintf_alloc (char **buf, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3);
typedef struct _string
{
char *buf;
int len;
int max;
} STRING;
typedef struct _string_array
{
char **entries;
int count;
int max;
} STRING_ARRAY;
/* At some point, we should add the concept of "max len" to these so we
* can't get DoS'd by someone sending us a line without an end point,
* etc. */
void string_init (STRING *str);
NEOERR *string_set (STRING *str, const char *buf);
NEOERR *string_append (STRING *str, const char *buf);
NEOERR *string_appendn (STRING *str, const char *buf, int l);
NEOERR *string_append_char (STRING *str, char c);
NEOERR *string_appendf (STRING *str, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3);
NEOERR *string_appendvf (STRING *str, const char *fmt, va_list ap);
NEOERR *string_readline (STRING *str, FILE *fp);
void string_clear (STRING *str);
/* typedef struct _ulist ULIST; */
#include "util/ulist.h"
/* s is not const because we actually temporarily modify the string
* during split */
NEOERR *string_array_split (ULIST **list, char *s, const char *sep,
int max);
BOOL reg_search (const char *re, const char *str);
/* NEOS_ESCAPE details the support escape contexts/modes handled
* by various NEOS helper methods and reused in CS itself. */
typedef enum
{
NEOS_ESCAPE_UNDEF = 0, /* Used to force eval-time checking */
NEOS_ESCAPE_NONE = 1<<0,
NEOS_ESCAPE_HTML = 1<<1,
NEOS_ESCAPE_SCRIPT = 1<<2,
NEOS_ESCAPE_URL = 1<<3,
NEOS_ESCAPE_FUNCTION = 1<<4 /* Special case used to override the others */
} NEOS_ESCAPE;
NEOERR* neos_escape(UINT8 *buf, int buflen, char esc_char, const char *escape,
char **esc);
UINT8 *neos_unescape (UINT8 *s, int buflen, char esc_char);
char *repr_string_alloc (const char *s);
/* This is the "super" escape call which will call the proper helper
* variable escape function based on the passed in context. */
NEOERR *neos_var_escape (NEOS_ESCAPE context,
const char *in,
char **esc);
/* Generic data escaping helper functions used by neos_contextual_escape
* and cs built-ins. */
NEOERR *neos_url_escape (const char *in, char **esc,
const char *other);
NEOERR *neos_js_escape (const char *in, char **esc);
NEOERR *neos_html_escape (const char *src, int slen,
char **out);
NEOERR *neos_url_validate (const char *in, char **esc);
__END_DECLS
#endif /* __NEO_STR_H_ */
clearsilver-0.10.5/util/osdep.h 0000644 0012117 0011610 00000001274 10261037531 013266 0000000 0000000
#ifndef __OSDEP_H__
#define __OSDEP_H__ 1
#ifdef __WINDOWS_GCC__
#include
#include
#define __BEGIN_DECLS
#define __END_DECLS
#define _POSIX_PATH_MAX 255
#define S_IXGRP S_IXUSR
#define S_IWGRP S_IWUSR
#define S_IRGRP S_IRUSR
#define S_IROTH S_IRUSR
#define S_IWOTH S_IWUSR
#define HAVE_STDARG_H 1
#define HAVE_STRING_H 1
#undef HAVE_GMTOFF
int snprintf (char *str, size_t count, const char *fmt, ...);
int vsnprintf (char *str, size_t count, const char *fmt, va_list arg);
int mkstemp(char *path);
#define os_random rand
#else // UNIX......
#define os_random random
#define HAVE_PTHREAD 1
#endif
#endif // __OSDEP_H__
clearsilver-0.10.5/util/rcfs.c 0000644 0012117 0011610 00000013200 10261042441 013070 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
/*
* revision-controlled file system (RCFS) with meta-info storage
*/
#include "cs_config.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "util/neo_misc.h"
#include "util/neo_err.h"
#include "util/neo_files.h"
#include "util/neo_hdf.h"
#include "util/ulocks.h"
#include "rcfs.h"
NEOERR * rcfs_meta_load (const char *path, HDF **meta)
{
NEOERR *err;
char fpath[_POSIX_PATH_MAX];
HDF *m;
snprintf (fpath, sizeof(fpath), "%s,log", path);
err = hdf_init (&m);
if (err) return nerr_pass (err);
err = hdf_read_file (m, fpath);
if (err)
{
hdf_destroy (&m);
return nerr_pass (err);
}
*meta = m;
return STATUS_OK;
}
static NEOERR * _meta_save (const char *path, HDF *meta)
{
NEOERR *err;
char ftmp[_POSIX_PATH_MAX];
char fpath[_POSIX_PATH_MAX];
snprintf (ftmp, sizeof(ftmp), "%s,log.tmp", path);
snprintf (fpath, sizeof(fpath), "%s,log", path);
err = hdf_write_file (meta, ftmp);
if (err) return nerr_pass (err);
if (rename (ftmp, fpath) == -1)
{
unlink (ftmp);
return nerr_raise_errno (NERR_IO, "Unable to rename file %s", ftmp);
}
return STATUS_OK;
}
NEOERR * rcfs_meta_save (const char *path, HDF *meta)
{
NEOERR *err;
int lock;
HDF *m;
err = rcfs_lock (path, &lock);
if (err) return nerr_pass (err);
do
{
err = rcfs_meta_load (path, &m);
if (err) break;
err = hdf_copy (m, "Meta", meta);
if (err) break;
err = _meta_save (path, m);
} while (0);
rcfs_unlock (lock);
return nerr_pass (err);
}
/* load a specified version of the file, version -1 is latest */
NEOERR * rcfs_load (const char *path, int version, char **data)
{
NEOERR *err;
char fpath[_POSIX_PATH_MAX];
if (version == -1)
{
HDF *meta, *vers;
int x;
err = rcfs_meta_load (path, &meta);
if (err) return nerr_pass (err);
for (vers = hdf_get_child (meta, "Versions");
vers;
vers = hdf_obj_next (vers))
{
x = atoi (hdf_obj_name (vers));
if (x > version) version = x;
}
hdf_destroy (&meta);
}
snprintf (fpath, sizeof (fpath), "%s,%d", path, version);
err = ne_load_file (fpath, data);
return nerr_pass (err);
}
NEOERR * rcfs_save (const char *path, const char *data, const char *user,
const char *log)
{
NEOERR *err;
HDF *meta = NULL, *vers;
char fpath[_POSIX_PATH_MAX];
char buf[256];
int version = 0;
int fd;
int lock;
int x, l, w;
err = rcfs_lock (path, &lock);
if (err) return nerr_pass (err);
do
{
err = rcfs_meta_load (path, &meta);
if (err && nerr_handle (&err, NERR_NOT_FOUND))
{
/* new file! */
err = hdf_init (&meta);
}
if (err) return nerr_pass (err);
for (vers = hdf_get_child (meta, "Versions");
vers;
vers = hdf_obj_next (vers))
{
x = atoi (hdf_obj_name (vers));
if (x > version) version = x;
}
/* new version */
version++;
snprintf (fpath, sizeof (fpath), "%s,%d", path, version);
fd = open (fpath, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (fd == -1)
{
err = nerr_raise_errno (NERR_IO, "Unable to create file %s", fpath);
break;
}
l = strlen(data);
w = write (fd, data, l);
if (w != l)
{
err = nerr_raise_errno (NERR_IO, "Unable to write file %s", fpath);
close (fd);
break;
}
close (fd);
snprintf (buf, sizeof(buf), "Versions.%d.Log", version);
err = hdf_set_value (meta, buf, log);
if (err) break;
snprintf (buf, sizeof(buf), "Versions.%d.User", version);
err = hdf_set_value (meta, buf, user);
if (err) break;
snprintf (buf, sizeof(buf), "Versions.%d.Date", version);
err = hdf_set_int_value (meta, buf, ne_timef());
if (err) break;
err = _meta_save (path, meta);
} while (0);
rcfs_unlock (lock);
hdf_destroy (&meta);
return nerr_pass (err);
}
NEOERR * rcfs_lock (const char *path, int *lock)
{
NEOERR *err;
char fpath[_POSIX_PATH_MAX];
snprintf (fpath, sizeof (fpath), "%s,lock", path);
err = fCreate (lock, fpath);
if (err) return nerr_pass (err);
err = fLock (*lock);
if (err)
{
fDestroy (*lock);
return nerr_pass (err);
}
return STATUS_OK;
}
void rcfs_unlock (int lock)
{
fUnlock (lock);
fDestroy (lock);
}
NEOERR * rcfs_listdir (const char *path, ULIST **list)
{
NEOERR *err;
DIR *dp;
ULIST *files;
struct dirent *de;
int l;
char *f;
*list = NULL;
err = uListInit (&files, 10, 0);
if (err) return nerr_pass (err);
dp = opendir(path);
if (dp == NULL)
{
uListDestroy(&files, ULIST_FREE);
if (errno == ENOENT)
return nerr_raise (NERR_NOT_FOUND, "Directory %s doesn't exist", path);
return nerr_raise_errno (NERR_IO, "Unable to open directory %s", path);
}
while ((de = readdir (dp)) != NULL)
{
l = strlen (de->d_name);
if (l>4 && !strcmp (de->d_name+l-4, ",log"))
{
f = (char *) malloc ((l-3) * sizeof(char));
if (f == NULL)
{
uListDestroy (&files, ULIST_FREE);
closedir(dp);
return nerr_raise (NERR_NOMEM,
"Unable to allocate memory for filename %s", de->d_name);
}
strncpy (f, de->d_name, l-4);
f[l-4] = '\0';
err = uListAppend (files, f);
if (err)
{
free (f);
uListDestroy (&files, ULIST_FREE);
closedir(dp);
return nerr_pass (err);
}
}
}
*list = files;
closedir(dp);
return STATUS_OK;
}
clearsilver-0.10.5/util/rcfs.h 0000644 0012117 0011610 00000001741 10261042477 013115 0000000 0000000 /*
* Copyright 2001-2004 Brandon Long
* All Rights Reserved.
*
* ClearSilver Templating System
*
* This code is made available under the terms of the ClearSilver License.
* http://www.clearsilver.net/license.hdf
*
*/
/*
* revision-controlled file system (RCFS) with meta-info storage
*/
#ifndef __RCFS_H_
#define __RCFS_H_ 1
typedef struct _rcfs RCFS;
NEOERR * rcfs_init (RCFS **rcfs);
NEOERR * rcfs_destroy (RCFS **rcfs);
NEOERR * rcfs_load (const char *path, int version, char **data);
NEOERR * rcfs_save (const char *path, const char *data, const char *user,
const char *log);
NEOERR * rcfs_lock (const char *path, int *lock);
void rcfs_unlock (int lock);
NEOERR * rcfs_meta_load (const char *path, HDF **meta);
NEOERR * rcfs_meta_save (const char *path, HDF *meta);
NEOERR * rcfs_listdir (const char *path, ULIST **list);
NEOERR * rcfs_link (const char *src_path, const char *dest_path);
NEOERR * rcfs_unlink (const char *path);
#endif /* __RCFS_H_ */
clearsilver-0.10.5/util/regex/ 0000755 0012117 0011610 00000000000 10645505044 013176 5 0000000 0000000 clearsilver-0.10.5/util/regex/regex.c 0000644 0012117 0011610 00000472237 10344026304 014404 0000000 0000000 /* Extended regular expression matching and search library, version
0.12. (Implements POSIX draft P10003.2/D11.2, except for
internationalization features.)
Copyright (C) 1993, 1994, 1995, 1996 Free Software Foundation, Inc.
This program 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 2, 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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA. */
/* AIX requires this to be the first thing in the file. */
#if defined (_AIX) && !defined (REGEX_MALLOC)
#pragma alloca
#endif
#undef _GNU_SOURCE
#define _GNU_SOURCE
#include "cs_config.h"
#include "util/osdep.h"
#ifdef HAVE_CONFIG_H
#include
#endif
/* We need this for `regex.h', and perhaps for the Emacs include files. */
#include
/* This is for other GNU distributions with internationalized messages. */
#if HAVE_LIBINTL_H || defined (_LIBC)
# include
#else
# define gettext(msgid) (msgid)
#endif
#ifndef gettext_noop
/* This define is so xgettext can find the internationalizable
strings. */
#define gettext_noop(String) String
#endif
/* The `emacs' switch turns on certain matching commands
that make sense only in Emacs. */
#ifdef emacs
#include "lisp.h"
#include "buffer.h"
#include "syntax.h"
#else /* not emacs */
/* If we are not linking with Emacs proper,
we can't use the relocating allocator
even if config.h says that we can. */
#undef REL_ALLOC
#if defined (STDC_HEADERS) || defined (_LIBC)
#include
#else
char *malloc ();
char *realloc ();
#endif
/* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
If nothing else has been done, use the method below. */
#ifdef INHIBIT_STRING_HEADER
#if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
#if !defined (bzero) && !defined (bcopy)
#undef INHIBIT_STRING_HEADER
#endif
#endif
#endif
/* This is the normal way of making sure we have a bcopy and a bzero.
This is used in most programs--a few other programs avoid this
by defining INHIBIT_STRING_HEADER. */
#ifndef INHIBIT_STRING_HEADER
#if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
#include
#ifndef bcmp
#define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
#endif
#ifndef bcopy
#define bcopy(s, d, n) memcpy ((d), (s), (n))
#endif
#ifndef bzero
#define bzero(s, n) memset ((s), 0, (n))
#endif
#else
#include
#endif
#endif
/* Define the syntax stuff for \<, \>, etc. */
/* This must be nonzero for the wordchar and notwordchar pattern
commands in re_match_2. */
#ifndef Sword
#define Sword 1
#endif
#ifdef SWITCH_ENUM_BUG
#define SWITCH_ENUM_CAST(x) ((int)(x))
#else
#define SWITCH_ENUM_CAST(x) (x)
#endif
#ifdef SYNTAX_TABLE
extern char *re_syntax_table;
#else /* not SYNTAX_TABLE */
/* How many characters in the character set. */
#define CHAR_SET_SIZE 256
static char re_syntax_table[CHAR_SET_SIZE];
static void
init_syntax_once ()
{
register int c;
static int done = 0;
if (done)
return;
bzero (re_syntax_table, sizeof re_syntax_table);
for (c = 'a'; c <= 'z'; c++)
re_syntax_table[c] = Sword;
for (c = 'A'; c <= 'Z'; c++)
re_syntax_table[c] = Sword;
for (c = '0'; c <= '9'; c++)
re_syntax_table[c] = Sword;
re_syntax_table['_'] = Sword;
done = 1;
}
#endif /* not SYNTAX_TABLE */
#define SYNTAX(c) re_syntax_table[c]
#endif /* not emacs */
/* Get the interface, including the syntax bits. */
#include "regex.h"
/* isalpha etc. are used for the character classes. */
#include
/* Jim Meyering writes:
"... Some ctype macros are valid only for character codes that
isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
using /bin/cc or gcc but without giving an ansi option). So, all
ctype uses should be through macros like ISPRINT... If
STDC_HEADERS is defined, then autoconf has verified that the ctype
macros don't need to be guarded with references to isascii. ...
Defining IN_CTYPE_DOMAIN to 1 should let any compiler worth its salt
eliminate the && through constant folding." */
#if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
#define IN_CTYPE_DOMAIN(c) 1
#else
#define IN_CTYPE_DOMAIN(c) isascii(c)
#endif
#ifdef isblank
#define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c))
#else
#define ISBLANK(c) ((c) == ' ' || (c) == '\t')
#endif
#ifdef isgraph
#define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c))
#else
#define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c))
#endif
#define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c))
#define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c))
#define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c))
#define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c))
#define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c))
#define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c))
#define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c))
#define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
#define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c))
#define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c))
#ifndef NULL
#define NULL (void *)0
#endif
/* We remove any previous definition of `SIGN_EXTEND_CHAR',
since ours (we hope) works properly with all combinations of
machines, compilers, `char' and `unsigned char' argument types.
(Per Bothner suggested the basic approach.) */
#undef SIGN_EXTEND_CHAR
#if __STDC__
#define SIGN_EXTEND_CHAR(c) ((signed char) (c))
#else /* not __STDC__ */
/* As in Harbison and Steele. */
#define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
#endif
/* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
use `alloca' instead of `malloc'. This is because using malloc in
re_search* or re_match* could cause memory leaks when C-g is used in
Emacs; also, malloc is slower and causes storage fragmentation. On
the other hand, malloc is more portable, and easier to debug.
Because we sometimes use alloca, some routines have to be macros,
not functions -- `alloca'-allocated space disappears at the end of the
function it is called in. */
#ifdef REGEX_MALLOC
#define REGEX_ALLOCATE malloc
#define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
#define REGEX_FREE free
#else /* not REGEX_MALLOC */
/* Emacs already defines alloca, sometimes. */
#ifndef alloca
/* Make alloca work the best possible way. */
#ifdef __GNUC__
#define alloca __builtin_alloca
#else /* not __GNUC__ */
#if HAVE_ALLOCA_H
#include
#else /* not __GNUC__ or HAVE_ALLOCA_H */
#if 0 /* It is a bad idea to declare alloca. We always cast the result. */
#ifndef _AIX /* Already did AIX, up at the top. */
char *alloca ();
#endif /* not _AIX */
#endif
#endif /* not HAVE_ALLOCA_H */
#endif /* not __GNUC__ */
#endif /* not alloca */
#define REGEX_ALLOCATE alloca
/* Assumes a `char *destination' variable. */
#define REGEX_REALLOCATE(source, osize, nsize) \
(destination = (char *) alloca (nsize), \
bcopy (source, destination, osize), \
destination)
/* No need to do anything to free, after alloca. */
#define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
#endif /* not REGEX_MALLOC */
/* Define how to allocate the failure stack. */
#if defined (REL_ALLOC) && defined (REGEX_MALLOC)
#define REGEX_ALLOCATE_STACK(size) \
r_alloc (&failure_stack_ptr, (size))
#define REGEX_REALLOCATE_STACK(source, osize, nsize) \
r_re_alloc (&failure_stack_ptr, (nsize))
#define REGEX_FREE_STACK(ptr) \
r_alloc_free (&failure_stack_ptr)
#else /* not using relocating allocator */
#ifdef REGEX_MALLOC
#define REGEX_ALLOCATE_STACK malloc
#define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
#define REGEX_FREE_STACK free
#else /* not REGEX_MALLOC */
#define REGEX_ALLOCATE_STACK alloca
#define REGEX_REALLOCATE_STACK(source, osize, nsize) \
REGEX_REALLOCATE (source, osize, nsize)
/* No need to explicitly free anything. */
#define REGEX_FREE_STACK(arg)
#endif /* not REGEX_MALLOC */
#endif /* not using relocating allocator */
/* True if `size1' is non-NULL and PTR is pointing anywhere inside
`string1' or just past its end. This works if PTR is NULL, which is
a good thing. */
#define FIRST_STRING_P(ptr) \
(size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
/* (Re)Allocate N items of type T using malloc, or fail. */
#define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
#define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
#define RETALLOC_IF(addr, n, t) \
if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
#define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
#define BYTEWIDTH 8 /* In bits. */
#define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
#undef MAX
#undef MIN
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
typedef char boolean;
#define false 0
#define true 1
static int re_match_2_internal ();
/* These are the command codes that appear in compiled regular
expressions. Some opcodes are followed by argument bytes. A
command code can specify any interpretation whatsoever for its
arguments. Zero bytes may appear in the compiled regular expression. */
typedef enum
{
no_op = 0,
/* Succeed right away--no more backtracking. */
succeed,
/* Followed by one byte giving n, then by n literal bytes. */
exactn,
/* Matches any (more or less) character. */
anychar,
/* Matches any one char belonging to specified set. First
following byte is number of bitmap bytes. Then come bytes
for a bitmap saying which chars are in. Bits in each byte
are ordered low-bit-first. A character is in the set if its
bit is 1. A character too large to have a bit in the map is
automatically not in the set. */
charset,
/* Same parameters as charset, but match any character that is
not one of those specified. */
charset_not,
/* Start remembering the text that is matched, for storing in a
register. Followed by one byte with the register number, in
the range 0 to one less than the pattern buffer's re_nsub
field. Then followed by one byte with the number of groups
inner to this one. (This last has to be part of the
start_memory only because we need it in the on_failure_jump
of re_match_2.) */
start_memory,
/* Stop remembering the text that is matched and store it in a
memory register. Followed by one byte with the register
number, in the range 0 to one less than `re_nsub' in the
pattern buffer, and one byte with the number of inner groups,
just like `start_memory'. (We need the number of inner
groups here because we don't have any easy way of finding the
corresponding start_memory when we're at a stop_memory.) */
stop_memory,
/* Match a duplicate of something remembered. Followed by one
byte containing the register number. */
duplicate,
/* Fail unless at beginning of line. */
begline,
/* Fail unless at end of line. */
endline,
/* Succeeds if at beginning of buffer (if emacs) or at beginning
of string to be matched (if not). */
begbuf,
/* Analogously, for end of buffer/string. */
endbuf,
/* Followed by two byte relative address to which to jump. */
jump,
/* Same as jump, but marks the end of an alternative. */
jump_past_alt,
/* Followed by two-byte relative address of place to resume at
in case of failure. */
on_failure_jump,
/* Like on_failure_jump, but pushes a placeholder instead of the
current string position when executed. */
on_failure_keep_string_jump,
/* Throw away latest failure point and then jump to following
two-byte relative address. */
pop_failure_jump,
/* Change to pop_failure_jump if know won't have to backtrack to
match; otherwise change to jump. This is used to jump
back to the beginning of a repeat. If what follows this jump
clearly won't match what the repeat does, such that we can be
sure that there is no use backtracking out of repetitions
already matched, then we change it to a pop_failure_jump.
Followed by two-byte address. */
maybe_pop_jump,
/* Jump to following two-byte address, and push a dummy failure
point. This failure point will be thrown away if an attempt
is made to use it for a failure. A `+' construct makes this
before the first repeat. Also used as an intermediary kind
of jump when compiling an alternative. */
dummy_failure_jump,
/* Push a dummy failure point and continue. Used at the end of
alternatives. */
push_dummy_failure,
/* Followed by two-byte relative address and two-byte number n.
After matching N times, jump to the address upon failure. */
succeed_n,
/* Followed by two-byte relative address, and two-byte number n.
Jump to the address N times, then fail. */
jump_n,
/* Set the following two-byte relative address to the
subsequent two-byte number. The address *includes* the two
bytes of number. */
set_number_at,
wordchar, /* Matches any word-constituent character. */
notwordchar, /* Matches any char that is not a word-constituent. */
wordbeg, /* Succeeds if at word beginning. */
wordend, /* Succeeds if at word end. */
wordbound, /* Succeeds if at a word boundary. */
notwordbound /* Succeeds if not at a word boundary. */
#ifdef emacs
,before_dot, /* Succeeds if before point. */
at_dot, /* Succeeds if at point. */
after_dot, /* Succeeds if after point. */
/* Matches any character whose syntax is specified. Followed by
a byte which contains a syntax code, e.g., Sword. */
syntaxspec,
/* Matches any character whose syntax is not that specified. */
notsyntaxspec
#endif /* emacs */
} re_opcode_t;
/* Common operations on the compiled pattern. */
/* Store NUMBER in two contiguous bytes starting at DESTINATION. */
#define STORE_NUMBER(destination, number) \
do { \
(destination)[0] = (number) & 0377; \
(destination)[1] = (number) >> 8; \
} while (0)
/* Same as STORE_NUMBER, except increment DESTINATION to
the byte after where the number is stored. Therefore, DESTINATION
must be an lvalue. */
#define STORE_NUMBER_AND_INCR(destination, number) \
do { \
STORE_NUMBER (destination, number); \
(destination) += 2; \
} while (0)
/* Put into DESTINATION a number stored in two contiguous bytes starting
at SOURCE. */
#define EXTRACT_NUMBER(destination, source) \
do { \
(destination) = *(source) & 0377; \
(destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
} while (0)
#ifdef DEBUG
static void
extract_number (dest, source)
int *dest;
unsigned char *source;
{
int temp = SIGN_EXTEND_CHAR (*(source + 1));
*dest = *source & 0377;
*dest += temp << 8;
}
#ifndef EXTRACT_MACROS /* To debug the macros. */
#undef EXTRACT_NUMBER
#define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
#endif /* not EXTRACT_MACROS */
#endif /* DEBUG */
/* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
SOURCE must be an lvalue. */
#define EXTRACT_NUMBER_AND_INCR(destination, source) \
do { \
EXTRACT_NUMBER (destination, source); \
(source) += 2; \
} while (0)
#ifdef DEBUG
static void
extract_number_and_incr (destination, source)
int *destination;
unsigned char **source;
{
extract_number (destination, *source);
*source += 2;
}
#ifndef EXTRACT_MACROS
#undef EXTRACT_NUMBER_AND_INCR
#define EXTRACT_NUMBER_AND_INCR(dest, src) \
extract_number_and_incr (&dest, &src)
#endif /* not EXTRACT_MACROS */
#endif /* DEBUG */
/* If DEBUG is defined, Regex prints many voluminous messages about what
it is doing (if the variable `debug' is nonzero). If linked with the
main program in `iregex.c', you can enter patterns and strings
interactively. And if linked with the main program in `main.c' and
the other test files, you can run the already-written tests. */
#ifdef DEBUG
/* We use standard I/O for debugging. */
#include
/* It is useful to test things that ``must'' be true when debugging. */
#include
static int debug = 0;
#define DEBUG_STATEMENT(e) e
#define DEBUG_PRINT1(x) if (debug) printf (x)
#define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
#define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
#define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
if (debug) print_partial_compiled_pattern (s, e)
#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
if (debug) print_double_string (w, s1, sz1, s2, sz2)
/* Print the fastmap in human-readable form. */
void
print_fastmap (fastmap)
char *fastmap;
{
unsigned was_a_range = 0;
unsigned i = 0;
while (i < (1 << BYTEWIDTH))
{
if (fastmap[i++])
{
was_a_range = 0;
putchar (i - 1);
while (i < (1 << BYTEWIDTH) && fastmap[i])
{
was_a_range = 1;
i++;
}
if (was_a_range)
{
printf ("-");
putchar (i - 1);
}
}
}
putchar ('\n');
}
/* Print a compiled pattern string in human-readable form, starting at
the START pointer into it and ending just before the pointer END. */
void
print_partial_compiled_pattern (start, end)
unsigned char *start;
unsigned char *end;
{
int mcnt, mcnt2;
unsigned char *p = start;
unsigned char *pend = end;
if (start == NULL)
{
printf ("(null)\n");
return;
}
/* Loop over pattern commands. */
while (p < pend)
{
printf ("%d:\t", p - start);
switch ((re_opcode_t) *p++)
{
case no_op:
printf ("/no_op");
break;
case exactn:
mcnt = *p++;
printf ("/exactn/%d", mcnt);
do
{
putchar ('/');
putchar (*p++);
}
while (--mcnt);
break;
case start_memory:
mcnt = *p++;
printf ("/start_memory/%d/%d", mcnt, *p++);
break;
case stop_memory:
mcnt = *p++;
printf ("/stop_memory/%d/%d", mcnt, *p++);
break;
case duplicate:
printf ("/duplicate/%d", *p++);
break;
case anychar:
printf ("/anychar");
break;
case charset:
case charset_not:
{
register int c, last = -100;
register int in_range = 0;
printf ("/charset [%s",
(re_opcode_t) *(p - 1) == charset_not ? "^" : "");
assert (p + *p < pend);
for (c = 0; c < 256; c++)
if (c / 8 < *p
&& (p[1 + (c/8)] & (1 << (c % 8))))
{
/* Are we starting a range? */
if (last + 1 == c && ! in_range)
{
putchar ('-');
in_range = 1;
}
/* Have we broken a range? */
else if (last + 1 != c && in_range)
{
putchar (last);
in_range = 0;
}
if (! in_range)
putchar (c);
last = c;
}
if (in_range)
putchar (last);
putchar (']');
p += 1 + *p;
}
break;
case begline:
printf ("/begline");
break;
case endline:
printf ("/endline");
break;
case on_failure_jump:
extract_number_and_incr (&mcnt, &p);
printf ("/on_failure_jump to %d", p + mcnt - start);
break;
case on_failure_keep_string_jump:
extract_number_and_incr (&mcnt, &p);
printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
break;
case dummy_failure_jump:
extract_number_and_incr (&mcnt, &p);
printf ("/dummy_failure_jump to %d", p + mcnt - start);
break;
case push_dummy_failure:
printf ("/push_dummy_failure");
break;
case maybe_pop_jump:
extract_number_and_incr (&mcnt, &p);
printf ("/maybe_pop_jump to %d", p + mcnt - start);
break;
case pop_failure_jump:
extract_number_and_incr (&mcnt, &p);
printf ("/pop_failure_jump to %d", p + mcnt - start);
break;
case jump_past_alt:
extract_number_and_incr (&mcnt, &p);
printf ("/jump_past_alt to %d", p + mcnt - start);
break;
case jump:
extract_number_and_incr (&mcnt, &p);
printf ("/jump to %d", p + mcnt - start);
break;
case succeed_n:
extract_number_and_incr (&mcnt, &p);
extract_number_and_incr (&mcnt2, &p);
printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
break;
case jump_n:
extract_number_and_incr (&mcnt, &p);
extract_number_and_incr (&mcnt2, &p);
printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
break;
case set_number_at:
extract_number_and_incr (&mcnt, &p);
extract_number_and_incr (&mcnt2, &p);
printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
break;
case wordbound:
printf ("/wordbound");
break;
case notwordbound:
printf ("/notwordbound");
break;
case wordbeg:
printf ("/wordbeg");
break;
case wordend:
printf ("/wordend");
#ifdef emacs
case before_dot:
printf ("/before_dot");
break;
case at_dot:
printf ("/at_dot");
break;
case after_dot:
printf ("/after_dot");
break;
case syntaxspec:
printf ("/syntaxspec");
mcnt = *p++;
printf ("/%d", mcnt);
break;
case notsyntaxspec:
printf ("/notsyntaxspec");
mcnt = *p++;
printf ("/%d", mcnt);
break;
#endif /* emacs */
case wordchar:
printf ("/wordchar");
break;
case notwordchar:
printf ("/notwordchar");
break;
case begbuf:
printf ("/begbuf");
break;
case endbuf:
printf ("/endbuf");
break;
default:
printf ("?%d", *(p-1));
}
putchar ('\n');
}
printf ("%d:\tend of pattern.\n", p - start);
}
void
print_compiled_pattern (bufp)
struct re_pattern_buffer *bufp;
{
unsigned char *buffer = bufp->buffer;
print_partial_compiled_pattern (buffer, buffer + bufp->used);
printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
if (bufp->fastmap_accurate && bufp->fastmap)
{
printf ("fastmap: ");
print_fastmap (bufp->fastmap);
}
printf ("re_nsub: %d\t", bufp->re_nsub);
printf ("regs_alloc: %d\t", bufp->regs_allocated);
printf ("can_be_null: %d\t", bufp->can_be_null);
printf ("newline_anchor: %d\n", bufp->newline_anchor);
printf ("no_sub: %d\t", bufp->no_sub);
printf ("not_bol: %d\t", bufp->not_bol);
printf ("not_eol: %d\t", bufp->not_eol);
printf ("syntax: %d\n", bufp->syntax);
/* Perhaps we should print the translate table? */
}
void
print_double_string (where, string1, size1, string2, size2)
const char *where;
const char *string1;
const char *string2;
int size1;
int size2;
{
unsigned this_char;
if (where == NULL)
printf ("(null)");
else
{
if (FIRST_STRING_P (where))
{
for (this_char = where - string1; this_char < size1; this_char++)
putchar (string1[this_char]);
where = string2;
}
for (this_char = where - string2; this_char < size2; this_char++)
putchar (string2[this_char]);
}
}
#else /* not DEBUG */
#undef assert
#define assert(e)
#define DEBUG_STATEMENT(e)
#define DEBUG_PRINT1(x)
#define DEBUG_PRINT2(x1, x2)
#define DEBUG_PRINT3(x1, x2, x3)
#define DEBUG_PRINT4(x1, x2, x3, x4)
#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
#endif /* not DEBUG */
/* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
also be assigned to arbitrarily: each pattern buffer stores its own
syntax, so it can be changed between regex compilations. */
/* This has no initializer because initialized variables in Emacs
become read-only after dumping. */
reg_syntax_t re_syntax_options;
/* Specify the precise syntax of regexps for compilation. This provides
for compatibility for various utilities which historically have
different, incompatible syntaxes.
The argument SYNTAX is a bit mask comprised of the various bits
defined in regex.h. We return the old syntax. */
reg_syntax_t
re_set_syntax (syntax)
reg_syntax_t syntax;
{
reg_syntax_t ret = re_syntax_options;
re_syntax_options = syntax;
return ret;
}
/* This table gives an error message for each of the error codes listed
in regex.h. Obviously the order here has to be same as there.
POSIX doesn't require that we do anything for REG_NOERROR,
but why not be nice? */
static const char *re_error_msgid[] =
{
gettext_noop ("Success"), /* REG_NOERROR */
gettext_noop ("No match"), /* REG_NOMATCH */
gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
gettext_noop ("Invalid range end"), /* REG_ERANGE */
gettext_noop ("Memory exhausted"), /* REG_ESPACE */
gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
gettext_noop ("Premature end of regular expression"), /* REG_EEND */
gettext_noop ("Regular expression too big"), /* REG_ESIZE */
gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
};
/* Avoiding alloca during matching, to placate r_alloc. */
/* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
searching and matching functions should not call alloca. On some
systems, alloca is implemented in terms of malloc, and if we're
using the relocating allocator routines, then malloc could cause a
relocation, which might (if the strings being searched are in the
ralloc heap) shift the data out from underneath the regexp
routines.
Here's another reason to avoid allocation: Emacs
processes input from X in a signal handler; processing X input may
call malloc; if input arrives while a matching routine is calling
malloc, then we're scrod. But Emacs can't just block input while
calling matching routines; then we don't notice interrupts when
they come in. So, Emacs blocks input around all regexp calls
except the matching calls, which it leaves unprotected, in the
faith that they will not malloc. */
/* Normally, this is fine. */
#define MATCH_MAY_ALLOCATE
/* When using GNU C, we are not REALLY using the C alloca, no matter
what config.h may say. So don't take precautions for it. */
#ifdef __GNUC__
#undef C_ALLOCA
#endif
/* The match routines may not allocate if (1) they would do it with malloc
and (2) it's not safe for them to use malloc.
Note that if REL_ALLOC is defined, matching would not use malloc for the
failure stack, but we would still use it for the register vectors;
so REL_ALLOC should not affect this. */
#if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
#undef MATCH_MAY_ALLOCATE
#endif
/* Failure stack declarations and macros; both re_compile_fastmap and
re_match_2 use a failure stack. These have to be macros because of
REGEX_ALLOCATE_STACK. */
/* Number of failure points for which to initially allocate space
when matching. If this number is exceeded, we allocate more
space, so it is not a hard limit. */
#ifndef INIT_FAILURE_ALLOC
#define INIT_FAILURE_ALLOC 5
#endif
/* Roughly the maximum number of failure points on the stack. Would be
exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
This is a variable only so users of regex can assign to it; we never
change it ourselves. */
#if defined (MATCH_MAY_ALLOCATE)
/* 4400 was enough to cause a crash on Alpha OSF/1,
whose default stack limit is 2mb. */
int re_max_failures = 20000;
#else
int re_max_failures = 2000;
#endif
union fail_stack_elt
{
unsigned char *pointer;
int integer;
};
typedef union fail_stack_elt fail_stack_elt_t;
typedef struct
{
fail_stack_elt_t *stack;
unsigned size;
unsigned avail; /* Offset of next open position. */
} fail_stack_type;
#define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
#define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
#define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
/* Define macros to initialize and free the failure stack.
Do `return -2' if the alloc fails. */
#ifdef MATCH_MAY_ALLOCATE
#define INIT_FAIL_STACK() \
do { \
fail_stack.stack = (fail_stack_elt_t *) \
REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
\
if (fail_stack.stack == NULL) \
return -2; \
\
fail_stack.size = INIT_FAILURE_ALLOC; \
fail_stack.avail = 0; \
} while (0)
#define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
#else
#define INIT_FAIL_STACK() \
do { \
fail_stack.avail = 0; \
} while (0)
#define RESET_FAIL_STACK()
#endif
/* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
Return 1 if succeeds, and 0 if either ran out of memory
allocating space for it or it was already too large.
REGEX_REALLOCATE_STACK requires `destination' be declared. */
#define DOUBLE_FAIL_STACK(fail_stack) \
((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
? 0 \
: ((fail_stack).stack = (fail_stack_elt_t *) \
REGEX_REALLOCATE_STACK ((fail_stack).stack, \
(fail_stack).size * sizeof (fail_stack_elt_t), \
((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
\
(fail_stack).stack == NULL \
? 0 \
: ((fail_stack).size <<= 1, \
1)))
/* Push pointer POINTER on FAIL_STACK.
Return 1 if was able to do so and 0 if ran out of memory allocating
space to do so. */
#define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
((FAIL_STACK_FULL () \
&& !DOUBLE_FAIL_STACK (FAIL_STACK)) \
? 0 \
: ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1))
/* Push a pointer value onto the failure stack.
Assumes the variable `fail_stack'. Probably should only
be called from within `PUSH_FAILURE_POINT'. */
#define PUSH_FAILURE_POINTER(item) \
fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
/* This pushes an integer-valued item onto the failure stack.
Assumes the variable `fail_stack'. Probably should only
be called from within `PUSH_FAILURE_POINT'. */
#define PUSH_FAILURE_INT(item) \
fail_stack.stack[fail_stack.avail++].integer = (item)
/* Push a fail_stack_elt_t value onto the failure stack.
Assumes the variable `fail_stack'. Probably should only
be called from within `PUSH_FAILURE_POINT'. */
#define PUSH_FAILURE_ELT(item) \
fail_stack.stack[fail_stack.avail++] = (item)
/* These three POP... operations complement the three PUSH... operations.
All assume that `fail_stack' is nonempty. */
#define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
#define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
#define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
/* Used to omit pushing failure point id's when we're not debugging. */
#ifdef DEBUG
#define DEBUG_PUSH PUSH_FAILURE_INT
#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
#else
#define DEBUG_PUSH(item)
#define DEBUG_POP(item_addr)
#endif
/* Push the information about the state we will need
if we ever fail back to it.
Requires variables fail_stack, regstart, regend, reg_info, and
num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
declared.
Does `return FAILURE_CODE' if runs out of memory. */
#define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
do { \
char *destination; \
/* Must be int, so when we don't save any registers, the arithmetic \
of 0 + -1 isn't done as unsigned. */ \
int this_reg; \
\
DEBUG_STATEMENT (failure_id++); \
DEBUG_STATEMENT (nfailure_points_pushed++); \
DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
\
DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
\
/* Ensure we have enough space allocated for what we will push. */ \
while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
{ \
if (!DOUBLE_FAIL_STACK (fail_stack)) \
return failure_code; \
\
DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
(fail_stack).size); \
DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
} \
\
/* Push the info, starting with the registers. */ \
DEBUG_PRINT1 ("\n"); \
\
if (1) \
for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
this_reg++) \
{ \
DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
DEBUG_STATEMENT (num_regs_pushed++); \
\
DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
PUSH_FAILURE_POINTER (regstart[this_reg]); \
\
DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
PUSH_FAILURE_POINTER (regend[this_reg]); \
\
DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
DEBUG_PRINT2 (" match_null=%d", \
REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
DEBUG_PRINT2 (" matched_something=%d", \
MATCHED_SOMETHING (reg_info[this_reg])); \
DEBUG_PRINT2 (" ever_matched=%d", \
EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
DEBUG_PRINT1 ("\n"); \
PUSH_FAILURE_ELT (reg_info[this_reg].word); \
} \
\
DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
PUSH_FAILURE_INT (lowest_active_reg); \
\
DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
PUSH_FAILURE_INT (highest_active_reg); \
\
DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
PUSH_FAILURE_POINTER (pattern_place); \
\
DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
size2); \
DEBUG_PRINT1 ("'\n"); \
PUSH_FAILURE_POINTER (string_place); \
\
DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
DEBUG_PUSH (failure_id); \
} while (0)
/* This is the number of items that are pushed and popped on the stack
for each register. */
#define NUM_REG_ITEMS 3
/* Individual items aside from the registers. */
#ifdef DEBUG
#define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
#else
#define NUM_NONREG_ITEMS 4
#endif
/* We push at most this many items on the stack. */
/* We used to use (num_regs - 1), which is the number of registers
this regexp will save; but that was changed to 5
to avoid stack overflow for a regexp with lots of parens. */
#define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
/* We actually push this many items. */
#define NUM_FAILURE_ITEMS \
(((0 \
? 0 : highest_active_reg - lowest_active_reg + 1) \
* NUM_REG_ITEMS) \
+ NUM_NONREG_ITEMS)
/* How many items can still be added to the stack without overflowing it. */
#define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
/* Pops what PUSH_FAIL_STACK pushes.
We restore into the parameters, all of which should be lvalues:
STR -- the saved data position.
PAT -- the saved pattern position.
LOW_REG, HIGH_REG -- the highest and lowest active registers.
REGSTART, REGEND -- arrays of string positions.
REG_INFO -- array of information about each subexpression.
Also assumes the variables `fail_stack' and (if debugging), `bufp',
`pend', `string1', `size1', `string2', and `size2'. */
#define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
{ \
DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
int this_reg; \
const unsigned char *string_temp; \
\
assert (!FAIL_STACK_EMPTY ()); \
\
/* Remove failure points and point to how many regs pushed. */ \
DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
\
assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
\
DEBUG_POP (&failure_id); \
DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
\
/* If the saved string location is NULL, it came from an \
on_failure_keep_string_jump opcode, and we want to throw away the \
saved NULL, thus retaining our current position in the string. */ \
string_temp = POP_FAILURE_POINTER (); \
if (string_temp != NULL) \
str = (const char *) string_temp; \
\
DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
DEBUG_PRINT1 ("'\n"); \
\
pat = (unsigned char *) POP_FAILURE_POINTER (); \
DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
\
/* Restore register info. */ \
high_reg = (unsigned) POP_FAILURE_INT (); \
DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
\
low_reg = (unsigned) POP_FAILURE_INT (); \
DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
\
if (1) \
for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
{ \
DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
\
reg_info[this_reg].word = POP_FAILURE_ELT (); \
DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
\
regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
\
regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
} \
else \
{ \
for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
{ \
reg_info[this_reg].word.integer = 0; \
regend[this_reg] = 0; \
regstart[this_reg] = 0; \
} \
highest_active_reg = high_reg; \
} \
\
set_regs_matched_done = 0; \
DEBUG_STATEMENT (nfailure_points_popped++); \
} /* POP_FAILURE_POINT */
/* Structure for per-register (a.k.a. per-group) information.
Other register information, such as the
starting and ending positions (which are addresses), and the list of
inner groups (which is a bits list) are maintained in separate
variables.
We are making a (strictly speaking) nonportable assumption here: that
the compiler will pack our bit fields into something that fits into
the type of `word', i.e., is something that fits into one item on the
failure stack. */
typedef union
{
fail_stack_elt_t word;
struct
{
/* This field is one if this group can match the empty string,
zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
#define MATCH_NULL_UNSET_VALUE 3
unsigned match_null_string_p : 2;
unsigned is_active : 1;
unsigned matched_something : 1;
unsigned ever_matched_something : 1;
} bits;
} register_info_type;
#define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
#define IS_ACTIVE(R) ((R).bits.is_active)
#define MATCHED_SOMETHING(R) ((R).bits.matched_something)
#define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
/* Call this when have matched a real character; it sets `matched' flags
for the subexpressions which we are currently inside. Also records
that those subexprs have matched. */
#define SET_REGS_MATCHED() \
do \
{ \
if (!set_regs_matched_done) \
{ \
unsigned r; \
set_regs_matched_done = 1; \
for (r = lowest_active_reg; r <= highest_active_reg; r++) \
{ \
MATCHED_SOMETHING (reg_info[r]) \
= EVER_MATCHED_SOMETHING (reg_info[r]) \
= 1; \
} \
} \
} \
while (0)
/* Registers are set to a sentinel when they haven't yet matched. */
static char reg_unset_dummy;
#define REG_UNSET_VALUE (®_unset_dummy)
#define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
/* Subroutine declarations and macros for regex_compile. */
static void store_op1 (), store_op2 ();
static void insert_op1 (), insert_op2 ();
static boolean at_begline_loc_p (), at_endline_loc_p ();
static boolean group_in_compile_stack ();
static reg_errcode_t compile_range ();
/* Fetch the next character in the uncompiled pattern---translating it
if necessary. Also cast from a signed character in the constant
string passed to us by the user to an unsigned char that we can use
as an array index (in, e.g., `translate'). */
#ifndef PATFETCH
#define PATFETCH(c) \
do {if (p == pend) return REG_EEND; \
c = (unsigned char) *p++; \
if (translate) c = (unsigned char) translate[c]; \
} while (0)
#endif
/* Fetch the next character in the uncompiled pattern, with no
translation. */
#define PATFETCH_RAW(c) \
do {if (p == pend) return REG_EEND; \
c = (unsigned char) *p++; \
} while (0)
/* Go backwards one character in the pattern. */
#define PATUNFETCH p--
/* If `translate' is non-null, return translate[D], else just D. We
cast the subscript to translate because some data is declared as
`char *', to avoid warnings when a string constant is passed. But
when we use a character as a subscript we must make it unsigned. */
#ifndef TRANSLATE
#define TRANSLATE(d) \
(translate ? (char) translate[(unsigned char) (d)] : (d))
#endif
/* Macros for outputting the compiled pattern into `buffer'. */
/* If the buffer isn't allocated when it comes in, use this. */
#define INIT_BUF_SIZE 32
/* Make sure we have at least N more bytes of space in buffer. */
#define GET_BUFFER_SPACE(n) \
while (b - bufp->buffer + (n) > bufp->allocated) \
EXTEND_BUFFER ()
/* Make sure we have one more byte of buffer space and then add C to it. */
#define BUF_PUSH(c) \
do { \
GET_BUFFER_SPACE (1); \
*b++ = (unsigned char) (c); \
} while (0)
/* Ensure we have two more bytes of buffer space and then append C1 and C2. */
#define BUF_PUSH_2(c1, c2) \
do { \
GET_BUFFER_SPACE (2); \
*b++ = (unsigned char) (c1); \
*b++ = (unsigned char) (c2); \
} while (0)
/* As with BUF_PUSH_2, except for three bytes. */
#define BUF_PUSH_3(c1, c2, c3) \
do { \
GET_BUFFER_SPACE (3); \
*b++ = (unsigned char) (c1); \
*b++ = (unsigned char) (c2); \
*b++ = (unsigned char) (c3); \
} while (0)
/* Store a jump with opcode OP at LOC to location TO. We store a
relative address offset by the three bytes the jump itself occupies. */
#define STORE_JUMP(op, loc, to) \
store_op1 (op, loc, (to) - (loc) - 3)
/* Likewise, for a two-argument jump. */
#define STORE_JUMP2(op, loc, to, arg) \
store_op2 (op, loc, (to) - (loc) - 3, arg)
/* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
#define INSERT_JUMP(op, loc, to) \
insert_op1 (op, loc, (to) - (loc) - 3, b)
/* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
#define INSERT_JUMP2(op, loc, to, arg) \
insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
/* This is not an arbitrary limit: the arguments which represent offsets
into the pattern are two bytes long. So if 2^16 bytes turns out to
be too small, many things would have to change. */
#define MAX_BUF_SIZE (1L << 16)
/* Extend the buffer by twice its current size via realloc and
reset the pointers that pointed into the old block to point to the
correct places in the new one. If extending the buffer results in it
being larger than MAX_BUF_SIZE, then flag memory exhausted. */
#define EXTEND_BUFFER() \
do { \
unsigned char *old_buffer = bufp->buffer; \
if (bufp->allocated == MAX_BUF_SIZE) \
return REG_ESIZE; \
bufp->allocated <<= 1; \
if (bufp->allocated > MAX_BUF_SIZE) \
bufp->allocated = MAX_BUF_SIZE; \
bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
if (bufp->buffer == NULL) \
return REG_ESPACE; \
/* If the buffer moved, move all the pointers into it. */ \
if (old_buffer != bufp->buffer) \
{ \
b = (b - old_buffer) + bufp->buffer; \
begalt = (begalt - old_buffer) + bufp->buffer; \
if (fixup_alt_jump) \
fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
if (laststart) \
laststart = (laststart - old_buffer) + bufp->buffer; \
if (pending_exact) \
pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
} \
} while (0)
/* Since we have one byte reserved for the register number argument to
{start,stop}_memory, the maximum number of groups we can report
things about is what fits in that byte. */
#define MAX_REGNUM 255
/* But patterns can have more than `MAX_REGNUM' registers. We just
ignore the excess. */
typedef unsigned regnum_t;
/* Macros for the compile stack. */
/* Since offsets can go either forwards or backwards, this type needs to
be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
typedef int pattern_offset_t;
typedef struct
{
pattern_offset_t begalt_offset;
pattern_offset_t fixup_alt_jump;
pattern_offset_t inner_group_offset;
pattern_offset_t laststart_offset;
regnum_t regnum;
} compile_stack_elt_t;
typedef struct
{
compile_stack_elt_t *stack;
unsigned size;
unsigned avail; /* Offset of next open position. */
} compile_stack_type;
#define INIT_COMPILE_STACK_SIZE 32
#define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
#define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
/* The next available element. */
#define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
/* Set the bit for character C in a list. */
#define SET_LIST_BIT(c) \
(b[((unsigned char) (c)) / BYTEWIDTH] \
|= 1 << (((unsigned char) c) % BYTEWIDTH))
/* Get the next unsigned number in the uncompiled pattern. */
#define GET_UNSIGNED_NUMBER(num) \
{ if (p != pend) \
{ \
PATFETCH (c); \
while (ISDIGIT (c)) \
{ \
if (num < 0) \
num = 0; \
num = num * 10 + c - '0'; \
if (p == pend) \
break; \
PATFETCH (c); \
} \
} \
}
#define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
#define IS_CHAR_CLASS(string) \
(STREQ (string, "alpha") || STREQ (string, "upper") \
|| STREQ (string, "lower") || STREQ (string, "digit") \
|| STREQ (string, "alnum") || STREQ (string, "xdigit") \
|| STREQ (string, "space") || STREQ (string, "print") \
|| STREQ (string, "punct") || STREQ (string, "graph") \
|| STREQ (string, "cntrl") || STREQ (string, "blank"))
#ifndef MATCH_MAY_ALLOCATE
/* If we cannot allocate large objects within re_match_2_internal,
we make the fail stack and register vectors global.
The fail stack, we grow to the maximum size when a regexp
is compiled.
The register vectors, we adjust in size each time we
compile a regexp, according to the number of registers it needs. */
static fail_stack_type fail_stack;
/* Size with which the following vectors are currently allocated.
That is so we can make them bigger as needed,
but never make them smaller. */
static int regs_allocated_size;
static const char ** regstart, ** regend;
static const char ** old_regstart, ** old_regend;
static const char **best_regstart, **best_regend;
static register_info_type *reg_info;
static const char **reg_dummy;
static register_info_type *reg_info_dummy;
/* Make the register vectors big enough for NUM_REGS registers,
but don't make them smaller. */
static
regex_grow_registers (num_regs)
int num_regs;
{
if (num_regs > regs_allocated_size)
{
RETALLOC_IF (regstart, num_regs, const char *);
RETALLOC_IF (regend, num_regs, const char *);
RETALLOC_IF (old_regstart, num_regs, const char *);
RETALLOC_IF (old_regend, num_regs, const char *);
RETALLOC_IF (best_regstart, num_regs, const char *);
RETALLOC_IF (best_regend, num_regs, const char *);
RETALLOC_IF (reg_info, num_regs, register_info_type);
RETALLOC_IF (reg_dummy, num_regs, const char *);
RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
regs_allocated_size = num_regs;
}
}
#endif /* not MATCH_MAY_ALLOCATE */
/* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
Returns one of error codes defined in `regex.h', or zero for success.
Assumes the `allocated' (and perhaps `buffer') and `translate'
fields are set in BUFP on entry.
If it succeeds, results are put in BUFP (if it returns an error, the
contents of BUFP are undefined):
`buffer' is the compiled pattern;
`syntax' is set to SYNTAX;
`used' is set to the length of the compiled pattern;
`fastmap_accurate' is zero;
`re_nsub' is the number of subexpressions in PATTERN;
`not_bol' and `not_eol' are zero;
The `fastmap' and `newline_anchor' fields are neither
examined nor set. */
/* Return, freeing storage we allocated. */
#define FREE_STACK_RETURN(value) \
return (free (compile_stack.stack), value)
static reg_errcode_t
regex_compile (pattern, size, syntax, bufp)
const char *pattern;
int size;
reg_syntax_t syntax;
struct re_pattern_buffer *bufp;
{
/* We fetch characters from PATTERN here. Even though PATTERN is
`char *' (i.e., signed), we declare these variables as unsigned, so
they can be reliably used as array indices. */
register unsigned char c, c1;
/* A random temporary spot in PATTERN. */
const char *p1;
/* Points to the end of the buffer, where we should append. */
register unsigned char *b;
/* Keeps track of unclosed groups. */
compile_stack_type compile_stack;
/* Points to the current (ending) position in the pattern. */
const char *p = pattern;
const char *pend = pattern + size;
/* How to translate the characters in the pattern. */
RE_TRANSLATE_TYPE translate = bufp->translate;
/* Address of the count-byte of the most recently inserted `exactn'
command. This makes it possible to tell if a new exact-match
character can be added to that command or if the character requires
a new `exactn' command. */
unsigned char *pending_exact = 0;
/* Address of start of the most recently finished expression.
This tells, e.g., postfix * where to find the start of its
operand. Reset at the beginning of groups and alternatives. */
unsigned char *laststart = 0;
/* Address of beginning of regexp, or inside of last group. */
unsigned char *begalt;
/* Place in the uncompiled pattern (i.e., the {) to
which to go back if the interval is invalid. */
const char *beg_interval;
/* Address of the place where a forward jump should go to the end of
the containing expression. Each alternative of an `or' -- except the
last -- ends with a forward jump of this sort. */
unsigned char *fixup_alt_jump = 0;
/* Counts open-groups as they are encountered. Remembered for the
matching close-group on the compile stack, so the same register
number is put in the stop_memory as the start_memory. */
regnum_t regnum = 0;
#ifdef DEBUG
DEBUG_PRINT1 ("\nCompiling pattern: ");
if (debug)
{
unsigned debug_count;
for (debug_count = 0; debug_count < size; debug_count++)
putchar (pattern[debug_count]);
putchar ('\n');
}
#endif /* DEBUG */
/* Initialize the compile stack. */
compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
if (compile_stack.stack == NULL)
return REG_ESPACE;
compile_stack.size = INIT_COMPILE_STACK_SIZE;
compile_stack.avail = 0;
/* Initialize the pattern buffer. */
bufp->syntax = syntax;
bufp->fastmap_accurate = 0;
bufp->not_bol = bufp->not_eol = 0;
/* Set `used' to zero, so that if we return an error, the pattern
printer (for debugging) will think there's no pattern. We reset it
at the end. */
bufp->used = 0;
/* Always count groups, whether or not bufp->no_sub is set. */
bufp->re_nsub = 0;
#if !defined (emacs) && !defined (SYNTAX_TABLE)
/* Initialize the syntax table. */
init_syntax_once ();
#endif
if (bufp->allocated == 0)
{
if (bufp->buffer)
{ /* If zero allocated, but buffer is non-null, try to realloc
enough space. This loses if buffer's address is bogus, but
that is the user's responsibility. */
RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
}
else
{ /* Caller did not allocate a buffer. Do it for them. */
bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
}
if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
bufp->allocated = INIT_BUF_SIZE;
}
begalt = b = bufp->buffer;
/* Loop through the uncompiled pattern until we're at the end. */
while (p != pend)
{
PATFETCH (c);
switch (c)
{
case '^':
{
if ( /* If at start of pattern, it's an operator. */
p == pattern + 1
/* If context independent, it's an operator. */
|| syntax & RE_CONTEXT_INDEP_ANCHORS
/* Otherwise, depends on what's come before. */
|| at_begline_loc_p (pattern, p, syntax))
BUF_PUSH (begline);
else
goto normal_char;
}
break;
case '$':
{
if ( /* If at end of pattern, it's an operator. */
p == pend
/* If context independent, it's an operator. */
|| syntax & RE_CONTEXT_INDEP_ANCHORS
/* Otherwise, depends on what's next. */
|| at_endline_loc_p (p, pend, syntax))
BUF_PUSH (endline);
else
goto normal_char;
}
break;
case '+':
case '?':
if ((syntax & RE_BK_PLUS_QM)
|| (syntax & RE_LIMITED_OPS))
goto normal_char;
handle_plus:
case '*':
/* If there is no previous pattern... */
if (!laststart)
{
if (syntax & RE_CONTEXT_INVALID_OPS)
FREE_STACK_RETURN (REG_BADRPT);
else if (!(syntax & RE_CONTEXT_INDEP_OPS))
goto normal_char;
}
{
/* Are we optimizing this jump? */
boolean keep_string_p = false;
/* 1 means zero (many) matches is allowed. */
char zero_times_ok = 0, many_times_ok = 0;
/* If there is a sequence of repetition chars, collapse it
down to just one (the right one). We can't combine
interval operators with these because of, e.g., `a{2}*',
which should only match an even number of `a's. */
for (;;)
{
zero_times_ok |= c != '+';
many_times_ok |= c != '?';
if (p == pend)
break;
PATFETCH (c);
if (c == '*'
|| (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
;
else if (syntax & RE_BK_PLUS_QM && c == '\\')
{
if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
PATFETCH (c1);
if (!(c1 == '+' || c1 == '?'))
{
PATUNFETCH;
PATUNFETCH;
break;
}
c = c1;
}
else
{
PATUNFETCH;
break;
}
/* If we get here, we found another repeat character. */
}
/* Star, etc. applied to an empty pattern is equivalent
to an empty pattern. */
if (!laststart)
break;
/* Now we know whether or not zero matches is allowed
and also whether or not two or more matches is allowed. */
if (many_times_ok)
{ /* More than one repetition is allowed, so put in at the
end a backward relative jump from `b' to before the next
jump we're going to put in below (which jumps from
laststart to after this jump).
But if we are at the `*' in the exact sequence `.*\n',
insert an unconditional jump backwards to the .,
instead of the beginning of the loop. This way we only
push a failure point once, instead of every time
through the loop. */
assert (p - 1 > pattern);
/* Allocate the space for the jump. */
GET_BUFFER_SPACE (3);
/* We know we are not at the first character of the pattern,
because laststart was nonzero. And we've already
incremented `p', by the way, to be the character after
the `*'. Do we have to do something analogous here
for null bytes, because of RE_DOT_NOT_NULL? */
if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
&& zero_times_ok
&& p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
&& !(syntax & RE_DOT_NEWLINE))
{ /* We have .*\n. */
STORE_JUMP (jump, b, laststart);
keep_string_p = true;
}
else
/* Anything else. */
STORE_JUMP (maybe_pop_jump, b, laststart - 3);
/* We've added more stuff to the buffer. */
b += 3;
}
/* On failure, jump from laststart to b + 3, which will be the
end of the buffer after this jump is inserted. */
GET_BUFFER_SPACE (3);
INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
: on_failure_jump,
laststart, b + 3);
pending_exact = 0;
b += 3;
if (!zero_times_ok)
{
/* At least one repetition is required, so insert a
`dummy_failure_jump' before the initial
`on_failure_jump' instruction of the loop. This
effects a skip over that instruction the first time
we hit that loop. */
GET_BUFFER_SPACE (3);
INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
b += 3;
}
}
break;
case '.':
laststart = b;
BUF_PUSH (anychar);
break;
case '[':
{
boolean had_char_class = false;
if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
/* Ensure that we have enough space to push a charset: the
opcode, the length count, and the bitset; 34 bytes in all. */
GET_BUFFER_SPACE (34);
laststart = b;
/* We test `*p == '^' twice, instead of using an if
statement, so we only need one BUF_PUSH. */
BUF_PUSH (*p == '^' ? charset_not : charset);
if (*p == '^')
p++;
/* Remember the first position in the bracket expression. */
p1 = p;
/* Push the number of bytes in the bitmap. */
BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
/* Clear the whole map. */
bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
/* charset_not matches newline according to a syntax bit. */
if ((re_opcode_t) b[-2] == charset_not
&& (syntax & RE_HAT_LISTS_NOT_NEWLINE))
SET_LIST_BIT ('\n');
/* Read in characters and ranges, setting map bits. */
for (;;)
{
if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
PATFETCH (c);
/* \ might escape characters inside [...] and [^...]. */
if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
{
if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
PATFETCH (c1);
SET_LIST_BIT (c1);
continue;
}
/* Could be the end of the bracket expression. If it's
not (i.e., when the bracket expression is `[]' so
far), the ']' character bit gets set way below. */
if (c == ']' && p != p1 + 1)
break;
/* Look ahead to see if it's a range when the last thing
was a character class. */
if (had_char_class && c == '-' && *p != ']')
FREE_STACK_RETURN (REG_ERANGE);
/* Look ahead to see if it's a range when the last thing
was a character: if this is a hyphen not at the
beginning or the end of a list, then it's the range
operator. */
if (c == '-'
&& !(p - 2 >= pattern && p[-2] == '[')
&& !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
&& *p != ']')
{
reg_errcode_t ret
= compile_range (&p, pend, translate, syntax, b);
if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
}
else if (p[0] == '-' && p[1] != ']')
{ /* This handles ranges made up of characters only. */
reg_errcode_t ret;
/* Move past the `-'. */
PATFETCH (c1);
ret = compile_range (&p, pend, translate, syntax, b);
if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
}
/* See if we're at the beginning of a possible character
class. */
else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
{ /* Leave room for the null. */
char str[CHAR_CLASS_MAX_LENGTH + 1];
PATFETCH (c);
c1 = 0;
/* If pattern is `[[:'. */
if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
for (;;)
{
PATFETCH (c);
if (c == ':' || c == ']' || p == pend
|| c1 == CHAR_CLASS_MAX_LENGTH)
break;
str[c1++] = c;
}
str[c1] = '\0';
/* If isn't a word bracketed by `[:' and:`]':
undo the ending character, the letters, and leave
the leading `:' and `[' (but set bits for them). */
if (c == ':' && *p == ']')
{
int ch;
boolean is_alnum = STREQ (str, "alnum");
boolean is_alpha = STREQ (str, "alpha");
boolean is_blank = STREQ (str, "blank");
boolean is_cntrl = STREQ (str, "cntrl");
boolean is_digit = STREQ (str, "digit");
boolean is_graph = STREQ (str, "graph");
boolean is_lower = STREQ (str, "lower");
boolean is_print = STREQ (str, "print");
boolean is_punct = STREQ (str, "punct");
boolean is_space = STREQ (str, "space");
boolean is_upper = STREQ (str, "upper");
boolean is_xdigit = STREQ (str, "xdigit");
if (!IS_CHAR_CLASS (str))
FREE_STACK_RETURN (REG_ECTYPE);
/* Throw away the ] at the end of the character
class. */
PATFETCH (c);
if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
{
int translated = TRANSLATE (ch);
/* This was split into 3 if's to
avoid an arbitrary limit in some compiler. */
if ( (is_alnum && ISALNUM (ch))
|| (is_alpha && ISALPHA (ch))
|| (is_blank && ISBLANK (ch))
|| (is_cntrl && ISCNTRL (ch)))
SET_LIST_BIT (translated);
if ( (is_digit && ISDIGIT (ch))
|| (is_graph && ISGRAPH (ch))
|| (is_lower && ISLOWER (ch))
|| (is_print && ISPRINT (ch)))
SET_LIST_BIT (translated);
if ( (is_punct && ISPUNCT (ch))
|| (is_space && ISSPACE (ch))
|| (is_upper && ISUPPER (ch))
|| (is_xdigit && ISXDIGIT (ch)))
SET_LIST_BIT (translated);
}
had_char_class = true;
}
else
{
c1++;
while (c1--)
PATUNFETCH;
SET_LIST_BIT ('[');
SET_LIST_BIT (':');
had_char_class = false;
}
}
else
{
had_char_class = false;
SET_LIST_BIT (c);
}
}
/* Discard any (non)matching list bytes that are all 0 at the
end of the map. Decrease the map-length byte too. */
while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
b[-1]--;
b += b[-1];
}
break;
case '(':
if (syntax & RE_NO_BK_PARENS)
goto handle_open;
else
goto normal_char;
case ')':
if (syntax & RE_NO_BK_PARENS)
goto handle_close;
else
goto normal_char;
case '\n':
if (syntax & RE_NEWLINE_ALT)
goto handle_alt;
else
goto normal_char;
case '|':
if (syntax & RE_NO_BK_VBAR)
goto handle_alt;
else
goto normal_char;
case '{':
if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
goto handle_interval;
else
goto normal_char;
case '\\':
if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
/* Do not translate the character after the \, so that we can
distinguish, e.g., \B from \b, even if we normally would
translate, e.g., B to b. */
PATFETCH_RAW (c);
switch (c)
{
case '(':
if (syntax & RE_NO_BK_PARENS)
goto normal_backslash;
handle_open:
bufp->re_nsub++;
regnum++;
if (COMPILE_STACK_FULL)
{
RETALLOC (compile_stack.stack, compile_stack.size << 1,
compile_stack_elt_t);
if (compile_stack.stack == NULL) return REG_ESPACE;
compile_stack.size <<= 1;
}
/* These are the values to restore when we hit end of this
group. They are all relative offsets, so that if the
whole pattern moves because of realloc, they will still
be valid. */
COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
COMPILE_STACK_TOP.fixup_alt_jump
= fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
COMPILE_STACK_TOP.regnum = regnum;
/* We will eventually replace the 0 with the number of
groups inner to this one. But do not push a
start_memory for groups beyond the last one we can
represent in the compiled pattern. */
if (regnum <= MAX_REGNUM)
{
COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
BUF_PUSH_3 (start_memory, regnum, 0);
}
compile_stack.avail++;
fixup_alt_jump = 0;
laststart = 0;
begalt = b;
/* If we've reached MAX_REGNUM groups, then this open
won't actually generate any code, so we'll have to
clear pending_exact explicitly. */
pending_exact = 0;
break;
case ')':
if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
if (COMPILE_STACK_EMPTY)
{
if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
goto normal_backslash;
else
FREE_STACK_RETURN (REG_ERPAREN);
}
handle_close:
if (fixup_alt_jump)
{ /* Push a dummy failure point at the end of the
alternative for a possible future
`pop_failure_jump' to pop. See comments at
`push_dummy_failure' in `re_match_2'. */
BUF_PUSH (push_dummy_failure);
/* We allocated space for this jump when we assigned
to `fixup_alt_jump', in the `handle_alt' case below. */
STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
}
/* See similar code for backslashed left paren above. */
if (COMPILE_STACK_EMPTY)
{
if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
goto normal_char;
else
FREE_STACK_RETURN (REG_ERPAREN);
}
/* Since we just checked for an empty stack above, this
``can't happen''. */
assert (compile_stack.avail != 0);
{
/* We don't just want to restore into `regnum', because
later groups should continue to be numbered higher,
as in `(ab)c(de)' -- the second group is #2. */
regnum_t this_group_regnum;
compile_stack.avail--;
begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
fixup_alt_jump
= COMPILE_STACK_TOP.fixup_alt_jump
? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
: 0;
laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
this_group_regnum = COMPILE_STACK_TOP.regnum;
/* If we've reached MAX_REGNUM groups, then this open
won't actually generate any code, so we'll have to
clear pending_exact explicitly. */
pending_exact = 0;
/* We're at the end of the group, so now we know how many
groups were inside this one. */
if (this_group_regnum <= MAX_REGNUM)
{
unsigned char *inner_group_loc
= bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
*inner_group_loc = regnum - this_group_regnum;
BUF_PUSH_3 (stop_memory, this_group_regnum,
regnum - this_group_regnum);
}
}
break;
case '|': /* `\|'. */
if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
goto normal_backslash;
handle_alt:
if (syntax & RE_LIMITED_OPS)
goto normal_char;
/* Insert before the previous alternative a jump which
jumps to this alternative if the former fails. */
GET_BUFFER_SPACE (3);
INSERT_JUMP (on_failure_jump, begalt, b + 6);
pending_exact = 0;
b += 3;
/* The alternative before this one has a jump after it
which gets executed if it gets matched. Adjust that
jump so it will jump to this alternative's analogous
jump (put in below, which in turn will jump to the next
(if any) alternative's such jump, etc.). The last such
jump jumps to the correct final destination. A picture:
_____ _____
| | | |
| v | v
a | b | c
If we are at `b', then fixup_alt_jump right now points to a
three-byte space after `a'. We'll put in the jump, set
fixup_alt_jump to right after `b', and leave behind three
bytes which we'll fill in when we get to after `c'. */
if (fixup_alt_jump)
STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
/* Mark and leave space for a jump after this alternative,
to be filled in later either by next alternative or
when know we're at the end of a series of alternatives. */
fixup_alt_jump = b;
GET_BUFFER_SPACE (3);
b += 3;
laststart = 0;
begalt = b;
break;
case '{':
/* If \{ is a literal. */
if (!(syntax & RE_INTERVALS)
/* If we're at `\{' and it's not the open-interval
operator. */
|| ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
|| (p - 2 == pattern && p == pend))
goto normal_backslash;
handle_interval:
{
/* If got here, then the syntax allows intervals. */
/* At least (most) this many matches must be made. */
int lower_bound = -1, upper_bound = -1;
beg_interval = p - 1;
if (p == pend)
{
if (syntax & RE_NO_BK_BRACES)
goto unfetch_interval;
else
FREE_STACK_RETURN (REG_EBRACE);
}
GET_UNSIGNED_NUMBER (lower_bound);
if (c == ',')
{
GET_UNSIGNED_NUMBER (upper_bound);
if (upper_bound < 0) upper_bound = RE_DUP_MAX;
}
else
/* Interval such as `{1}' => match exactly once. */
upper_bound = lower_bound;
if (lower_bound < 0 || upper_bound > RE_DUP_MAX
|| lower_bound > upper_bound)
{
if (syntax & RE_NO_BK_BRACES)
goto unfetch_interval;
else
FREE_STACK_RETURN (REG_BADBR);
}
if (!(syntax & RE_NO_BK_BRACES))
{
if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
PATFETCH (c);
}
if (c != '}')
{
if (syntax & RE_NO_BK_BRACES)
goto unfetch_interval;
else
FREE_STACK_RETURN (REG_BADBR);
}
/* We just parsed a valid interval. */
/* If it's invalid to have no preceding re. */
if (!laststart)
{
if (syntax & RE_CONTEXT_INVALID_OPS)
FREE_STACK_RETURN (REG_BADRPT);
else if (syntax & RE_CONTEXT_INDEP_OPS)
laststart = b;
else
goto unfetch_interval;
}
/* If the upper bound is zero, don't want to succeed at
all; jump from `laststart' to `b + 3', which will be
the end of the buffer after we insert the jump. */
if (upper_bound == 0)
{
GET_BUFFER_SPACE (3);
INSERT_JUMP (jump, laststart, b + 3);
b += 3;
}
/* Otherwise, we have a nontrivial interval. When
we're all done, the pattern will look like:
set_number_at
set_number_at
succeed_n
jump_n
(The upper bound and `jump_n' are omitted if
`upper_bound' is 1, though.) */
else
{ /* If the upper bound is > 1, we need to insert
more at the end of the loop. */
unsigned nbytes = 10 + (upper_bound > 1) * 10;
GET_BUFFER_SPACE (nbytes);
/* Initialize lower bound of the `succeed_n', even
though it will be set during matching by its
attendant `set_number_at' (inserted next),
because `re_compile_fastmap' needs to know.
Jump to the `jump_n' we might insert below. */
INSERT_JUMP2 (succeed_n, laststart,
b + 5 + (upper_bound > 1) * 5,
lower_bound);
b += 5;
/* Code to initialize the lower bound. Insert
before the `succeed_n'. The `5' is the last two
bytes of this `set_number_at', plus 3 bytes of
the following `succeed_n'. */
insert_op2 (set_number_at, laststart, 5, lower_bound, b);
b += 5;
if (upper_bound > 1)
{ /* More than one repetition is allowed, so
append a backward jump to the `succeed_n'
that starts this interval.
When we've reached this during matching,
we'll have matched the interval once, so
jump back only `upper_bound - 1' times. */
STORE_JUMP2 (jump_n, b, laststart + 5,
upper_bound - 1);
b += 5;
/* The location we want to set is the second
parameter of the `jump_n'; that is `b-2' as
an absolute address. `laststart' will be
the `set_number_at' we're about to insert;
`laststart+3' the number to set, the source
for the relative address. But we are
inserting into the middle of the pattern --
so everything is getting moved up by 5.
Conclusion: (b - 2) - (laststart + 3) + 5,
i.e., b - laststart.
We insert this at the beginning of the loop
so that if we fail during matching, we'll
reinitialize the bounds. */
insert_op2 (set_number_at, laststart, b - laststart,
upper_bound - 1, b);
b += 5;
}
}
pending_exact = 0;
beg_interval = NULL;
}
break;
unfetch_interval:
/* If an invalid interval, match the characters as literals. */
assert (beg_interval);
p = beg_interval;
beg_interval = NULL;
/* normal_char and normal_backslash need `c'. */
PATFETCH (c);
if (!(syntax & RE_NO_BK_BRACES))
{
if (p > pattern && p[-1] == '\\')
goto normal_backslash;
}
goto normal_char;
#ifdef emacs
/* There is no way to specify the before_dot and after_dot
operators. rms says this is ok. --karl */
case '=':
BUF_PUSH (at_dot);
break;
case 's':
laststart = b;
PATFETCH (c);
BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
break;
case 'S':
laststart = b;
PATFETCH (c);
BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
break;
#endif /* emacs */
case 'w':
laststart = b;
BUF_PUSH (wordchar);
break;
case 'W':
laststart = b;
BUF_PUSH (notwordchar);
break;
case '<':
BUF_PUSH (wordbeg);
break;
case '>':
BUF_PUSH (wordend);
break;
case 'b':
BUF_PUSH (wordbound);
break;
case 'B':
BUF_PUSH (notwordbound);
break;
case '`':
BUF_PUSH (begbuf);
break;
case '\'':
BUF_PUSH (endbuf);
break;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
if (syntax & RE_NO_BK_REFS)
goto normal_char;
c1 = c - '0';
if (c1 > regnum)
FREE_STACK_RETURN (REG_ESUBREG);
/* Can't back reference to a subexpression if inside of it. */
if (group_in_compile_stack (compile_stack, c1))
goto normal_char;
laststart = b;
BUF_PUSH_2 (duplicate, c1);
break;
case '+':
case '?':
if (syntax & RE_BK_PLUS_QM)
goto handle_plus;
else
goto normal_backslash;
default:
normal_backslash:
/* You might think it would be useful for \ to mean
not to translate; but if we don't translate it
it will never match anything. */
c = TRANSLATE (c);
goto normal_char;
}
break;
default:
/* Expects the character in `c'. */
normal_char:
/* If no exactn currently being built. */
if (!pending_exact
/* If last exactn not at current position. */
|| pending_exact + *pending_exact + 1 != b
/* We have only one byte following the exactn for the count. */
|| *pending_exact == (1 << BYTEWIDTH) - 1
/* If followed by a repetition operator. */
|| *p == '*' || *p == '^'
|| ((syntax & RE_BK_PLUS_QM)
? *p == '\\' && (p[1] == '+' || p[1] == '?')
: (*p == '+' || *p == '?'))
|| ((syntax & RE_INTERVALS)
&& ((syntax & RE_NO_BK_BRACES)
? *p == '{'
: (p[0] == '\\' && p[1] == '{'))))
{
/* Start building a new exactn. */
laststart = b;
BUF_PUSH_2 (exactn, 0);
pending_exact = b - 1;
}
BUF_PUSH (c);
(*pending_exact)++;
break;
} /* switch (c) */
} /* while p != pend */
/* Through the pattern now. */
if (fixup_alt_jump)
STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
if (!COMPILE_STACK_EMPTY)
FREE_STACK_RETURN (REG_EPAREN);
/* If we don't want backtracking, force success
the first time we reach the end of the compiled pattern. */
if (syntax & RE_NO_POSIX_BACKTRACKING)
BUF_PUSH (succeed);
free (compile_stack.stack);
/* We have succeeded; set the length of the buffer. */
bufp->used = b - bufp->buffer;
#ifdef DEBUG
if (debug)
{
DEBUG_PRINT1 ("\nCompiled pattern: \n");
print_compiled_pattern (bufp);
}
#endif /* DEBUG */
#ifndef MATCH_MAY_ALLOCATE
/* Initialize the failure stack to the largest possible stack. This
isn't necessary unless we're trying to avoid calling alloca in
the search and match routines. */
{
int num_regs = bufp->re_nsub + 1;
/* Since DOUBLE_FAIL_STACK refuses to double only if the current size
is strictly greater than re_max_failures, the largest possible stack
is 2 * re_max_failures failure points. */
if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
{
fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
#ifdef emacs
if (! fail_stack.stack)
fail_stack.stack
= (fail_stack_elt_t *) xmalloc (fail_stack.size
* sizeof (fail_stack_elt_t));
else
fail_stack.stack
= (fail_stack_elt_t *) xrealloc (fail_stack.stack,
(fail_stack.size
* sizeof (fail_stack_elt_t)));
#else /* not emacs */
if (! fail_stack.stack)
fail_stack.stack
= (fail_stack_elt_t *) malloc (fail_stack.size
* sizeof (fail_stack_elt_t));
else
fail_stack.stack
= (fail_stack_elt_t *) realloc (fail_stack.stack,
(fail_stack.size
* sizeof (fail_stack_elt_t)));
#endif /* not emacs */
}
regex_grow_registers (num_regs);
}
#endif /* not MATCH_MAY_ALLOCATE */
return REG_NOERROR;
} /* regex_compile */
/* Subroutines for `regex_compile'. */
/* Store OP at LOC followed by two-byte integer parameter ARG. */
static void
store_op1 (op, loc, arg)
re_opcode_t op;
unsigned char *loc;
int arg;
{
*loc = (unsigned char) op;
STORE_NUMBER (loc + 1, arg);
}
/* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
static void
store_op2 (op, loc, arg1, arg2)
re_opcode_t op;
unsigned char *loc;
int arg1, arg2;
{
*loc = (unsigned char) op;
STORE_NUMBER (loc + 1, arg1);
STORE_NUMBER (loc + 3, arg2);
}
/* Copy the bytes from LOC to END to open up three bytes of space at LOC
for OP followed by two-byte integer parameter ARG. */
static void
insert_op1 (op, loc, arg, end)
re_opcode_t op;
unsigned char *loc;
int arg;
unsigned char *end;
{
register unsigned char *pfrom = end;
register unsigned char *pto = end + 3;
while (pfrom != loc)
*--pto = *--pfrom;
store_op1 (op, loc, arg);
}
/* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
static void
insert_op2 (op, loc, arg1, arg2, end)
re_opcode_t op;
unsigned char *loc;
int arg1, arg2;
unsigned char *end;
{
register unsigned char *pfrom = end;
register unsigned char *pto = end + 5;
while (pfrom != loc)
*--pto = *--pfrom;
store_op2 (op, loc, arg1, arg2);
}
/* P points to just after a ^ in PATTERN. Return true if that ^ comes
after an alternative or a begin-subexpression. We assume there is at
least one character before the ^. */
static boolean
at_begline_loc_p (pattern, p, syntax)
const char *pattern, *p;
reg_syntax_t syntax;
{
const char *prev = p - 2;
boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
return
/* After a subexpression? */
(*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
/* After an alternative? */
|| (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
}
/* The dual of at_begline_loc_p. This one is for $. We assume there is
at least one character after the $, i.e., `P < PEND'. */
static boolean
at_endline_loc_p (p, pend, syntax)
const char *p, *pend;
int syntax;
{
const char *next = p;
boolean next_backslash = *next == '\\';
const char *next_next = p + 1 < pend ? p + 1 : 0;
return
/* Before a subexpression? */
(syntax & RE_NO_BK_PARENS ? *next == ')'
: next_backslash && next_next && *next_next == ')')
/* Before an alternative? */
|| (syntax & RE_NO_BK_VBAR ? *next == '|'
: next_backslash && next_next && *next_next == '|');
}
/* Returns true if REGNUM is in one of COMPILE_STACK's elements and
false if it's not. */
static boolean
group_in_compile_stack (compile_stack, regnum)
compile_stack_type compile_stack;
regnum_t regnum;
{
int this_element;
for (this_element = compile_stack.avail - 1;
this_element >= 0;
this_element--)
if (compile_stack.stack[this_element].regnum == regnum)
return true;
return false;
}
/* Read the ending character of a range (in a bracket expression) from the
uncompiled pattern *P_PTR (which ends at PEND). We assume the
starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
Then we set the translation of all bits between the starting and
ending characters (inclusive) in the compiled pattern B.
Return an error code.
We use these short variable names so we can use the same macros as
`regex_compile' itself. */
static reg_errcode_t
compile_range (p_ptr, pend, translate, syntax, b)
const char **p_ptr, *pend;
RE_TRANSLATE_TYPE translate;
reg_syntax_t syntax;
unsigned char *b;
{
unsigned this_char;
const char *p = *p_ptr;
int range_start, range_end;
if (p == pend)
return REG_ERANGE;
/* Even though the pattern is a signed `char *', we need to fetch
with unsigned char *'s; if the high bit of the pattern character
is set, the range endpoints will be negative if we fetch using a
signed char *.
We also want to fetch the endpoints without translating them; the
appropriate translation is done in the bit-setting loop below. */
/* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
range_start = ((const unsigned char *) p)[-2];
range_end = ((const unsigned char *) p)[0];
/* Have to increment the pointer into the pattern string, so the
caller isn't still at the ending character. */
(*p_ptr)++;
/* If the start is after the end, the range is empty. */
if (range_start > range_end)
return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
/* Here we see why `this_char' has to be larger than an `unsigned
char' -- the range is inclusive, so if `range_end' == 0xff
(assuming 8-bit characters), we would otherwise go into an infinite
loop, since all characters <= 0xff. */
for (this_char = range_start; this_char <= range_end; this_char++)
{
SET_LIST_BIT (TRANSLATE (this_char));
}
return REG_NOERROR;
}
/* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
characters can start a string that matches the pattern. This fastmap
is used by re_search to skip quickly over impossible starting points.
The caller must supply the address of a (1 << BYTEWIDTH)-byte data
area as BUFP->fastmap.
We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
the pattern buffer.
Returns 0 if we succeed, -2 if an internal error. */
int
re_compile_fastmap (bufp)
struct re_pattern_buffer *bufp;
{
int j, k;
#ifdef MATCH_MAY_ALLOCATE
fail_stack_type fail_stack;
#endif
#ifndef REGEX_MALLOC
char *destination;
#endif
/* We don't push any register information onto the failure stack. */
unsigned num_regs = 0;
register char *fastmap = bufp->fastmap;
unsigned char *pattern = bufp->buffer;
unsigned long size = bufp->used;
unsigned char *p = pattern;
register unsigned char *pend = pattern + size;
/* This holds the pointer to the failure stack, when
it is allocated relocatably. */
#ifdef REL_ALLOC
fail_stack_elt_t *failure_stack_ptr;
#endif
/* Assume that each path through the pattern can be null until
proven otherwise. We set this false at the bottom of switch
statement, to which we get only if a particular path doesn't
match the empty string. */
boolean path_can_be_null = true;
/* We aren't doing a `succeed_n' to begin with. */
boolean succeed_n_p = false;
assert (fastmap != NULL && p != NULL);
INIT_FAIL_STACK ();
bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
bufp->fastmap_accurate = 1; /* It will be when we're done. */
bufp->can_be_null = 0;
while (1)
{
if (p == pend || *p == succeed)
{
/* We have reached the (effective) end of pattern. */
if (!FAIL_STACK_EMPTY ())
{
bufp->can_be_null |= path_can_be_null;
/* Reset for next path. */
path_can_be_null = true;
p = fail_stack.stack[--fail_stack.avail].pointer;
continue;
}
else
break;
}
/* We should never be about to go beyond the end of the pattern. */
assert (p < pend);
switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
{
/* I guess the idea here is to simply not bother with a fastmap
if a backreference is used, since it's too hard to figure out
the fastmap for the corresponding group. Setting
`can_be_null' stops `re_search_2' from using the fastmap, so
that is all we do. */
case duplicate:
bufp->can_be_null = 1;
goto done;
/* Following are the cases which match a character. These end
with `break'. */
case exactn:
fastmap[p[1]] = 1;
break;
case charset:
for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
fastmap[j] = 1;
break;
case charset_not:
/* Chars beyond end of map must be allowed. */
for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
fastmap[j] = 1;
for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
fastmap[j] = 1;
break;
case wordchar:
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) == Sword)
fastmap[j] = 1;
break;
case notwordchar:
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) != Sword)
fastmap[j] = 1;
break;
case anychar:
{
int fastmap_newline = fastmap['\n'];
/* `.' matches anything ... */
for (j = 0; j < (1 << BYTEWIDTH); j++)
fastmap[j] = 1;
/* ... except perhaps newline. */
if (!(bufp->syntax & RE_DOT_NEWLINE))
fastmap['\n'] = fastmap_newline;
/* Return if we have already set `can_be_null'; if we have,
then the fastmap is irrelevant. Something's wrong here. */
else if (bufp->can_be_null)
goto done;
/* Otherwise, have to check alternative paths. */
break;
}
#ifdef emacs
case syntaxspec:
k = *p++;
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) == (enum syntaxcode) k)
fastmap[j] = 1;
break;
case notsyntaxspec:
k = *p++;
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) != (enum syntaxcode) k)
fastmap[j] = 1;
break;
/* All cases after this match the empty string. These end with
`continue'. */
case before_dot:
case at_dot:
case after_dot:
continue;
#endif /* emacs */
case no_op:
case begline:
case endline:
case begbuf:
case endbuf:
case wordbound:
case notwordbound:
case wordbeg:
case wordend:
case push_dummy_failure:
continue;
case jump_n:
case pop_failure_jump:
case maybe_pop_jump:
case jump:
case jump_past_alt:
case dummy_failure_jump:
EXTRACT_NUMBER_AND_INCR (j, p);
p += j;
if (j > 0)
continue;
/* Jump backward implies we just went through the body of a
loop and matched nothing. Opcode jumped to should be
`on_failure_jump' or `succeed_n'. Just treat it like an
ordinary jump. For a * loop, it has pushed its failure
point already; if so, discard that as redundant. */
if ((re_opcode_t) *p != on_failure_jump
&& (re_opcode_t) *p != succeed_n)
continue;
p++;
EXTRACT_NUMBER_AND_INCR (j, p);
p += j;
/* If what's on the stack is where we are now, pop it. */
if (!FAIL_STACK_EMPTY ()
&& fail_stack.stack[fail_stack.avail - 1].pointer == p)
fail_stack.avail--;
continue;
case on_failure_jump:
case on_failure_keep_string_jump:
handle_on_failure_jump:
EXTRACT_NUMBER_AND_INCR (j, p);
/* For some patterns, e.g., `(a?)?', `p+j' here points to the
end of the pattern. We don't want to push such a point,
since when we restore it above, entering the switch will
increment `p' past the end of the pattern. We don't need
to push such a point since we obviously won't find any more
fastmap entries beyond `pend'. Such a pattern can match
the null string, though. */
if (p + j < pend)
{
if (!PUSH_PATTERN_OP (p + j, fail_stack))
{
RESET_FAIL_STACK ();
return -2;
}
}
else
bufp->can_be_null = 1;
if (succeed_n_p)
{
EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
succeed_n_p = false;
}
continue;
case succeed_n:
/* Get to the number of times to succeed. */
p += 2;
/* Increment p past the n for when k != 0. */
EXTRACT_NUMBER_AND_INCR (k, p);
if (k == 0)
{
p -= 4;
succeed_n_p = true; /* Spaghetti code alert. */
goto handle_on_failure_jump;
}
continue;
case set_number_at:
p += 4;
continue;
case start_memory:
case stop_memory:
p += 2;
continue;
default:
abort (); /* We have listed all the cases. */
} /* switch *p++ */
/* Getting here means we have found the possible starting
characters for one path of the pattern -- and that the empty
string does not match. We need not follow this path further.
Instead, look at the next alternative (remembered on the
stack), or quit if no more. The test at the top of the loop
does these things. */
path_can_be_null = false;
p = pend;
} /* while p */
/* Set `can_be_null' for the last path (also the first path, if the
pattern is empty). */
bufp->can_be_null |= path_can_be_null;
done:
RESET_FAIL_STACK ();
return 0;
} /* re_compile_fastmap */
/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
this memory for recording register information. STARTS and ENDS
must be allocated using the malloc library routine, and must each
be at least NUM_REGS * sizeof (regoff_t) bytes long.
If NUM_REGS == 0, then subsequent matches should allocate their own
register data.
Unless this function is called, the first search or match using
PATTERN_BUFFER will allocate its own register data, without
freeing the old data. */
void
re_set_registers (bufp, regs, num_regs, starts, ends)
struct re_pattern_buffer *bufp;
struct re_registers *regs;
unsigned num_regs;
regoff_t *starts, *ends;
{
if (num_regs)
{
bufp->regs_allocated = REGS_REALLOCATE;
regs->num_regs = num_regs;
regs->start = starts;
regs->end = ends;
}
else
{
bufp->regs_allocated = REGS_UNALLOCATED;
regs->num_regs = 0;
regs->start = regs->end = (regoff_t *) 0;
}
}
/* Searching routines. */
/* Like re_search_2, below, but only one string is specified, and
doesn't let you say where to stop matching. */
int
re_search (bufp, string, size, startpos, range, regs)
struct re_pattern_buffer *bufp;
const char *string;
int size, startpos, range;
struct re_registers *regs;
{
return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
regs, size);
}
/* Using the compiled pattern in BUFP->buffer, first tries to match the
virtual concatenation of STRING1 and STRING2, starting first at index
STARTPOS, then at STARTPOS + 1, and so on.
STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
RANGE is how far to scan while trying to match. RANGE = 0 means try
only at STARTPOS; in general, the last start tried is STARTPOS +
RANGE.
In REGS, return the indices of the virtual concatenation of STRING1
and STRING2 that matched the entire BUFP->buffer and its contained
subexpressions.
Do not consider matching one past the index STOP in the virtual
concatenation of STRING1 and STRING2.
We return either the position in the strings at which the match was
found, -1 if no match, or -2 if error (such as failure
stack overflow). */
int
re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
struct re_pattern_buffer *bufp;
const char *string1, *string2;
int size1, size2;
int startpos;
int range;
struct re_registers *regs;
int stop;
{
int val;
register char *fastmap = bufp->fastmap;
register RE_TRANSLATE_TYPE translate = bufp->translate;
int total_size = size1 + size2;
int endpos = startpos + range;
int anchored_start = 0;
/* Check for out-of-range STARTPOS. */
if (startpos < 0 || startpos > total_size)
return -1;
/* Fix up RANGE if it might eventually take us outside
the virtual concatenation of STRING1 and STRING2.
Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
if (endpos < 0)
range = 0 - startpos;
else if (endpos > total_size)
range = total_size - startpos;
/* If the search isn't to be a backwards one, don't waste time in a
search for a pattern that must be anchored. */
if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
{
if (startpos > 0)
return -1;
else
range = 1;
}
#ifdef emacs
/* In a forward search for something that starts with \=.
don't keep searching past point. */
if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
{
range = PT - startpos;
if (range <= 0)
return -1;
}
#endif /* emacs */
/* Update the fastmap now if not correct already. */
if (fastmap && !bufp->fastmap_accurate)
if (re_compile_fastmap (bufp) == -2)
return -2;
/* See whether the pattern is anchored. */
if (bufp->buffer[0] == begline)
anchored_start = 1;
/* Loop through the string, looking for a place to start matching. */
for (;;)
{
/* If the pattern is anchored,
skip quickly past places we cannot match.
We don't bother to treat startpos == 0 specially
because that case doesn't repeat. */
if (anchored_start && startpos > 0)
{
if (! (bufp->newline_anchor
&& ((startpos <= size1 ? string1[startpos - 1]
: string2[startpos - size1 - 1])
== '\n')))
goto advance;
}
/* If a fastmap is supplied, skip quickly over characters that
cannot be the start of a match. If the pattern can match the
null string, however, we don't need to skip characters; we want
the first null string. */
if (fastmap && startpos < total_size && !bufp->can_be_null)
{
if (range > 0) /* Searching forwards. */
{
register const char *d;
register int lim = 0;
int irange = range;
if (startpos < size1 && startpos + range >= size1)
lim = range - (size1 - startpos);
d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
/* Written out as an if-else to avoid testing `translate'
inside the loop. */
if (translate)
while (range > lim
&& !fastmap[(unsigned char)
translate[(unsigned char) *d++]])
range--;
else
while (range > lim && !fastmap[(unsigned char) *d++])
range--;
startpos += irange - range;
}
else /* Searching backwards. */
{
register char c = (size1 == 0 || startpos >= size1
? string2[startpos - size1]
: string1[startpos]);
if (!fastmap[(unsigned char) TRANSLATE (c)])
goto advance;
}
}
/* If can't match the null string, and that's all we have left, fail. */
if (range >= 0 && startpos == total_size && fastmap
&& !bufp->can_be_null)
return -1;
val = re_match_2_internal (bufp, string1, size1, string2, size2,
startpos, regs, stop);
#ifndef REGEX_MALLOC
#ifdef C_ALLOCA
alloca (0);
#endif
#endif
if (val >= 0)
return startpos;
if (val == -2)
return -2;
advance:
if (!range)
break;
else if (range > 0)
{
range--;
startpos++;
}
else
{
range++;
startpos--;
}
}
return -1;
} /* re_search_2 */
/* Declarations and macros for re_match_2. */
static int bcmp_translate ();
static boolean alt_match_null_string_p (),
common_op_match_null_string_p (),
group_match_null_string_p ();
/* This converts PTR, a pointer into one of the search strings `string1'
and `string2' into an offset from the beginning of that string. */
#define POINTER_TO_OFFSET(ptr) \
(FIRST_STRING_P (ptr) \
? ((regoff_t) ((ptr) - string1)) \
: ((regoff_t) ((ptr) - string2 + size1)))
/* Macros for dealing with the split strings in re_match_2. */
#define MATCHING_IN_FIRST_STRING (dend == end_match_1)
/* Call before fetching a character with *d. This switches over to
string2 if necessary. */
#define PREFETCH() \
while (d == dend) \
{ \
/* End of string2 => fail. */ \
if (dend == end_match_2) \
goto fail; \
/* End of string1 => advance to string2. */ \
d = string2; \
dend = end_match_2; \
}
/* Test if at very beginning or at very end of the virtual concatenation
of `string1' and `string2'. If only one string, it's `string2'. */
#define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
#define AT_STRINGS_END(d) ((d) == end2)
/* Test if D points to a character which is word-constituent. We have
two special cases to check for: if past the end of string1, look at
the first character in string2; and if before the beginning of
string2, look at the last character in string1. */
#define WORDCHAR_P(d) \
(SYNTAX ((d) == end1 ? *string2 \
: (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
== Sword)
/* Disabled due to a compiler bug -- see comment at case wordbound */
#if 0
/* Test if the character before D and the one at D differ with respect
to being word-constituent. */
#define AT_WORD_BOUNDARY(d) \
(AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
|| WORDCHAR_P (d - 1) != WORDCHAR_P (d))
#endif
/* Free everything we malloc. */
#ifdef MATCH_MAY_ALLOCATE
#define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
#define FREE_VARIABLES() \
do { \
REGEX_FREE_STACK (fail_stack.stack); \
FREE_VAR (regstart); \
FREE_VAR (regend); \
FREE_VAR (old_regstart); \
FREE_VAR (old_regend); \
FREE_VAR (best_regstart); \
FREE_VAR (best_regend); \
FREE_VAR (reg_info); \
FREE_VAR (reg_dummy); \
FREE_VAR (reg_info_dummy); \
} while (0)
#else
#define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
#endif /* not MATCH_MAY_ALLOCATE */
/* These values must meet several constraints. They must not be valid
register values; since we have a limit of 255 registers (because
we use only one byte in the pattern for the register number), we can
use numbers larger than 255. They must differ by 1, because of
NUM_FAILURE_ITEMS above. And the value for the lowest register must
be larger than the value for the highest register, so we do not try
to actually save any registers when none are active. */
#define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
#define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
/* Matching routines. */
#ifndef emacs /* Emacs never uses this. */
/* re_match is like re_match_2 except it takes only a single string. */
int
re_match (bufp, string, size, pos, regs)
struct re_pattern_buffer *bufp;
const char *string;
int size, pos;
struct re_registers *regs;
{
int result = re_match_2_internal (bufp, NULL, 0, string, size,
pos, regs, size);
alloca (0);
return result;
}
#endif /* not emacs */
/* re_match_2 matches the compiled pattern in BUFP against the
the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
and SIZE2, respectively). We start matching at POS, and stop
matching at STOP.
If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
store offsets for the substring each group matched in REGS. See the
documentation for exactly how many groups we fill.
We return -1 if no match, -2 if an internal error (such as the
failure stack overflowing). Otherwise, we return the length of the
matched substring. */
int
re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
struct re_pattern_buffer *bufp;
const char *string1, *string2;
int size1, size2;
int pos;
struct re_registers *regs;
int stop;
{
int result = re_match_2_internal (bufp, string1, size1, string2, size2,
pos, regs, stop);
alloca (0);
return result;
}
/* This is a separate function so that we can force an alloca cleanup
afterwards. */
static int
re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
struct re_pattern_buffer *bufp;
const char *string1, *string2;
int size1, size2;
int pos;
struct re_registers *regs;
int stop;
{
/* General temporaries. */
int mcnt;
unsigned char *p1;
/* Just past the end of the corresponding string. */
const char *end1, *end2;
/* Pointers into string1 and string2, just past the last characters in
each to consider matching. */
const char *end_match_1, *end_match_2;
/* Where we are in the data, and the end of the current string. */
const char *d, *dend;
/* Where we are in the pattern, and the end of the pattern. */
unsigned char *p = bufp->buffer;
register unsigned char *pend = p + bufp->used;
/* Mark the opcode just after a start_memory, so we can test for an
empty subpattern when we get to the stop_memory. */
unsigned char *just_past_start_mem = 0;
/* We use this to map every character in the string. */
RE_TRANSLATE_TYPE translate = bufp->translate;
/* Failure point stack. Each place that can handle a failure further
down the line pushes a failure point on this stack. It consists of
restart, regend, and reg_info for all registers corresponding to
the subexpressions we're currently inside, plus the number of such
registers, and, finally, two char *'s. The first char * is where
to resume scanning the pattern; the second one is where to resume
scanning the strings. If the latter is zero, the failure point is
a ``dummy''; if a failure happens and the failure point is a dummy,
it gets discarded and the next next one is tried. */
#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
fail_stack_type fail_stack;
#endif
#ifdef DEBUG
static unsigned failure_id = 0;
unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
#endif
/* This holds the pointer to the failure stack, when
it is allocated relocatably. */
#ifdef REL_ALLOC
fail_stack_elt_t *failure_stack_ptr;
#endif
/* We fill all the registers internally, independent of what we
return, for use in backreferences. The number here includes
an element for register zero. */
unsigned num_regs = bufp->re_nsub + 1;
/* The currently active registers. */
unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
/* Information on the contents of registers. These are pointers into
the input strings; they record just what was matched (on this
attempt) by a subexpression part of the pattern, that is, the
regnum-th regstart pointer points to where in the pattern we began
matching and the regnum-th regend points to right after where we
stopped matching the regnum-th subexpression. (The zeroth register
keeps track of what the whole pattern matches.) */
#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
const char **regstart, **regend;
#endif
/* If a group that's operated upon by a repetition operator fails to
match anything, then the register for its start will need to be
restored because it will have been set to wherever in the string we
are when we last see its open-group operator. Similarly for a
register's end. */
#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
const char **old_regstart, **old_regend;
#endif
/* The is_active field of reg_info helps us keep track of which (possibly
nested) subexpressions we are currently in. The matched_something
field of reg_info[reg_num] helps us tell whether or not we have
matched any of the pattern so far this time through the reg_num-th
subexpression. These two fields get reset each time through any
loop their register is in. */
#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
register_info_type *reg_info;
#endif
/* The following record the register info as found in the above
variables when we find a match better than any we've seen before.
This happens as we backtrack through the failure points, which in
turn happens only if we have not yet matched the entire string. */
unsigned best_regs_set = false;
#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
const char **best_regstart, **best_regend;
#endif
/* Logically, this is `best_regend[0]'. But we don't want to have to
allocate space for that if we're not allocating space for anything
else (see below). Also, we never need info about register 0 for
any of the other register vectors, and it seems rather a kludge to
treat `best_regend' differently than the rest. So we keep track of
the end of the best match so far in a separate variable. We
initialize this to NULL so that when we backtrack the first time
and need to test it, it's not garbage. */
const char *match_end = NULL;
/* This helps SET_REGS_MATCHED avoid doing redundant work. */
int set_regs_matched_done = 0;
/* Used when we pop values we don't care about. */
#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
const char **reg_dummy;
register_info_type *reg_info_dummy;
#endif
#ifdef DEBUG
/* Counts the total number of registers pushed. */
unsigned num_regs_pushed = 0;
#endif
DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
INIT_FAIL_STACK ();
#ifdef MATCH_MAY_ALLOCATE
/* Do not bother to initialize all the register variables if there are
no groups in the pattern, as it takes a fair amount of time. If
there are groups, we include space for register 0 (the whole
pattern), even though we never use it, since it simplifies the
array indexing. We should fix this. */
if (bufp->re_nsub)
{
regstart = REGEX_TALLOC (num_regs, const char *);
regend = REGEX_TALLOC (num_regs, const char *);
old_regstart = REGEX_TALLOC (num_regs, const char *);
old_regend = REGEX_TALLOC (num_regs, const char *);
best_regstart = REGEX_TALLOC (num_regs, const char *);
best_regend = REGEX_TALLOC (num_regs, const char *);
reg_info = REGEX_TALLOC (num_regs, register_info_type);
reg_dummy = REGEX_TALLOC (num_regs, const char *);
reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
if (!(regstart && regend && old_regstart && old_regend && reg_info
&& best_regstart && best_regend && reg_dummy && reg_info_dummy))
{
FREE_VARIABLES ();
return -2;
}
}
else
{
/* We must initialize all our variables to NULL, so that
`FREE_VARIABLES' doesn't try to free them. */
regstart = regend = old_regstart = old_regend = best_regstart
= best_regend = reg_dummy = NULL;
reg_info = reg_info_dummy = (register_info_type *) NULL;
}
#endif /* MATCH_MAY_ALLOCATE */
/* The starting position is bogus. */
if (pos < 0 || pos > size1 + size2)
{
FREE_VARIABLES ();
return -1;
}
/* Initialize subexpression text positions to -1 to mark ones that no
start_memory/stop_memory has been seen for. Also initialize the
register information struct. */
for (mcnt = 1; mcnt < num_regs; mcnt++)
{
regstart[mcnt] = regend[mcnt]
= old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
IS_ACTIVE (reg_info[mcnt]) = 0;
MATCHED_SOMETHING (reg_info[mcnt]) = 0;
EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
}
/* We move `string1' into `string2' if the latter's empty -- but not if
`string1' is null. */
if (size2 == 0 && string1 != NULL)
{
string2 = string1;
size2 = size1;
string1 = 0;
size1 = 0;
}
end1 = string1 + size1;
end2 = string2 + size2;
/* Compute where to stop matching, within the two strings. */
if (stop <= size1)
{
end_match_1 = string1 + stop;
end_match_2 = string2;
}
else
{
end_match_1 = end1;
end_match_2 = string2 + stop - size1;
}
/* `p' scans through the pattern as `d' scans through the data.
`dend' is the end of the input string that `d' points within. `d'
is advanced into the following input string whenever necessary, but
this happens before fetching; therefore, at the beginning of the
loop, `d' can be pointing at the end of a string, but it cannot
equal `string2'. */
if (size1 > 0 && pos <= size1)
{
d = string1 + pos;
dend = end_match_1;
}
else
{
d = string2 + pos - size1;
dend = end_match_2;
}
DEBUG_PRINT1 ("The compiled pattern is: ");
DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
DEBUG_PRINT1 ("The string to match is: `");
DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
DEBUG_PRINT1 ("'\n");
/* This loops over pattern commands. It exits by returning from the
function if the match is complete, or it drops through if the match
fails at this starting point in the input data. */
for (;;)
{
DEBUG_PRINT2 ("\n0x%x: ", p);
if (p == pend)
{ /* End of pattern means we might have succeeded. */
DEBUG_PRINT1 ("end of pattern ... ");
/* If we haven't matched the entire string, and we want the
longest match, try backtracking. */
if (d != end_match_2)
{
/* 1 if this match ends in the same string (string1 or string2)
as the best previous match. */
boolean same_str_p = (FIRST_STRING_P (match_end)
== MATCHING_IN_FIRST_STRING);
/* 1 if this match is the best seen so far. */
boolean best_match_p;
/* AIX compiler got confused when this was combined
with the previous declaration. */
if (same_str_p)
best_match_p = d > match_end;
else
best_match_p = !MATCHING_IN_FIRST_STRING;
DEBUG_PRINT1 ("backtracking.\n");
if (!FAIL_STACK_EMPTY ())
{ /* More failure points to try. */
/* If exceeds best match so far, save it. */
if (!best_regs_set || best_match_p)
{
best_regs_set = true;
match_end = d;
DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
for (mcnt = 1; mcnt < num_regs; mcnt++)
{
best_regstart[mcnt] = regstart[mcnt];
best_regend[mcnt] = regend[mcnt];
}
}
goto fail;
}
/* If no failure points, don't restore garbage. And if
last match is real best match, don't restore second
best one. */
else if (best_regs_set && !best_match_p)
{
restore_best_regs:
/* Restore best match. It may happen that `dend ==
end_match_1' while the restored d is in string2.
For example, the pattern `x.*y.*z' against the
strings `x-' and `y-z-', if the two strings are
not consecutive in memory. */
DEBUG_PRINT1 ("Restoring best registers.\n");
d = match_end;
dend = ((d >= string1 && d <= end1)
? end_match_1 : end_match_2);
for (mcnt = 1; mcnt < num_regs; mcnt++)
{
regstart[mcnt] = best_regstart[mcnt];
regend[mcnt] = best_regend[mcnt];
}
}
} /* d != end_match_2 */
succeed_label:
DEBUG_PRINT1 ("Accepting match.\n");
/* If caller wants register contents data back, do it. */
if (regs && !bufp->no_sub)
{
/* Have the register data arrays been allocated? */
if (bufp->regs_allocated == REGS_UNALLOCATED)
{ /* No. So allocate them with malloc. We need one
extra element beyond `num_regs' for the `-1' marker
GNU code uses. */
regs->num_regs = MAX (RE_NREGS, num_regs + 1);
regs->start = TALLOC (regs->num_regs, regoff_t);
regs->end = TALLOC (regs->num_regs, regoff_t);
if (regs->start == NULL || regs->end == NULL)
{
FREE_VARIABLES ();
return -2;
}
bufp->regs_allocated = REGS_REALLOCATE;
}
else if (bufp->regs_allocated == REGS_REALLOCATE)
{ /* Yes. If we need more elements than were already
allocated, reallocate them. If we need fewer, just
leave it alone. */
if (regs->num_regs < num_regs + 1)
{
regs->num_regs = num_regs + 1;
RETALLOC (regs->start, regs->num_regs, regoff_t);
RETALLOC (regs->end, regs->num_regs, regoff_t);
if (regs->start == NULL || regs->end == NULL)
{
FREE_VARIABLES ();
return -2;
}
}
}
else
{
/* These braces fend off a "empty body in an else-statement"
warning under GCC when assert expands to nothing. */
assert (bufp->regs_allocated == REGS_FIXED);
}
/* Convert the pointer data in `regstart' and `regend' to
indices. Register zero has to be set differently,
since we haven't kept track of any info for it. */
if (regs->num_regs > 0)
{
regs->start[0] = pos;
regs->end[0] = (MATCHING_IN_FIRST_STRING
? ((regoff_t) (d - string1))
: ((regoff_t) (d - string2 + size1)));
}
/* Go through the first `min (num_regs, regs->num_regs)'
registers, since that is all we initialized. */
for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
{
if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
regs->start[mcnt] = regs->end[mcnt] = -1;
else
{
regs->start[mcnt]
= (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
regs->end[mcnt]
= (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
}
}
/* If the regs structure we return has more elements than
were in the pattern, set the extra elements to -1. If
we (re)allocated the registers, this is the case,
because we always allocate enough to have at least one
-1 at the end. */
for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
regs->start[mcnt] = regs->end[mcnt] = -1;
} /* regs && !bufp->no_sub */
DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
nfailure_points_pushed, nfailure_points_popped,
nfailure_points_pushed - nfailure_points_popped);
DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
mcnt = d - pos - (MATCHING_IN_FIRST_STRING
? string1
: string2 - size1);
DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
FREE_VARIABLES ();
return mcnt;
}
/* Otherwise match next pattern command. */
switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
{
/* Ignore these. Used to ignore the n of succeed_n's which
currently have n == 0. */
case no_op:
DEBUG_PRINT1 ("EXECUTING no_op.\n");
break;
case succeed:
DEBUG_PRINT1 ("EXECUTING succeed.\n");
goto succeed_label;
/* Match the next n pattern characters exactly. The following
byte in the pattern defines n, and the n bytes after that
are the characters to match. */
case exactn:
mcnt = *p++;
DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
/* This is written out as an if-else so we don't waste time
testing `translate' inside the loop. */
if (translate)
{
do
{
PREFETCH ();
if ((unsigned char) translate[(unsigned char) *d++]
!= (unsigned char) *p++)
goto fail;
}
while (--mcnt);
}
else
{
do
{
PREFETCH ();
if (*d++ != (char) *p++) goto fail;
}
while (--mcnt);
}
SET_REGS_MATCHED ();
break;
/* Match any character except possibly a newline or a null. */
case anychar:
DEBUG_PRINT1 ("EXECUTING anychar.\n");
PREFETCH ();
if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
|| (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
goto fail;
SET_REGS_MATCHED ();
DEBUG_PRINT2 (" Matched `%d'.\n", *d);
d++;
break;
case charset:
case charset_not:
{
register unsigned char c;
boolean not = (re_opcode_t) *(p - 1) == charset_not;
DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
PREFETCH ();
c = TRANSLATE (*d); /* The character to match. */
/* Cast to `unsigned' instead of `unsigned char' in case the
bit list is a full 32 bytes long. */
if (c < (unsigned) (*p * BYTEWIDTH)
&& p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
not = !not;
p += 1 + *p;
if (!not) goto fail;
SET_REGS_MATCHED ();
d++;
break;
}
/* The beginning of a group is represented by start_memory.
The arguments are the register number in the next byte, and the
number of groups inner to this one in the next. The text
matched within the group is recorded (in the internal
registers data structure) under the register number. */
case start_memory:
DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
/* Find out if this group can match the empty string. */
p1 = p; /* To send to group_match_null_string_p. */
if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
REG_MATCH_NULL_STRING_P (reg_info[*p])
= group_match_null_string_p (&p1, pend, reg_info);
/* Save the position in the string where we were the last time
we were at this open-group operator in case the group is
operated upon by a repetition operator, e.g., with `(a*)*b'
against `ab'; then we want to ignore where we are now in
the string in case this attempt to match fails. */
old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
? REG_UNSET (regstart[*p]) ? d : regstart[*p]
: regstart[*p];
DEBUG_PRINT2 (" old_regstart: %d\n",
POINTER_TO_OFFSET (old_regstart[*p]));
regstart[*p] = d;
DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
IS_ACTIVE (reg_info[*p]) = 1;
MATCHED_SOMETHING (reg_info[*p]) = 0;
/* Clear this whenever we change the register activity status. */
set_regs_matched_done = 0;
/* This is the new highest active register. */
highest_active_reg = *p;
/* If nothing was active before, this is the new lowest active
register. */
if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
lowest_active_reg = *p;
/* Move past the register number and inner group count. */
p += 2;
just_past_start_mem = p;
break;
/* The stop_memory opcode represents the end of a group. Its
arguments are the same as start_memory's: the register
number, and the number of inner groups. */
case stop_memory:
DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
/* We need to save the string position the last time we were at
this close-group operator in case the group is operated
upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
against `aba'; then we want to ignore where we are now in
the string in case this attempt to match fails. */
old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
? REG_UNSET (regend[*p]) ? d : regend[*p]
: regend[*p];
DEBUG_PRINT2 (" old_regend: %d\n",
POINTER_TO_OFFSET (old_regend[*p]));
regend[*p] = d;
DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
/* This register isn't active anymore. */
IS_ACTIVE (reg_info[*p]) = 0;
/* Clear this whenever we change the register activity status. */
set_regs_matched_done = 0;
/* If this was the only register active, nothing is active
anymore. */
if (lowest_active_reg == highest_active_reg)
{
lowest_active_reg = NO_LOWEST_ACTIVE_REG;
highest_active_reg = NO_HIGHEST_ACTIVE_REG;
}
else
{ /* We must scan for the new highest active register, since
it isn't necessarily one less than now: consider
(a(b)c(d(e)f)g). When group 3 ends, after the f), the
new highest active register is 1. */
unsigned char r = *p - 1;
while (r > 0 && !IS_ACTIVE (reg_info[r]))
r--;
/* If we end up at register zero, that means that we saved
the registers as the result of an `on_failure_jump', not
a `start_memory', and we jumped to past the innermost
`stop_memory'. For example, in ((.)*) we save
registers 1 and 2 as a result of the *, but when we pop
back to the second ), we are at the stop_memory 1.
Thus, nothing is active. */
if (r == 0)
{
lowest_active_reg = NO_LOWEST_ACTIVE_REG;
highest_active_reg = NO_HIGHEST_ACTIVE_REG;
}
else
highest_active_reg = r;
}
/* If just failed to match something this time around with a
group that's operated on by a repetition operator, try to
force exit from the ``loop'', and restore the register
information for this group that we had before trying this
last match. */
if ((!MATCHED_SOMETHING (reg_info[*p])
|| just_past_start_mem == p - 1)
&& (p + 2) < pend)
{
boolean is_a_jump_n = false;
p1 = p + 2;
mcnt = 0;
switch ((re_opcode_t) *p1++)
{
case jump_n:
is_a_jump_n = true;
case pop_failure_jump:
case maybe_pop_jump:
case jump:
case dummy_failure_jump:
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
if (is_a_jump_n)
p1 += 2;
break;
default:
/* do nothing */ ;
}
p1 += mcnt;
/* If the next operation is a jump backwards in the pattern
to an on_failure_jump right before the start_memory
corresponding to this stop_memory, exit from the loop
by forcing a failure after pushing on the stack the
on_failure_jump's jump in the pattern, and d. */
if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
&& (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
{
/* If this group ever matched anything, then restore
what its registers were before trying this last
failed match, e.g., with `(a*)*b' against `ab' for
regstart[1], and, e.g., with `((a*)*(b*)*)*'
against `aba' for regend[3].
Also restore the registers for inner groups for,
e.g., `((a*)(b*))*' against `aba' (register 3 would
otherwise get trashed). */
if (EVER_MATCHED_SOMETHING (reg_info[*p]))
{
unsigned r;
EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
/* Restore this and inner groups' (if any) registers. */
for (r = *p; r < *p + *(p + 1); r++)
{
regstart[r] = old_regstart[r];
/* xx why this test? */
if (old_regend[r] >= regstart[r])
regend[r] = old_regend[r];
}
}
p1++;
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
goto fail;
}
}
/* Move past the register number and the inner group count. */
p += 2;
break;
/* \ has been turned into a `duplicate' command which is
followed by the numeric value of as the register number. */
case duplicate:
{
register const char *d2, *dend2;
int regno = *p++; /* Get which register to match against. */
DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
/* Can't back reference a group which we've never matched. */
if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
goto fail;
/* Where in input to try to start matching. */
d2 = regstart[regno];
/* Where to stop matching; if both the place to start and
the place to stop matching are in the same string, then
set to the place to stop, otherwise, for now have to use
the end of the first string. */
dend2 = ((FIRST_STRING_P (regstart[regno])
== FIRST_STRING_P (regend[regno]))
? regend[regno] : end_match_1);
for (;;)
{
/* If necessary, advance to next segment in register
contents. */
while (d2 == dend2)
{
if (dend2 == end_match_2) break;
if (dend2 == regend[regno]) break;
/* End of string1 => advance to string2. */
d2 = string2;
dend2 = regend[regno];
}
/* At end of register contents => success */
if (d2 == dend2) break;
/* If necessary, advance to next segment in data. */
PREFETCH ();
/* How many characters left in this segment to match. */
mcnt = dend - d;
/* Want how many consecutive characters we can match in
one shot, so, if necessary, adjust the count. */
if (mcnt > dend2 - d2)
mcnt = dend2 - d2;
/* Compare that many; failure if mismatch, else move
past them. */
if (translate
? bcmp_translate (d, d2, mcnt, translate)
: bcmp (d, d2, mcnt))
goto fail;
d += mcnt, d2 += mcnt;
/* Do this because we've match some characters. */
SET_REGS_MATCHED ();
}
}
break;
/* begline matches the empty string at the beginning of the string
(unless `not_bol' is set in `bufp'), and, if
`newline_anchor' is set, after newlines. */
case begline:
DEBUG_PRINT1 ("EXECUTING begline.\n");
if (AT_STRINGS_BEG (d))
{
if (!bufp->not_bol) break;
}
else if (d[-1] == '\n' && bufp->newline_anchor)
{
break;
}
/* In all other cases, we fail. */
goto fail;
/* endline is the dual of begline. */
case endline:
DEBUG_PRINT1 ("EXECUTING endline.\n");
if (AT_STRINGS_END (d))
{
if (!bufp->not_eol) break;
}
/* We have to ``prefetch'' the next character. */
else if ((d == end1 ? *string2 : *d) == '\n'
&& bufp->newline_anchor)
{
break;
}
goto fail;
/* Match at the very beginning of the data. */
case begbuf:
DEBUG_PRINT1 ("EXECUTING begbuf.\n");
if (AT_STRINGS_BEG (d))
break;
goto fail;
/* Match at the very end of the data. */
case endbuf:
DEBUG_PRINT1 ("EXECUTING endbuf.\n");
if (AT_STRINGS_END (d))
break;
goto fail;
/* on_failure_keep_string_jump is used to optimize `.*\n'. It
pushes NULL as the value for the string on the stack. Then
`pop_failure_point' will keep the current value for the
string, instead of restoring it. To see why, consider
matching `foo\nbar' against `.*\n'. The .* matches the foo;
then the . fails against the \n. But the next thing we want
to do is match the \n against the \n; if we restored the
string value, we would be back at the foo.
Because this is used only in specific cases, we don't need to
check all the things that `on_failure_jump' does, to make
sure the right things get saved on the stack. Hence we don't
share its code. The only reason to push anything on the
stack at all is that otherwise we would have to change
`anychar's code to do something besides goto fail in this
case; that seems worse than this. */
case on_failure_keep_string_jump:
DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
EXTRACT_NUMBER_AND_INCR (mcnt, p);
DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
break;
/* Uses of on_failure_jump:
Each alternative starts with an on_failure_jump that points
to the beginning of the next alternative. Each alternative
except the last ends with a jump that in effect jumps past
the rest of the alternatives. (They really jump to the
ending jump of the following alternative, because tensioning
these jumps is a hassle.)
Repeats start with an on_failure_jump that points past both
the repetition text and either the following jump or
pop_failure_jump back to this on_failure_jump. */
case on_failure_jump:
on_failure:
DEBUG_PRINT1 ("EXECUTING on_failure_jump");
EXTRACT_NUMBER_AND_INCR (mcnt, p);
DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
/* If this on_failure_jump comes right before a group (i.e.,
the original * applied to a group), save the information
for that group and all inner ones, so that if we fail back
to this point, the group's information will be correct.
For example, in \(a*\)*\1, we need the preceding group,
and in \(zz\(a*\)b*\)\2, we need the inner group. */
/* We can't use `p' to check ahead because we push
a failure point to `p + mcnt' after we do this. */
p1 = p;
/* We need to skip no_op's before we look for the
start_memory in case this on_failure_jump is happening as
the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
against aba. */
while (p1 < pend && (re_opcode_t) *p1 == no_op)
p1++;
if (p1 < pend && (re_opcode_t) *p1 == start_memory)
{
/* We have a new highest active register now. This will
get reset at the start_memory we are about to get to,
but we will have saved all the registers relevant to
this repetition op, as described above. */
highest_active_reg = *(p1 + 1) + *(p1 + 2);
if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
lowest_active_reg = *(p1 + 1);
}
DEBUG_PRINT1 (":\n");
PUSH_FAILURE_POINT (p + mcnt, d, -2);
break;
/* A smart repeat ends with `maybe_pop_jump'.
We change it to either `pop_failure_jump' or `jump'. */
case maybe_pop_jump:
EXTRACT_NUMBER_AND_INCR (mcnt, p);
DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
{
register unsigned char *p2 = p;
/* Compare the beginning of the repeat with what in the
pattern follows its end. If we can establish that there
is nothing that they would both match, i.e., that we
would have to backtrack because of (as in, e.g., `a*a')
then we can change to pop_failure_jump, because we'll
never have to backtrack.
This is not true in the case of alternatives: in
`(a|ab)*' we do need to backtrack to the `ab' alternative
(e.g., if the string was `ab'). But instead of trying to
detect that here, the alternative has put on a dummy
failure point which is what we will end up popping. */
/* Skip over open/close-group commands.
If what follows this loop is a ...+ construct,
look at what begins its body, since we will have to
match at least one of that. */
while (1)
{
if (p2 + 2 < pend
&& ((re_opcode_t) *p2 == stop_memory
|| (re_opcode_t) *p2 == start_memory))
p2 += 3;
else if (p2 + 6 < pend
&& (re_opcode_t) *p2 == dummy_failure_jump)
p2 += 6;
else
break;
}
p1 = p + mcnt;
/* p1[0] ... p1[2] are the `on_failure_jump' corresponding
to the `maybe_finalize_jump' of this case. Examine what
follows. */
/* If we're at the end of the pattern, we can change. */
if (p2 == pend)
{
/* Consider what happens when matching ":\(.*\)"
against ":/". I don't really understand this code
yet. */
p[-3] = (unsigned char) pop_failure_jump;
DEBUG_PRINT1
(" End of pattern: change to `pop_failure_jump'.\n");
}
else if ((re_opcode_t) *p2 == exactn
|| (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
{
register unsigned char c
= *p2 == (unsigned char) endline ? '\n' : p2[2];
if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
{
p[-3] = (unsigned char) pop_failure_jump;
DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
c, p1[5]);
}
else if ((re_opcode_t) p1[3] == charset
|| (re_opcode_t) p1[3] == charset_not)
{
int not = (re_opcode_t) p1[3] == charset_not;
if (c < (unsigned char) (p1[4] * BYTEWIDTH)
&& p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
not = !not;
/* `not' is equal to 1 if c would match, which means
that we can't change to pop_failure_jump. */
if (!not)
{
p[-3] = (unsigned char) pop_failure_jump;
DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
}
}
}
else if ((re_opcode_t) *p2 == charset)
{
#ifdef DEBUG
register unsigned char c
= *p2 == (unsigned char) endline ? '\n' : p2[2];
#endif
if ((re_opcode_t) p1[3] == exactn
&& ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
&& (p2[2 + p1[5] / BYTEWIDTH]
& (1 << (p1[5] % BYTEWIDTH)))))
{
p[-3] = (unsigned char) pop_failure_jump;
DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
c, p1[5]);
}
else if ((re_opcode_t) p1[3] == charset_not)
{
int idx;
/* We win if the charset_not inside the loop
lists every character listed in the charset after. */
for (idx = 0; idx < (int) p2[1]; idx++)
if (! (p2[2 + idx] == 0
|| (idx < (int) p1[4]
&& ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
break;
if (idx == p2[1])
{
p[-3] = (unsigned char) pop_failure_jump;
DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
}
}
else if ((re_opcode_t) p1[3] == charset)
{
int idx;
/* We win if the charset inside the loop
has no overlap with the one after the loop. */
for (idx = 0;
idx < (int) p2[1] && idx < (int) p1[4];
idx++)
if ((p2[2 + idx] & p1[5 + idx]) != 0)
break;
if (idx == p2[1] || idx == p1[4])
{
p[-3] = (unsigned char) pop_failure_jump;
DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
}
}
}
}
p -= 2; /* Point at relative address again. */
if ((re_opcode_t) p[-1] != pop_failure_jump)
{
p[-1] = (unsigned char) jump;
DEBUG_PRINT1 (" Match => jump.\n");
goto unconditional_jump;
}
/* Note fall through. */
/* The end of a simple repeat has a pop_failure_jump back to
its matching on_failure_jump, where the latter will push a
failure point. The pop_failure_jump takes off failure
points put on by this pop_failure_jump's matching
on_failure_jump; we got through the pattern to here from the
matching on_failure_jump, so didn't fail. */
case pop_failure_jump:
{
/* We need to pass separate storage for the lowest and
highest registers, even though we don't care about the
actual values. Otherwise, we will restore only one
register from the stack, since lowest will == highest in
`pop_failure_point'. */
unsigned dummy_low_reg, dummy_high_reg;
unsigned char *pdummy;
const char *sdummy;
DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
POP_FAILURE_POINT (sdummy, pdummy,
dummy_low_reg, dummy_high_reg,
reg_dummy, reg_dummy, reg_info_dummy);
}
/* Note fall through. */
/* Unconditionally jump (without popping any failure points). */
case jump:
unconditional_jump:
EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
p += mcnt; /* Do the jump. */
DEBUG_PRINT2 ("(to 0x%x).\n", p);
break;
/* We need this opcode so we can detect where alternatives end
in `group_match_null_string_p' et al. */
case jump_past_alt:
DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
goto unconditional_jump;
/* Normally, the on_failure_jump pushes a failure point, which
then gets popped at pop_failure_jump. We will end up at
pop_failure_jump, also, and with a pattern of, say, `a+', we
are skipping over the on_failure_jump, so we have to push
something meaningless for pop_failure_jump to pop. */
case dummy_failure_jump:
DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
/* It doesn't matter what we push for the string here. What
the code at `fail' tests is the value for the pattern. */
PUSH_FAILURE_POINT (0, 0, -2);
goto unconditional_jump;
/* At the end of an alternative, we need to push a dummy failure
point in case we are followed by a `pop_failure_jump', because
we don't want the failure point for the alternative to be
popped. For example, matching `(a|ab)*' against `aab'
requires that we match the `ab' alternative. */
case push_dummy_failure:
DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
/* See comments just above at `dummy_failure_jump' about the
two zeroes. */
PUSH_FAILURE_POINT (0, 0, -2);
break;
/* Have to succeed matching what follows at least n times.
After that, handle like `on_failure_jump'. */
case succeed_n:
EXTRACT_NUMBER (mcnt, p + 2);
DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
assert (mcnt >= 0);
/* Originally, this is how many times we HAVE to succeed. */
if (mcnt > 0)
{
mcnt--;
p += 2;
STORE_NUMBER_AND_INCR (p, mcnt);
DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt);
}
else if (mcnt == 0)
{
DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
p[2] = (unsigned char) no_op;
p[3] = (unsigned char) no_op;
goto on_failure;
}
break;
case jump_n:
EXTRACT_NUMBER (mcnt, p + 2);
DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
/* Originally, this is how many times we CAN jump. */
if (mcnt)
{
mcnt--;
STORE_NUMBER (p + 2, mcnt);
goto unconditional_jump;
}
/* If don't have to jump any more, skip over the rest of command. */
else
p += 4;
break;
case set_number_at:
{
DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
EXTRACT_NUMBER_AND_INCR (mcnt, p);
p1 = p + mcnt;
EXTRACT_NUMBER_AND_INCR (mcnt, p);
DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
STORE_NUMBER (p1, mcnt);
break;
}
#if 0
/* The DEC Alpha C compiler 3.x generates incorrect code for the
test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
AT_WORD_BOUNDARY, so this code is disabled. Expanding the
macro and introducing temporary variables works around the bug. */
case wordbound:
DEBUG_PRINT1 ("EXECUTING wordbound.\n");
if (AT_WORD_BOUNDARY (d))
break;
goto fail;
case notwordbound:
DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
if (AT_WORD_BOUNDARY (d))
goto fail;
break;
#else
case wordbound:
{
boolean prevchar, thischar;
DEBUG_PRINT1 ("EXECUTING wordbound.\n");
if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
break;
prevchar = WORDCHAR_P (d - 1);
thischar = WORDCHAR_P (d);
if (prevchar != thischar)
break;
goto fail;
}
case notwordbound:
{
boolean prevchar, thischar;
DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
goto fail;
prevchar = WORDCHAR_P (d - 1);
thischar = WORDCHAR_P (d);
if (prevchar != thischar)
goto fail;
break;
}
#endif
case wordbeg:
DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
break;
goto fail;
case wordend:
DEBUG_PRINT1 ("EXECUTING wordend.\n");
if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
&& (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
break;
goto fail;
#ifdef emacs
case before_dot:
DEBUG_PRINT1 ("EXECUTING before_dot.\n");
if (PTR_CHAR_POS ((unsigned char *) d) >= PT)
goto fail;
break;
case at_dot:
DEBUG_PRINT1 ("EXECUTING at_dot.\n");
if (PTR_CHAR_POS ((unsigned char *) d) != PT)
goto fail;
break;
case after_dot:
DEBUG_PRINT1 ("EXECUTING after_dot.\n");
if (PTR_CHAR_POS ((unsigned char *) d) <= PT)
goto fail;
break;
case syntaxspec:
DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
mcnt = *p++;
goto matchsyntax;
case wordchar:
DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
mcnt = (int) Sword;
matchsyntax:
PREFETCH ();
/* Can't use *d++ here; SYNTAX may be an unsafe macro. */
d++;
if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
goto fail;
SET_REGS_MATCHED ();
break;
case notsyntaxspec:
DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
mcnt = *p++;
goto matchnotsyntax;
case notwordchar:
DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
mcnt = (int) Sword;
matchnotsyntax:
PREFETCH ();
/* Can't use *d++ here; SYNTAX may be an unsafe macro. */
d++;
if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
goto fail;
SET_REGS_MATCHED ();
break;
#else /* not emacs */
case wordchar:
DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
PREFETCH ();
if (!WORDCHAR_P (d))
goto fail;
SET_REGS_MATCHED ();
d++;
break;
case notwordchar:
DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
PREFETCH ();
if (WORDCHAR_P (d))
goto fail;
SET_REGS_MATCHED ();
d++;
break;
#endif /* not emacs */
default:
abort ();
}
continue; /* Successfully executed one pattern command; keep going. */
/* We goto here if a matching operation fails. */
fail:
if (!FAIL_STACK_EMPTY ())
{ /* A restart point is known. Restore to that state. */
DEBUG_PRINT1 ("\nFAIL:\n");
POP_FAILURE_POINT (d, p,
lowest_active_reg, highest_active_reg,
regstart, regend, reg_info);
/* If this failure point is a dummy, try the next one. */
if (!p)
goto fail;
/* If we failed to the end of the pattern, don't examine *p. */
assert (p <= pend);
if (p < pend)
{
boolean is_a_jump_n = false;
/* If failed to a backwards jump that's part of a repetition
loop, need to pop this failure point and use the next one. */
switch ((re_opcode_t) *p)
{
case jump_n:
is_a_jump_n = true;
case maybe_pop_jump:
case pop_failure_jump:
case jump:
p1 = p + 1;
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
p1 += mcnt;
if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
|| (!is_a_jump_n
&& (re_opcode_t) *p1 == on_failure_jump))
goto fail;
break;
default:
/* do nothing */ ;
}
}
if (d >= string1 && d <= end1)
dend = end_match_1;
}
else
break; /* Matching at this starting point really fails. */
} /* for (;;) */
if (best_regs_set)
goto restore_best_regs;
FREE_VARIABLES ();
return -1; /* Failure to match. */
} /* re_match_2 */
/* Subroutine definitions for re_match_2. */
/* We are passed P pointing to a register number after a start_memory.
Return true if the pattern up to the corresponding stop_memory can
match the empty string, and false otherwise.
If we find the matching stop_memory, sets P to point to one past its number.
Otherwise, sets P to an undefined byte less than or equal to END.
We don't handle duplicates properly (yet). */
static boolean
group_match_null_string_p (p, end, reg_info)
unsigned char **p, *end;
register_info_type *reg_info;
{
int mcnt;
/* Point to after the args to the start_memory. */
unsigned char *p1 = *p + 2;
while (p1 < end)
{
/* Skip over opcodes that can match nothing, and return true or
false, as appropriate, when we get to one that can't, or to the
matching stop_memory. */
switch ((re_opcode_t) *p1)
{
/* Could be either a loop or a series of alternatives. */
case on_failure_jump:
p1++;
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
/* If the next operation is not a jump backwards in the
pattern. */
if (mcnt >= 0)
{
/* Go through the on_failure_jumps of the alternatives,
seeing if any of the alternatives cannot match nothing.
The last alternative starts with only a jump,
whereas the rest start with on_failure_jump and end
with a jump, e.g., here is the pattern for `a|b|c':
/on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
/on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
/exactn/1/c
So, we have to first go through the first (n-1)
alternatives and then deal with the last one separately. */
/* Deal with the first (n-1) alternatives, which start
with an on_failure_jump (see above) that jumps to right
past a jump_past_alt. */
while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
{
/* `mcnt' holds how many bytes long the alternative
is, including the ending `jump_past_alt' and
its number. */
if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
reg_info))
return false;
/* Move to right after this alternative, including the
jump_past_alt. */
p1 += mcnt;
/* Break if it's the beginning of an n-th alternative
that doesn't begin with an on_failure_jump. */
if ((re_opcode_t) *p1 != on_failure_jump)
break;
/* Still have to check that it's not an n-th
alternative that starts with an on_failure_jump. */
p1++;
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
{
/* Get to the beginning of the n-th alternative. */
p1 -= 3;
break;
}
}
/* Deal with the last alternative: go back and get number
of the `jump_past_alt' just before it. `mcnt' contains
the length of the alternative. */
EXTRACT_NUMBER (mcnt, p1 - 2);
if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
return false;
p1 += mcnt; /* Get past the n-th alternative. */
} /* if mcnt > 0 */
break;
case stop_memory:
assert (p1[1] == **p);
*p = p1 + 2;
return true;
default:
if (!common_op_match_null_string_p (&p1, end, reg_info))
return false;
}
} /* while p1 < end */
return false;
} /* group_match_null_string_p */
/* Similar to group_match_null_string_p, but doesn't deal with alternatives:
It expects P to be the first byte of a single alternative and END one
byte past the last. The alternative can contain groups. */
static boolean
alt_match_null_string_p (p, end, reg_info)
unsigned char *p, *end;
register_info_type *reg_info;
{
int mcnt;
unsigned char *p1 = p;
while (p1 < end)
{
/* Skip over opcodes that can match nothing, and break when we get
to one that can't. */
switch ((re_opcode_t) *p1)
{
/* It's a loop. */
case on_failure_jump:
p1++;
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
p1 += mcnt;
break;
default:
if (!common_op_match_null_string_p (&p1, end, reg_info))
return false;
}
} /* while p1 < end */
return true;
} /* alt_match_null_string_p */
/* Deals with the ops common to group_match_null_string_p and
alt_match_null_string_p.
Sets P to one after the op and its arguments, if any. */
static boolean
common_op_match_null_string_p (p, end, reg_info)
unsigned char **p, *end;
register_info_type *reg_info;
{
int mcnt;
boolean ret;
int reg_no;
unsigned char *p1 = *p;
switch ((re_opcode_t) *p1++)
{
case no_op:
case begline:
case endline:
case begbuf:
case endbuf:
case wordbeg:
case wordend:
case wordbound:
case notwordbound:
#ifdef emacs
case before_dot:
case at_dot:
case after_dot:
#endif
break;
case start_memory:
reg_no = *p1;
assert (reg_no > 0 && reg_no <= MAX_REGNUM);
ret = group_match_null_string_p (&p1, end, reg_info);
/* Have to set this here in case we're checking a group which
contains a group and a back reference to it. */
if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
if (!ret)
return false;
break;
/* If this is an optimized succeed_n for zero times, make the jump. */
case jump:
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
if (mcnt >= 0)
p1 += mcnt;
else
return false;
break;
case succeed_n:
/* Get to the number of times to succeed. */
p1 += 2;
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
if (mcnt == 0)
{
p1 -= 4;
EXTRACT_NUMBER_AND_INCR (mcnt, p1);
p1 += mcnt;
}
else
return false;
break;
case duplicate:
if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
return false;
break;
case set_number_at:
p1 += 4;
default:
/* All other opcodes mean we cannot match the empty string. */
return false;
}
*p = p1;
return true;
} /* common_op_match_null_string_p */
/* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
bytes; nonzero otherwise. */
static int
bcmp_translate (s1, s2, len, translate)
unsigned char *s1, *s2;
register int len;
RE_TRANSLATE_TYPE translate;
{
register unsigned char *p1 = s1, *p2 = s2;
while (len)
{
if (translate[*p1++] != translate[*p2++]) return 1;
len--;
}
return 0;
}
/* Entry points for GNU code. */
/* re_compile_pattern is the GNU regular expression compiler: it
compiles PATTERN (of length SIZE) and puts the result in BUFP.
Returns 0 if the pattern was valid, otherwise an error string.
Assumes the `allocated' (and perhaps `buffer') and `translate' fields
are set in BUFP on entry.
We call regex_compile to do the actual compilation. */
const char *
re_compile_pattern (pattern, length, bufp)
const char *pattern;
int length;
struct re_pattern_buffer *bufp;
{
reg_errcode_t ret;
/* GNU code is written to assume at least RE_NREGS registers will be set
(and at least one extra will be -1). */
bufp->regs_allocated = REGS_UNALLOCATED;
/* And GNU code determines whether or not to get register information
by passing null for the REGS argument to re_match, etc., not by
setting no_sub. */
bufp->no_sub = 0;
/* Match anchors at newline. */
bufp->newline_anchor = 1;
ret = regex_compile (pattern, length, re_syntax_options, bufp);
if (!ret)
return NULL;
return gettext (re_error_msgid[(int) ret]);
}
/* Entry points compatible with 4.2 BSD regex library. We don't define
them unless specifically requested. */
#if defined (_REGEX_RE_COMP) || defined (_LIBC)
/* BSD has one and only one pattern buffer. */
static struct re_pattern_buffer re_comp_buf;
char *
#ifdef _LIBC
/* Make these definitions weak in libc, so POSIX programs can redefine
these names if they don't use our functions, and still use
regcomp/regexec below without link errors. */
weak_function
#endif
re_comp (s)
const char *s;
{
reg_errcode_t ret;
if (!s)
{
if (!re_comp_buf.buffer)
return gettext ("No previous regular expression");
return 0;
}
if (!re_comp_buf.buffer)
{
re_comp_buf.buffer = (unsigned char *) malloc (200);
if (re_comp_buf.buffer == NULL)
return gettext (re_error_msgid[(int) REG_ESPACE]);
re_comp_buf.allocated = 200;
re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
if (re_comp_buf.fastmap == NULL)
return gettext (re_error_msgid[(int) REG_ESPACE]);
}
/* Since `re_exec' always passes NULL for the `regs' argument, we
don't need to initialize the pattern buffer fields which affect it. */
/* Match anchors at newlines. */
re_comp_buf.newline_anchor = 1;
ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
if (!ret)
return NULL;
/* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
return (char *) gettext (re_error_msgid[(int) ret]);
}
int
#ifdef _LIBC
weak_function
#endif
re_exec (s)
const char *s;
{
const int len = strlen (s);
return
0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
}
#endif /* _REGEX_RE_COMP */
/* POSIX.2 functions. Don't define these for Emacs. */
#ifndef emacs
/* regcomp takes a regular expression as a string and compiles it.
PREG is a regex_t *. We do not expect any fields to be initialized,
since POSIX says we shouldn't. Thus, we set
`buffer' to the compiled pattern;
`used' to the length of the compiled pattern;
`syntax' to RE_SYNTAX_POSIX_EXTENDED if the
REG_EXTENDED bit in CFLAGS is set; otherwise, to
RE_SYNTAX_POSIX_BASIC;
`newline_anchor' to REG_NEWLINE being set in CFLAGS;
`fastmap' and `fastmap_accurate' to zero;
`re_nsub' to the number of subexpressions in PATTERN.
PATTERN is the address of the pattern string.
CFLAGS is a series of bits which affect compilation.
If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
use POSIX basic syntax.
If REG_NEWLINE is set, then . and [^...] don't match newline.
Also, regexec will try a match beginning after every newline.
If REG_ICASE is set, then we considers upper- and lowercase
versions of letters to be equivalent when matching.
If REG_NOSUB is set, then when PREG is passed to regexec, that
routine will report only success or failure, and nothing about the
registers.
It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
the return codes and their meanings.) */
int
regcomp (preg, pattern, cflags)
regex_t *preg;
const char *pattern;
int cflags;
{
reg_errcode_t ret;
unsigned syntax
= (cflags & REG_EXTENDED) ?
RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
/* regex_compile will allocate the space for the compiled pattern. */
preg->buffer = 0;
preg->allocated = 0;
preg->used = 0;
/* Don't bother to use a fastmap when searching. This simplifies the
REG_NEWLINE case: if we used a fastmap, we'd have to put all the
characters after newlines into the fastmap. This way, we just try
every character. */
preg->fastmap = 0;
if (cflags & REG_ICASE)
{
unsigned i;
preg->translate
= (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
* sizeof (*(RE_TRANSLATE_TYPE)0));
if (preg->translate == NULL)
return (int) REG_ESPACE;
/* Map uppercase characters to corresponding lowercase ones. */
for (i = 0; i < CHAR_SET_SIZE; i++)
preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
}
else
preg->translate = NULL;
/* If REG_NEWLINE is set, newlines are treated differently. */
if (cflags & REG_NEWLINE)
{ /* REG_NEWLINE implies neither . nor [^...] match newline. */
syntax &= ~RE_DOT_NEWLINE;
syntax |= RE_HAT_LISTS_NOT_NEWLINE;
/* It also changes the matching behavior. */
preg->newline_anchor = 1;
}
else
preg->newline_anchor = 0;
preg->no_sub = !!(cflags & REG_NOSUB);
/* POSIX says a null character in the pattern terminates it, so we
can use strlen here in compiling the pattern. */
ret = regex_compile (pattern, strlen (pattern), syntax, preg);
/* POSIX doesn't distinguish between an unmatched open-group and an
unmatched close-group: both are REG_EPAREN. */
if (ret == REG_ERPAREN) ret = REG_EPAREN;
return (int) ret;
}
/* regexec searches for a given pattern, specified by PREG, in the
string STRING.
If NMATCH is zero or REG_NOSUB was set in the cflags argument to
`regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
least NMATCH elements, and we set them to the offsets of the
corresponding matched substrings.
EFLAGS specifies `execution flags' which affect matching: if
REG_NOTBOL is set, then ^ does not match at the beginning of the
string; if REG_NOTEOL is set, then $ does not match at the end.
We return 0 if we find a match and REG_NOMATCH if not. */
int
regexec (preg, string, nmatch, pmatch, eflags)
const regex_t *preg;
const char *string;
size_t nmatch;
regmatch_t pmatch[];
int eflags;
{
int ret;
struct re_registers regs;
regex_t private_preg;
int len = strlen (string);
boolean want_reg_info = !preg->no_sub && nmatch > 0;
private_preg = *preg;
private_preg.not_bol = !!(eflags & REG_NOTBOL);
private_preg.not_eol = !!(eflags & REG_NOTEOL);
/* The user has told us exactly how many registers to return
information about, via `nmatch'. We have to pass that on to the
matching routines. */
private_preg.regs_allocated = REGS_FIXED;
if (want_reg_info)
{
regs.num_regs = nmatch;
regs.start = TALLOC (nmatch, regoff_t);
regs.end = TALLOC (nmatch, regoff_t);
if (regs.start == NULL || regs.end == NULL)
return (int) REG_NOMATCH;
}
/* Perform the searching operation. */
ret = re_search (&private_preg, string, len,
/* start: */ 0, /* range: */ len,
want_reg_info ? ®s : (struct re_registers *) 0);
/* Copy the register information to the POSIX structure. */
if (want_reg_info)
{
if (ret >= 0)
{
unsigned r;
for (r = 0; r < nmatch; r++)
{
pmatch[r].rm_so = regs.start[r];
pmatch[r].rm_eo = regs.end[r];
}
}
/* If we needed the temporary register info, free the space now. */
free (regs.start);
free (regs.end);
}
/* We want zero return to mean success, unlike `re_search'. */
return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
}
/* Returns a message corresponding to an error code, ERRCODE, returned
from either regcomp or regexec. We don't use PREG here. */
size_t
regerror (errcode, preg, errbuf, errbuf_size)
int errcode;
const regex_t *preg;
char *errbuf;
size_t errbuf_size;
{
const char *msg;
size_t msg_size;
if (errcode < 0
|| errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
/* Only error codes returned by the rest of the code should be passed
to this routine. If we are given anything else, or if other regex
code generates an invalid error code, then the program has a bug.
Dump core so we can fix it. */
abort ();
msg = gettext (re_error_msgid[errcode]);
msg_size = strlen (msg) + 1; /* Includes the null. */
if (errbuf_size != 0)
{
if (msg_size > errbuf_size)
{
strncpy (errbuf, msg, errbuf_size - 1);
errbuf[errbuf_size - 1] = 0;
}
else
strcpy (errbuf, msg);
}
return msg_size;
}
/* Free dynamically allocated space used by PREG. */
void
regfree (preg)
regex_t *preg;
{
if (preg->buffer != NULL)
free (preg->buffer);
preg->buffer = NULL;
preg->allocated = 0;
preg->used = 0;
if (preg->fastmap != NULL)
free (preg->fastmap);
preg->fastmap = NULL;
preg->fastmap_accurate = 0;
if (preg->translate != NULL)
free (preg->translate);
preg->translate = NULL;
}
#endif /* not emacs */
clearsilver-0.10.5/util/regex/regex.h 0000644 0012117 0011610 00000044732 10261037532 014407 0000000 0000000 /* Definitions for data structures and routines for the regular
expression library, version 0.12.
Copyright (C) 1985, 89, 90, 91, 92, 93, 95 Free Software Foundation, Inc.
This program 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 2, 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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
#ifndef __REGEXP_LIBRARY_H__
#define __REGEXP_LIBRARY_H__
/* POSIX says that must be included (by the caller) before
. */
#if !defined (_POSIX_C_SOURCE) && !defined (_POSIX_SOURCE) && defined (VMS)
/* VMS doesn't have `size_t' in , even though POSIX says it
should be there. */
#include
#endif
/* The following bits are used to determine the regexp syntax we
recognize. The set/not-set meanings are chosen so that Emacs syntax
remains the value 0. The bits are given in alphabetical order, and
the definitions shifted by one from the previous bit; thus, when we
add or remove a bit, only one other definition need change. */
typedef unsigned reg_syntax_t;
/* If this bit is not set, then \ inside a bracket expression is literal.
If set, then such a \ quotes the following character. */
#define RE_BACKSLASH_ESCAPE_IN_LISTS (1)
/* If this bit is not set, then + and ? are operators, and \+ and \? are
literals.
If set, then \+ and \? are operators and + and ? are literals. */
#define RE_BK_PLUS_QM (RE_BACKSLASH_ESCAPE_IN_LISTS << 1)
/* If this bit is set, then character classes are supported. They are:
[:alpha:], [:upper:], [:lower:], [:digit:], [:alnum:], [:xdigit:],
[:space:], [:print:], [:punct:], [:graph:], and [:cntrl:].
If not set, then character classes are not supported. */
#define RE_CHAR_CLASSES (RE_BK_PLUS_QM << 1)
/* If this bit is set, then ^ and $ are always anchors (outside bracket
expressions, of course).
If this bit is not set, then it depends:
^ is an anchor if it is at the beginning of a regular
expression or after an open-group or an alternation operator;
$ is an anchor if it is at the end of a regular expression, or
before a close-group or an alternation operator.
This bit could be (re)combined with RE_CONTEXT_INDEP_OPS, because
POSIX draft 11.2 says that * etc. in leading positions is undefined.
We already implemented a previous draft which made those constructs
invalid, though, so we haven't changed the code back. */
#define RE_CONTEXT_INDEP_ANCHORS (RE_CHAR_CLASSES << 1)
/* If this bit is set, then special characters are always special
regardless of where they are in the pattern.
If this bit is not set, then special characters are special only in
some contexts; otherwise they are ordinary. Specifically,
* + ? and intervals are only special when not after the beginning,
open-group, or alternation operator. */
#define RE_CONTEXT_INDEP_OPS (RE_CONTEXT_INDEP_ANCHORS << 1)
/* If this bit is set, then *, +, ?, and { cannot be first in an re or
immediately after an alternation or begin-group operator. */
#define RE_CONTEXT_INVALID_OPS (RE_CONTEXT_INDEP_OPS << 1)
/* If this bit is set, then . matches newline.
If not set, then it doesn't. */
#define RE_DOT_NEWLINE (RE_CONTEXT_INVALID_OPS << 1)
/* If this bit is set, then . doesn't match NUL.
If not set, then it does. */
#define RE_DOT_NOT_NULL (RE_DOT_NEWLINE << 1)
/* If this bit is set, nonmatching lists [^...] do not match newline.
If not set, they do. */
#define RE_HAT_LISTS_NOT_NEWLINE (RE_DOT_NOT_NULL << 1)
/* If this bit is set, either \{...\} or {...} defines an
interval, depending on RE_NO_BK_BRACES.
If not set, \{, \}, {, and } are literals. */
#define RE_INTERVALS (RE_HAT_LISTS_NOT_NEWLINE << 1)
/* If this bit is set, +, ? and | aren't recognized as operators.
If not set, they are. */
#define RE_LIMITED_OPS (RE_INTERVALS << 1)
/* If this bit is set, newline is an alternation operator.
If not set, newline is literal. */
#define RE_NEWLINE_ALT (RE_LIMITED_OPS << 1)
/* If this bit is set, then `{...}' defines an interval, and \{ and \}
are literals.
If not set, then `\{...\}' defines an interval. */
#define RE_NO_BK_BRACES (RE_NEWLINE_ALT << 1)
/* If this bit is set, (...) defines a group, and \( and \) are literals.
If not set, \(...\) defines a group, and ( and ) are literals. */
#define RE_NO_BK_PARENS (RE_NO_BK_BRACES << 1)
/* If this bit is set, then \ matches .
If not set, then \ is a back-reference. */
#define RE_NO_BK_REFS (RE_NO_BK_PARENS << 1)
/* If this bit is set, then | is an alternation operator, and \| is literal.
If not set, then \| is an alternation operator, and | is literal. */
#define RE_NO_BK_VBAR (RE_NO_BK_REFS << 1)
/* If this bit is set, then an ending range point collating higher
than the starting range point, as in [z-a], is invalid.
If not set, then when ending range point collates higher than the
starting range point, the range is ignored. */
#define RE_NO_EMPTY_RANGES (RE_NO_BK_VBAR << 1)
/* If this bit is set, then an unmatched ) is ordinary.
If not set, then an unmatched ) is invalid. */
#define RE_UNMATCHED_RIGHT_PAREN_ORD (RE_NO_EMPTY_RANGES << 1)
/* If this bit is set, succeed as soon as we match the whole pattern,
without further backtracking. */
#define RE_NO_POSIX_BACKTRACKING (RE_UNMATCHED_RIGHT_PAREN_ORD << 1)
/* This global variable defines the particular regexp syntax to use (for
some interfaces). When a regexp is compiled, the syntax used is
stored in the pattern buffer, so changing this does not affect
already-compiled regexps. */
extern reg_syntax_t re_syntax_options;
/* Define combinations of the above bits for the standard possibilities.
(The [[[ comments delimit what gets put into the Texinfo file, so
don't delete them!) */
/* [[[begin syntaxes]]] */
#define RE_SYNTAX_EMACS 0
#define RE_SYNTAX_AWK \
(RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DOT_NOT_NULL \
| RE_NO_BK_PARENS | RE_NO_BK_REFS \
| RE_NO_BK_VBAR | RE_NO_EMPTY_RANGES \
| RE_UNMATCHED_RIGHT_PAREN_ORD)
#define RE_SYNTAX_POSIX_AWK \
(RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS)
#define RE_SYNTAX_GREP \
(RE_BK_PLUS_QM | RE_CHAR_CLASSES \
| RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS \
| RE_NEWLINE_ALT)
#define RE_SYNTAX_EGREP \
(RE_CHAR_CLASSES | RE_CONTEXT_INDEP_ANCHORS \
| RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE \
| RE_NEWLINE_ALT | RE_NO_BK_PARENS \
| RE_NO_BK_VBAR)
#define RE_SYNTAX_POSIX_EGREP \
(RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES)
/* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */
#define RE_SYNTAX_ED RE_SYNTAX_POSIX_BASIC
#define RE_SYNTAX_SED RE_SYNTAX_POSIX_BASIC
/* Syntax bits common to both basic and extended POSIX regex syntax. */
#define _RE_SYNTAX_POSIX_COMMON \
(RE_CHAR_CLASSES | RE_DOT_NEWLINE | RE_DOT_NOT_NULL \
| RE_INTERVALS | RE_NO_EMPTY_RANGES)
#define RE_SYNTAX_POSIX_BASIC \
(_RE_SYNTAX_POSIX_COMMON | RE_BK_PLUS_QM)
/* Differs from ..._POSIX_BASIC only in that RE_BK_PLUS_QM becomes
RE_LIMITED_OPS, i.e., \? \+ \| are not recognized. Actually, this
isn't minimal, since other operators, such as \`, aren't disabled. */
#define RE_SYNTAX_POSIX_MINIMAL_BASIC \
(_RE_SYNTAX_POSIX_COMMON | RE_LIMITED_OPS)
#define RE_SYNTAX_POSIX_EXTENDED \
(_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \
| RE_CONTEXT_INDEP_OPS | RE_NO_BK_BRACES \
| RE_NO_BK_PARENS | RE_NO_BK_VBAR \
| RE_UNMATCHED_RIGHT_PAREN_ORD)
/* Differs from ..._POSIX_EXTENDED in that RE_CONTEXT_INVALID_OPS
replaces RE_CONTEXT_INDEP_OPS and RE_NO_BK_REFS is added. */
#define RE_SYNTAX_POSIX_MINIMAL_EXTENDED \
(_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \
| RE_CONTEXT_INVALID_OPS | RE_NO_BK_BRACES \
| RE_NO_BK_PARENS | RE_NO_BK_REFS \
| RE_NO_BK_VBAR | RE_UNMATCHED_RIGHT_PAREN_ORD)
/* [[[end syntaxes]]] */
/* Maximum number of duplicates an interval can allow. Some systems
(erroneously) define this in other header files, but we want our
value, so remove any previous define. */
#ifdef RE_DUP_MAX
#undef RE_DUP_MAX
#endif
#define RE_DUP_MAX ((1 << 15) - 1)
/* POSIX `cflags' bits (i.e., information for `regcomp'). */
/* If this bit is set, then use extended regular expression syntax.
If not set, then use basic regular expression syntax. */
#define REG_EXTENDED 1
/* If this bit is set, then ignore case when matching.
If not set, then case is significant. */
#define REG_ICASE (REG_EXTENDED << 1)
/* If this bit is set, then anchors do not match at newline
characters in the string.
If not set, then anchors do match at newlines. */
#define REG_NEWLINE (REG_ICASE << 1)
/* If this bit is set, then report only success or fail in regexec.
If not set, then returns differ between not matching and errors. */
#define REG_NOSUB (REG_NEWLINE << 1)
/* POSIX `eflags' bits (i.e., information for regexec). */
/* If this bit is set, then the beginning-of-line operator doesn't match
the beginning of the string (presumably because it's not the
beginning of a line).
If not set, then the beginning-of-line operator does match the
beginning of the string. */
#define REG_NOTBOL 1
/* Like REG_NOTBOL, except for the end-of-line. */
#define REG_NOTEOL (1 << 1)
/* If any error codes are removed, changed, or added, update the
`re_error_msg' table in regex.c. */
typedef enum
{
REG_NOERROR = 0, /* Success. */
REG_NOMATCH, /* Didn't find a match (for regexec). */
/* POSIX regcomp return error codes. (In the order listed in the
standard.) */
REG_BADPAT, /* Invalid pattern. */
REG_ECOLLATE, /* Not implemented. */
REG_ECTYPE, /* Invalid character class name. */
REG_EESCAPE, /* Trailing backslash. */
REG_ESUBREG, /* Invalid back reference. */
REG_EBRACK, /* Unmatched left bracket. */
REG_EPAREN, /* Parenthesis imbalance. */
REG_EBRACE, /* Unmatched \{. */
REG_BADBR, /* Invalid contents of \{\}. */
REG_ERANGE, /* Invalid range end. */
REG_ESPACE, /* Ran out of memory. */
REG_BADRPT, /* No preceding re for repetition op. */
/* Error codes we've added. */
REG_EEND, /* Premature end. */
REG_ESIZE, /* Compiled pattern bigger than 2^16 bytes. */
REG_ERPAREN /* Unmatched ) or \); not returned from regcomp. */
} reg_errcode_t;
/* This data structure represents a compiled pattern. Before calling
the pattern compiler, the fields `buffer', `allocated', `fastmap',
`translate', and `no_sub' can be set. After the pattern has been
compiled, the `re_nsub' field is available. All other fields are
private to the regex routines. */
#ifndef RE_TRANSLATE_TYPE
#define RE_TRANSLATE_TYPE char *
#endif
struct re_pattern_buffer
{
/* [[[begin pattern_buffer]]] */
/* Space that holds the compiled pattern. It is declared as
`unsigned char *' because its elements are
sometimes used as array indexes. */
unsigned char *buffer;
/* Number of bytes to which `buffer' points. */
unsigned long allocated;
/* Number of bytes actually used in `buffer'. */
unsigned long used;
/* Syntax setting with which the pattern was compiled. */
reg_syntax_t syntax;
/* Pointer to a fastmap, if any, otherwise zero. re_search uses
the fastmap, if there is one, to skip over impossible
starting points for matches. */
char *fastmap;
/* Either a translate table to apply to all characters before
comparing them, or zero for no translation. The translation
is applied to a pattern when it is compiled and to a string
when it is matched. */
RE_TRANSLATE_TYPE translate;
/* Number of subexpressions found by the compiler. */
size_t re_nsub;
/* Zero if this pattern cannot match the empty string, one else.
Well, in truth it's used only in `re_search_2', to see
whether or not we should use the fastmap, so we don't set
this absolutely perfectly; see `re_compile_fastmap' (the
`duplicate' case). */
unsigned can_be_null : 1;
/* If REGS_UNALLOCATED, allocate space in the `regs' structure
for `max (RE_NREGS, re_nsub + 1)' groups.
If REGS_REALLOCATE, reallocate space if necessary.
If REGS_FIXED, use what's there. */
#define REGS_UNALLOCATED 0
#define REGS_REALLOCATE 1
#define REGS_FIXED 2
unsigned regs_allocated : 2;
/* Set to zero when `regex_compile' compiles a pattern; set to one
by `re_compile_fastmap' if it updates the fastmap. */
unsigned fastmap_accurate : 1;
/* If set, `re_match_2' does not return information about
subexpressions. */
unsigned no_sub : 1;
/* If set, a beginning-of-line anchor doesn't match at the
beginning of the string. */
unsigned not_bol : 1;
/* Similarly for an end-of-line anchor. */
unsigned not_eol : 1;
/* If true, an anchor at a newline matches. */
unsigned newline_anchor : 1;
/* [[[end pattern_buffer]]] */
};
typedef struct re_pattern_buffer regex_t;
/* Type for byte offsets within the string. POSIX mandates this. */
typedef int regoff_t;
/* This is the structure we store register match data in. See
regex.texinfo for a full description of what registers match. */
struct re_registers
{
unsigned num_regs;
regoff_t *start;
regoff_t *end;
};
/* If `regs_allocated' is REGS_UNALLOCATED in the pattern buffer,
`re_match_2' returns information about at least this many registers
the first time a `regs' structure is passed. */
#ifndef RE_NREGS
#define RE_NREGS 30
#endif
/* POSIX specification for registers. Aside from the different names than
`re_registers', POSIX uses an array of structures, instead of a
structure of arrays. */
typedef struct
{
regoff_t rm_so; /* Byte offset from string's start to substring's start. */
regoff_t rm_eo; /* Byte offset from string's start to substring's end. */
} regmatch_t;
/* Declarations for routines. */
/* To avoid duplicating every routine declaration -- once with a
prototype (if we are ANSI), and once without (if we aren't) -- we
use the following macro to declare argument types. This
unfortunately clutters up the declarations a bit, but I think it's
worth it. */
#if __STDC__
#define _RE_ARGS(args) args
#else /* not __STDC__ */
#define _RE_ARGS(args) ()
#endif /* not __STDC__ */
/* Sets the current default syntax to SYNTAX, and return the old syntax.
You can also simply assign to the `re_syntax_options' variable. */
extern reg_syntax_t re_set_syntax _RE_ARGS ((reg_syntax_t syntax));
/* Compile the regular expression PATTERN, with length LENGTH
and syntax given by the global `re_syntax_options', into the buffer
BUFFER. Return NULL if successful, and an error string if not. */
extern const char *re_compile_pattern
_RE_ARGS ((const char *pattern, int length,
struct re_pattern_buffer *buffer));
/* Compile a fastmap for the compiled pattern in BUFFER; used to
accelerate searches. Return 0 if successful and -2 if was an
internal error. */
extern int re_compile_fastmap _RE_ARGS ((struct re_pattern_buffer *buffer));
/* Search in the string STRING (with length LENGTH) for the pattern
compiled into BUFFER. Start searching at position START, for RANGE
characters. Return the starting position of the match, -1 for no
match, or -2 for an internal error. Also return register
information in REGS (if REGS and BUFFER->no_sub are nonzero). */
extern int re_search
_RE_ARGS ((struct re_pattern_buffer *buffer, const char *string,
int length, int start, int range, struct re_registers *regs));
/* Like `re_search', but search in the concatenation of STRING1 and
STRING2. Also, stop searching at index START + STOP. */
extern int re_search_2
_RE_ARGS ((struct re_pattern_buffer *buffer, const char *string1,
int length1, const char *string2, int length2,
int start, int range, struct re_registers *regs, int stop));
/* Like `re_search', but return how many characters in STRING the regexp
in BUFFER matched, starting at position START. */
extern int re_match
_RE_ARGS ((struct re_pattern_buffer *buffer, const char *string,
int length, int start, struct re_registers *regs));
/* Relates to `re_match' as `re_search_2' relates to `re_search'. */
extern int re_match_2
_RE_ARGS ((struct re_pattern_buffer *buffer, const char *string1,
int length1, const char *string2, int length2,
int start, struct re_registers *regs, int stop));
/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
ENDS. Subsequent matches using BUFFER and REGS will use this memory
for recording register information. STARTS and ENDS must be
allocated with malloc, and must each be at least `NUM_REGS * sizeof
(regoff_t)' bytes long.
If NUM_REGS == 0, then subsequent matches should allocate their own
register data.
Unless this function is called, the first search or match using
PATTERN_BUFFER will allocate its own register data, without
freeing the old data. */
extern void re_set_registers
_RE_ARGS ((struct re_pattern_buffer *buffer, struct re_registers *regs,
unsigned num_regs, regoff_t *starts, regoff_t *ends));
#ifdef _REGEX_RE_COMP
/* 4.2 bsd compatibility. */
extern char *re_comp _RE_ARGS ((const char *));
extern int re_exec _RE_ARGS ((const char *));
#endif
/* POSIX compatibility. */
extern int regcomp _RE_ARGS ((regex_t *preg, const char *pattern, int cflags));
extern int regexec
_RE_ARGS ((const regex_t *preg, const char *string, size_t nmatch,
regmatch_t pmatch[], int eflags));
extern size_t regerror
_RE_ARGS ((int errcode, const regex_t *preg, char *errbuf,
size_t errbuf_size));
extern void regfree _RE_ARGS ((regex_t *preg));
#endif /* not __REGEXP_LIBRARY_H__ */
/*
Local variables:
make-backup-files: t
version-control: t
trim-versions-without-asking: nil
End:
*/
clearsilver-0.10.5/util/skiplist.c 0000644 0012117 0011610 00000037437 10261037532 014024 0000000 0000000 /*
*
* Thread-safe Skiplist Using Integer Identifiers
* Copyright 1998-2000 Scott Shambarger (scott@shambarger.net)
*
* This software is open source. Permission to use, copy, modify, and
* distribute this software for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies. No
* warranty of any kind is expressed or implied. Use at your own risk.
*
* 1/14/2001 blong
* Made it use neo errs... probably need to check locking functions
* for error returns...
*
*/
#include "cs_config.h"
#include
#include
#include
#include "neo_misc.h"
#include "neo_err.h"
#include "skiplist.h"
#include "ulocks.h"
typedef struct skipItem *skipItem;
/* structure is sized on allocation based on its level */
struct skipItem {
UINT32 locks; /* count of locks on value */
UINT32 key; /* item's key */
void *value; /* item's value */
INT32 level; /* item level */
skipItem next[1]; /* array of next items */
};
#define SIZEOFITEM(max) (sizeof(struct skipItem) + \
((max+1) * sizeof(skipItem)))
struct skipList_struct {
INT32 topLevel; /* current max level in any item */
INT32 levelHint; /* hint at level to start search */
skipItem header; /* header item (has all levels) */
skipItem tail; /* tail item (has all levels) */
/* elements to handle cached deleted items */
skipItem deleted; /* cached deleted items (linked by level+1 next entries) */
UINT32 cached; /* number of cached deleted items */
int flushing; /* TRUE if thread waiting to flush cached items */
UINT32 readers; /* number of current readers */
int block; /* TRUE if readers should wait */
pthread_mutex_t read; /* readers count/cond wait mutex */
pthread_mutex_t write; /* writer mutex */
pthread_cond_t resume; /* condition to wait on to resume reads */
pthread_cond_t flush; /* condition to wait on for flush */
/* list constants */
int threaded; /* TRUE if list needs to be thread safe */
UINT32 flushLimit; /* max number of cached deleted items before flush */
INT32 maxLevel; /* max level list can reach */
double randLimit; /* min random value to jump levels */
skipFreeValue freeValue; /* free value callback */
void *freeValueCtx; /* context to pass to callback */
};
static void readLock(skipList list) {
mLock(&list->read);
if(list->block)
cWait(&list->resume, &list->read);
list->readers++;
mUnlock(&list->read);
return;
}
static void readUnlock(skipList list, skipItem x, void **plock) {
int startFlush = FALSE;
if(list->threaded)
mLock(&list->read);
if(plock) {
x->locks++;
*plock = x;
}
if(! list->threaded)
return;
list->readers--;
if((list->readers == 0) && list->block)
startFlush = TRUE;
mUnlock(&list->read);
if(startFlush)
cSignal(&list->flush);
return;
}
static void readBlock(skipList list) {
mLock(&list->read);
list->block = TRUE;
if(list->readers)
cWait(&list->flush, &list->read); /* wait until reader locks released */
return;
}
static void readUnblock(skipList list) {
list->block = FALSE;
mUnlock(&list->read);
cBroadcast(&list->resume);
return;
}
static void writeLock(skipList list) {
mLock(&list->write);
return;
}
static void writeUnlock(skipList list) {
mUnlock(&list->write);
return;
}
static NEOERR *skipAllocItem(skipItem *item, UINT32 level, UINT32 key,
void *value)
{
if(! (*item = malloc(SIZEOFITEM(level))))
return nerr_raise(NERR_NOMEM, "Unable to allocate space for skipItem");
/* init new item */
(*item)->locks = 0;
(*item)->key = key;
(*item)->value = value;
(*item)->level = level;
return STATUS_OK;
}
static void skipFreeItem(skipList list, skipItem item) {
if(list->freeValue)
list->freeValue(item->value, list->freeValueCtx); /* free value */
free(item); /* release item */
return;
}
static void skipFlushDeleted(skipList list, int force) {
skipItem x, y, next;
x = list->deleted;
y = x->next[x->level + 1];
while(y != list->tail) {
next = y->next[y->level + 1];
if(force || (! y->locks)) { /* check if value currently locked */
x->next[x->level + 1] = next; /* set previous item's next link */
skipFreeItem(list, y); /* free item */
list->cached--; /* update cached count */
}
else {
x = y; /* make this item the previous item */
}
y = next; /* advance to next item */
}
return;
}
static void skipWriteUnlock(skipList list) {
int flush;
if(! list->threaded)
return;
if((list->cached > list->flushLimit) && (! list->flushing)) {
list->flushing = TRUE;
flush = TRUE;
}
else {
flush = FALSE;
}
writeUnlock(list); /* let any pending writes complete */
readUnlock(list, NULL, NULL); /* no longer reading */
if(flush) {
/* we are now flushing deleted items */
readBlock(list); /* acquire all read locks */
/* at this point no readers/writers are active */
skipFlushDeleted(list, FALSE); /* flush deleted items */
list->flushing = FALSE; /* done flushing */
readUnblock(list); /* let everyone continue */
}
return;
}
static skipItem skipFind(skipList list, UINT32 key) {
skipItem x, y = NULL;
INT32 i;
if(list->threaded)
readLock(list);
x = list->header; /* header contains all levels */
for(i = list->levelHint; /* loop from levelHint level down to level 0 */
i >= 0;
i--) {
y = x->next[i]; /* get next item at new level */
while(y->key < key) { /* if y has a smaller key, try the next item */
x = y; /* save x in case we overshoot */
y = x->next[i]; /* get next item */
}
}
return y;
}
void *skipSearch(skipList list, UINT32 key, void **plock) {
skipItem y;
void *value;
y = skipFind(list, key); /* find item */
if(y->key == key) { /* y has our key, or it isn't here */
value = y->value;
}
else { /* didn't find item, don't allow locks */
value = NULL;
plock = NULL;
}
readUnlock(list, y, plock);
return value;
}
void *skipNext(skipList list, UINT32 *pkey, void **plock) {
skipItem y;
void *value;
y = skipFind(list, *pkey); /* find item */
if((y->key == *pkey) && (y != list->tail)) /* skip to next if found y */
y = y->next[0];
if(y != list->tail) { /* reset key to next, return value */
*pkey = y->key;
value = y->value;
}
else { /* no next item, don't allow locks */
value = NULL;
plock = NULL;
}
readUnlock(list, y, plock);
return value;
}
void skipRelease(skipList list, void *lock) {
skipItem x;
mLock(&list->read);
x = lock;
x->locks--;
mUnlock(&list->read);
return;
}
/* list is write locked */
static NEOERR *skipNewItem(skipList list, skipItem *item, UINT32 key,
void *value)
{
INT32 level = 0;
while((drand48() < list->randLimit) && (level < list->maxLevel))
level++;
if(level > list->topLevel) {
if(list->topLevel < list->maxLevel)
list->topLevel++;
level = list->topLevel;
}
return skipAllocItem(item, level, key, value);
}
/* list is write locked */
static void skipDeleteItem(skipList list, skipItem item) {
if(list->threaded) {
item->next[item->level + 1] = list->deleted->next[1];
list->cached++;
list->deleted->next[1] = item;
}
else {
skipFreeItem(list, item);
}
return;
}
NEOERR *skipNewList(skipList *skip, int threaded, int root, int maxLevel,
int flushLimit, skipFreeValue freeValue, void *ctx)
{
NEOERR *err;
skipList list;
UINT32 i;
*skip = NULL;
if(! (list = calloc(1, sizeof(struct skipList_struct))))
return nerr_raise(NERR_NOMEM, "Unable to allocate memore for skiplist");
if (maxLevel == 0)
return nerr_raise(NERR_ASSERT, "maxLevel must be greater than 0");
if(maxLevel >= SKIP_MAXLEVEL) /* check limits */
maxLevel = SKIP_MAXLEVEL-1;
if(root > 4)
root = 4;
else if(root < 2)
root = 2;
list->maxLevel = maxLevel; /* init list constants */
list->randLimit = 1.0 / (double)root;
list->threaded = threaded;
list->freeValue = freeValue;
list->freeValueCtx = ctx;
do {
if(threaded) {
list->flushLimit = flushLimit;
err = mCreate(&list->read);
if (err != STATUS_OK) break;
err = mCreate(&list->write);
if (err != STATUS_OK) break;
err = cCreate(&list->resume);
if (err != STATUS_OK) break;
err = cCreate(&list->flush);
if (err != STATUS_OK) break;
}
err = skipAllocItem(&(list->header), list->maxLevel, 0, NULL);
if (err != STATUS_OK) break;
err = skipAllocItem(&(list->tail), list->maxLevel, (UINT32)-1, NULL);
if (err != STATUS_OK) break;
err = skipAllocItem(&(list->deleted), 0, 0, NULL);
if (err != STATUS_OK) break;
for(i = 0; /* init header and tail */
i <= list->maxLevel;
i++) {
list->tail->next[i] = NULL;
list->header->next[i] = list->tail;
}
list->deleted->next[1] = list->tail;
*skip = list;
return STATUS_OK; /* return new list */
} while(FALSE);
if(list->header) /* failed to make list, bail */
free(list->header);
free(list);
return nerr_pass(err);
}
/* list considered locked */
static void skipFreeAllItems(skipList list) {
UINT32 i;
skipItem x, y;
x = list->header->next[0];
while(x != list->tail) {
y = x->next[0]; /* get next item from level 0 pointer */
skipFreeItem(list, x); /* release item */
x = y;
}
/* clear header pointers */
for(i = 0;
i <= list->maxLevel;
i++)
list->header->next[i] = list->tail;
return;
}
void skipFreeList(skipList list) {
skipFlushDeleted(list, TRUE); /* flush deleted items */
skipFreeAllItems(list); /* free list items */
if(list->threaded) {
cDestroy(&list->flush);
cDestroy(&list->resume);
mDestroy(&list->write);
mDestroy(&list->read);
}
free(list->tail); /* free list */
free(list->header);
free(list->deleted);
free(list);
return;
}
/* is locked, is at least level , and ->key < */
static skipItem skipClosest(skipItem x, UINT32 key, UINT32 level) {
skipItem y;
y = x->next[level]; /* get next item at this level */
while(y->key < key) { /* ensure that we have the item before the key */
x = y;
y = x->next[level];
}
return x;
}
static skipItem skipLock(skipList list, UINT32 key, skipItem *save, INT32 top) {
INT32 i;
skipItem x, y;
if(list->threaded)
readLock(list);
x = list->header; /* header contains all levels */
for(i = top; /* loop from top level down to level 0 */
i >= 0;
i--) {
y = x->next[i]; /* get next item at this level */
while(y->key < key) { /* if y has a smaller key, try the next item */
x = y; /* save x in case we overshoot */
y = x->next[i]; /* get next item */
}
save[i] = x; /* preserve item with next pointer in save */
}
if(list->threaded)
writeLock(list); /* lock list for update */
/* validate we have the closest previous item */
return skipClosest(x, key, 0);
}
NEOERR *skipInsert(skipList list, UINT32 key, void *value, int allowUpdate)
{
NEOERR *err;
INT32 i, level;
skipItem save[SKIP_MAXLEVEL];
skipItem x, y;
if (value == 0)
return nerr_raise(NERR_ASSERT, "value must be non-zero");
if (key == 0 || key == (UINT32)-1)
return nerr_raise(NERR_ASSERT, "key must not be 0 or -1");
level = list->levelHint;
x = skipLock(list, key, save, level); /* quick search for key */
y = x->next[0];
if(y->key == key) {
if(!allowUpdate)
{
skipWriteUnlock(list);
return nerr_raise(NERR_DUPLICATE, "key %u exists in skiplist", key);
}
y->value = value; /* found the key, update value */
skipWriteUnlock(list);
return STATUS_OK;
}
err = skipNewItem(list, &y, key, value);
if (err != STATUS_OK)
{
skipWriteUnlock(list);
return nerr_pass(err);
}
for(i = level + 1; /* is new item has more levels than */
i <= y->level; /* if so fill in save */
i++)
save[i] = list->header;
for(i = 0; /* populate pointers for all levels */
i <= y->level;
i++) {
if(i) /* check that save is correct for each level */
x = skipClosest(save[i], key, i);
y->next[i] = x->next[i]; /* now insert the item at this level */
x->next[i] = y; /* (order here important for thread-safeness) */
}
while((list->levelHint < list->topLevel) /* update levelHint */
&& (list->header->next[list->levelHint+1] != list->tail))
list->levelHint++;
skipWriteUnlock(list);
return STATUS_OK;
}
void skipDelete(skipList list, UINT32 key) {
INT32 i, level;
skipItem save[SKIP_MAXLEVEL];
skipItem x, y;
assert(key && (key != (UINT32)-1));
level = list->levelHint;
x = skipLock(list, key, save, level); /* quick search for key */
y = x->next[0];
/* check that we found the key, and it isn't deleted */
if((y->key != key) || (y->next[0]->key < key)) {
skipWriteUnlock(list);
return;
}
for(i = level + 1; /* check if item has more levels than */
i <= y->level; /* if so fill in save */
i++)
save[i] = list->header;
for(i = y->level;
i >= 0;
i--) {
/* check that save is correct for each level */
x = skipClosest(save[i], key, i);
x->next[i] = y->next[i]; /* now remove item at this level */
y->next[i] = x; /* (order here is imported for thread-safeness) */
}
skipDeleteItem(list, y); /* put on deleted list */
while((list->levelHint > 0) /* update levelHint */
&& (list->header->next[list->levelHint] == list->tail))
list->levelHint--;
skipWriteUnlock(list);
return;
}
clearsilver-0.10.5/util/skiplist.h 0000644 0012117 0011610 00000014147 10261037532 014022 0000000 0000000 /*
*
* Thread-safe Skiplist Using Integer Identifiers
* Copyright 1998-2000 Scott Shambarger (scott@shambarger.net)
*
* This software is open source. Permission to use, copy, modify, and
* distribute this software for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies. No
* warranty of any kind is expressed or implied. Use at your own risk.
*
* 1/14/2001 blong
* Made it use neo errs... probably need to check locking functions
* for error returns...
*
*/
#ifndef __SKIPLIST_H_
#define __SKIPLIST_H_
#include "util/neo_err.h"
__BEGIN_DECLS
/*
* Larger values of means fewer levels and faster lookups,
* but more variability in those lookup times (range limited from 2 to 4).
*
* should be calculated from expected list size using (^ = power):
*
* ^ == expected # of items
*
* I've capped