]> git.kernelconcepts.de Git - karo-tx-redboot.git/commitdiff
Initial revision
authorlothar <lothar>
Fri, 13 Feb 2009 16:55:51 +0000 (16:55 +0000)
committerlothar <lothar>
Fri, 13 Feb 2009 16:55:51 +0000 (16:55 +0000)
75 files changed:
packages/compat/posix/v2_0/include/sys/time.h [new file with mode: 0644]
packages/compat/posix/v2_0/tests/pmqueue1.c [new file with mode: 0644]
packages/compat/posix/v2_0/tests/pmqueue2.c [new file with mode: 0644]
packages/compat/posix/v2_0/tests/pmutex3.c [new file with mode: 0644]
packages/compat/posix/v2_0/tests/tm_posix.cxx [new file with mode: 0644]
packages/net/.cvsignore [new file with mode: 0644]
packages/net/athttpd/v2_0/ChangeLog [new file with mode: 0644]
packages/net/athttpd/v2_0/cdl/httpd.cdl [new file with mode: 0644]
packages/net/athttpd/v2_0/doc/athttpd.sgml [new file with mode: 0644]
packages/net/athttpd/v2_0/doc/mime_types.txt [new file with mode: 0644]
packages/net/athttpd/v2_0/include/auth.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/cgi.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/digcalc.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/forms.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/global.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/handler.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/http.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/jim.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/md5.h [new file with mode: 0644]
packages/net/athttpd/v2_0/include/socket.h [new file with mode: 0644]
packages/net/athttpd/v2_0/src/auth.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/cgi.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/forms.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/handler.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/http.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/jim-aio.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/jim.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/md5c.c [new file with mode: 0644]
packages/net/athttpd/v2_0/src/socket.c [new file with mode: 0644]
packages/net/autotest/v2_0/ChangeLog [new file with mode: 0644]
packages/net/autotest/v2_0/cdl/net_autotest.cdl [new file with mode: 0644]
packages/net/autotest/v2_0/doc/host.txt [new file with mode: 0644]
packages/net/autotest/v2_0/doc/strategy.txt [new file with mode: 0644]
packages/net/autotest/v2_0/host/_suping.c [new file with mode: 0644]
packages/net/autotest/v2_0/host/awaitorder.c [new file with mode: 0644]
packages/net/autotest/v2_0/host/floodping.sh [new file with mode: 0755]
packages/net/autotest/v2_0/host/makefile [new file with mode: 0644]
packages/net/autotest/v2_0/host/obey.sh [new file with mode: 0755]
packages/net/autotest/v2_0/host/sendack.sh [new file with mode: 0755]
packages/net/autotest/v2_0/host/slowping.sh [new file with mode: 0755]
packages/net/autotest/v2_0/host/snmpwalk.sh [new file with mode: 0755]
packages/net/autotest/v2_0/host/tftpget.sh [new file with mode: 0755]
packages/net/autotest/v2_0/host/tftpput.sh [new file with mode: 0755]
packages/net/autotest/v2_0/host/tmpfile.c [new file with mode: 0644]
packages/net/autotest/v2_0/permtests/netauto_bootp.ptest [new file with mode: 0644]
packages/net/autotest/v2_0/permtests/netauto_corrupt.ptest [new file with mode: 0644]
packages/net/autotest/v2_0/permtests/netauto_failrx.ptest [new file with mode: 0644]
packages/net/autotest/v2_0/permtests/netauto_failtx.ptest [new file with mode: 0644]
packages/net/autotest/v2_0/permtests/netauto_rt.ptest [new file with mode: 0644]
packages/net/autotest/v2_0/permtests/netauto_snmp.ptest [new file with mode: 0644]
packages/net/autotest/v2_0/permtests/netauto_std.ptest [new file with mode: 0644]
packages/net/autotest/v2_0/tests/autohost.inl [new file with mode: 0644]
packages/net/autotest/v2_0/tests/floodping.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/floodpingmux.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/memcheck.inl [new file with mode: 0644]
packages/net/autotest/v2_0/tests/route_3.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/route_3_4.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/route_4.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/route_none.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/routeping.inl [new file with mode: 0644]
packages/net/autotest/v2_0/tests/slowping.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/slowpingmux.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/snmpmulti.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/snmppings.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/snmpwalk.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv.inl [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_g0.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_g1M.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_g512.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_get.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_p0.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_p1M.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_p512.c [new file with mode: 0644]
packages/net/autotest/v2_0/tests/tftp_serv_put.c [new file with mode: 0644]
packages/net/ipsec/.cvsignore [new file with mode: 0644]

diff --git a/packages/compat/posix/v2_0/include/sys/time.h b/packages/compat/posix/v2_0/include/sys/time.h
new file mode 100644 (file)
index 0000000..c695862
--- /dev/null
@@ -0,0 +1,173 @@
+//==========================================================================
+//
+//      include/sys/time.h
+//
+//      
+//
+//==========================================================================
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    gthomas
+// Contributors: gthomas
+// Date:         2000-01-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+
+/*     $OpenBSD: time.h,v 1.9 1999/12/06 19:36:42 aaron Exp $  */
+/*     $NetBSD: time.h,v 1.18 1996/04/23 10:29:33 mycroft Exp $        */
+
+/*
+ * Copyright (c) 1982, 1986, 1993
+ *     The Regents of the University of California.  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. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *     This product includes software developed by the University of
+ *     California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ *     @(#)time.h      8.2 (Berkeley) 7/10/94
+ */
+
+#ifndef _SYS_TIME_H_
+#define _SYS_TIME_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <sys/types.h>
+#include <time.h>
+
+/*
+ * Structure returned by gettimeofday(2) system call,
+ * and used in other calls.
+ */
+struct timeval {
+       long    tv_sec;         /* seconds */
+       long    tv_usec;        /* and microseconds */
+};
+
+
+#define        TIMEVAL_TO_TIMESPEC(tv, ts) {                                   \
+       (ts)->tv_sec = (tv)->tv_sec;                                    \
+       (ts)->tv_nsec = (tv)->tv_usec * 1000;                           \
+}
+#define        TIMESPEC_TO_TIMEVAL(tv, ts) {                                   \
+       (tv)->tv_sec = (ts)->tv_sec;                                    \
+       (tv)->tv_usec = (ts)->tv_nsec / 1000;                           \
+}
+
+struct timezone {
+       int     tz_minuteswest; /* minutes west of Greenwich */
+       int     tz_dsttime;     /* type of dst correction */
+};
+
+#define        DST_NONE        0       /* not on dst */
+#define        DST_USA         1       /* USA style dst */
+#define        DST_AUST        2       /* Australian style dst */
+#define        DST_WET         3       /* Western European dst */
+#define        DST_MET         4       /* Middle European dst */
+#define        DST_EET         5       /* Eastern European dst */
+#define        DST_CAN         6       /* Canada */
+
+/* Operations on timevals. */
+#define        timerclear(tvp)         (tvp)->tv_sec = (tvp)->tv_usec = 0
+#define        timerisset(tvp)         ((tvp)->tv_sec || (tvp)->tv_usec)
+#define        timercmp(tvp, uvp, cmp)                                         \
+       (((tvp)->tv_sec == (uvp)->tv_sec) ?                             \
+           ((tvp)->tv_usec cmp (uvp)->tv_usec) :                       \
+           ((tvp)->tv_sec cmp (uvp)->tv_sec))
+#define        timeradd(tvp, uvp, vvp)                                         \
+       do {                                                            \
+               (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;          \
+               (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
+               if ((vvp)->tv_usec >= 1000000) {                        \
+                       (vvp)->tv_sec++;                                \
+                       (vvp)->tv_usec -= 1000000;                      \
+               }                                                       \
+       } while (0)
+#define        timersub(tvp, uvp, vvp)                                         \
+       do {                                                            \
+               (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;          \
+               (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;       \
+               if ((vvp)->tv_usec < 0) {                               \
+                       (vvp)->tv_sec--;                                \
+                       (vvp)->tv_usec += 1000000;                      \
+               }                                                       \
+       } while (0)
+
+/* Operations on timespecs. */
+#define        timespecclear(tsp)              (tsp)->tv_sec = (tsp)->tv_nsec = 0
+#define        timespecisset(tsp)              ((tsp)->tv_sec || (tsp)->tv_nsec)
+#define        timespeccmp(tsp, usp, cmp)                                      \
+       (((tsp)->tv_sec == (usp)->tv_sec) ?                             \
+           ((tsp)->tv_nsec cmp (usp)->tv_nsec) :                       \
+           ((tsp)->tv_sec cmp (usp)->tv_sec))
+#define        timespecadd(tsp, usp, vsp)                                      \
+       do {                                                            \
+               (vsp)->tv_sec = (tsp)->tv_sec + (usp)->tv_sec;          \
+               (vsp)->tv_nsec = (tsp)->tv_nsec + (usp)->tv_nsec;       \
+               if ((vsp)->tv_nsec >= 1000000000L) {                    \
+                       (vsp)->tv_sec++;                                \
+                       (vsp)->tv_nsec -= 1000000000L;                  \
+               }                                                       \
+       } while (0)
+#define        timespecsub(tsp, usp, vsp)                                      \
+       do {                                                            \
+               (vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec;          \
+               (vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec;       \
+               if ((vsp)->tv_nsec < 0) {                               \
+                       (vsp)->tv_sec--;                                \
+                       (vsp)->tv_nsec += 1000000000L;                  \
+               }                                                       \
+       } while (0)
+
+
+int    gettimeofday(struct timeval *, struct timezone *);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif
diff --git a/packages/compat/posix/v2_0/tests/pmqueue1.c b/packages/compat/posix/v2_0/tests/pmqueue1.c
new file mode 100644 (file)
index 0000000..38272a0
--- /dev/null
@@ -0,0 +1,359 @@
+/*========================================================================
+//
+//      pmqueue1.c
+//
+//      POSIX Message queues tests
+//
+//========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
+// at http://sources.redhat.com/ecos/ecos-license/
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):     jlarmour
+// Contributors:  
+// Date:          2000-05-18
+// Purpose:       This file provides tests for POSIX mqueues
+// Description:   
+// Usage:         
+//
+//####DESCRIPTIONEND####
+//
+//======================================================================
+*/
+
+/* CONFIGURATION */
+
+#include <pkgconf/posix.h>
+
+#ifndef CYGPKG_POSIX_MQUEUES
+# define NA_MSG "Message queues not configured"
+#endif
+
+#ifdef NA_MSG
+#include <cyg/infra/testcase.h>      // test API
+void
+cyg_user_start(void)
+{
+    CYG_TEST_NA( NA_MSG );
+}
+
+#else
+
+/* INCLUDES */
+
+#include <fcntl.h>                   // O_*
+#include <errno.h>                   // errno
+#include <sys/stat.h>                // file modes
+#include <mqueue.h>                  // Mqueue Header
+#include <cyg/infra/testcase.h>      // test API
+
+/* FUNCTIONS */
+
+static int
+my_memcmp(const void *m1, const void *m2, size_t n)
+{
+    char *s1 = (char *)m1;
+    char *s2 = (char *)m2;
+
+    while (n--) {
+        if (*s1 != *s2)
+            return *s1 - *s2;
+        s1++;
+        s2++;
+    }
+    return 0;
+} // my_memcmp()
+
+//************************************************************************
+
+int
+main(void)
+{
+    mqd_t q1, q2;
+    char buf[20];
+    ssize_t recvlen;
+    unsigned int prio;
+    struct mq_attr attr, oattr;
+    mode_t mode;
+    int err;
+
+    CYG_TEST_INIT();
+    CYG_TEST_INFO( "Starting POSIX message test 1" );
+
+    q1 = mq_open( "/mq1", O_RDWR );
+    CYG_TEST_PASS_FAIL( q1 == (mqd_t)-1, "error for non-existent queue" );
+    CYG_TEST_PASS_FAIL( ENOENT == errno,
+                        "errno correct for non-existent queue" );
+
+    attr.mq_flags = 0;
+    attr.mq_maxmsg = 4;
+    attr.mq_msgsize = 20;
+    mode = S_IRWXU|S_IRWXG|S_IRWXO; // rwx for all
+
+    q1 = mq_open( "/mq1", O_CREAT|O_NONBLOCK|O_WRONLY, mode, &attr );
+    CYG_TEST_PASS_FAIL( q1 != (mqd_t)-1, "simple mq_open (write only)" );
+    
+    err = mq_getattr( q1, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_getattr" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK == (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY != (attr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY == (attr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (attr.mq_flags & O_RDWR)) &&
+                        (0 == attr.mq_curmsgs ), "getattr attributes correct" );
+                        
+    err = mq_send( q1, "Vik is brill", sizeof("Vik is brill"), 10 );
+
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_send" );
+    
+    err = mq_getattr( q1, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_getattr after send" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK == (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY != (attr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY == (attr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (attr.mq_flags & O_RDWR)) &&
+                        (1 == attr.mq_curmsgs ),
+                        "getattr attributes correct #2" );
+                        
+    q2 = mq_open( "/mq1", O_RDONLY|O_CREAT|O_EXCL );
+    CYG_TEST_PASS_FAIL( q2 == (mqd_t)-1,
+                        "error for exclusive open of existing queue" );
+    CYG_TEST_PASS_FAIL( EEXIST == errno,
+                        "errno correct for exclusive open of existing queue" );
+    
+    q2 = mq_open( "/mq1", O_RDONLY );
+    CYG_TEST_PASS_FAIL( q2 != (mqd_t)-1, "simple mq_open (read only)" );
+    
+    err = mq_getattr( q2, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_getattr, different mqd_t" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK != (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY == (attr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY != (attr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (attr.mq_flags & O_RDWR)) &&
+                        (1 == attr.mq_curmsgs ),
+                        "getattr attributes correct #3" );
+
+    err = mq_close( q2 );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_close" );
+    
+    q2 = mq_open( "/mq1", O_RDONLY );
+    CYG_TEST_PASS_FAIL( q2 != (mqd_t)-1, "mq_open reopen (read only)" );
+    
+    err = mq_getattr( q2, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_getattr, different mqd_t" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK != (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY == (attr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY != (attr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (attr.mq_flags & O_RDWR)) &&
+                        (1 == attr.mq_curmsgs ),
+                        "getattr attributes correct #4" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == sizeof("Vik is brill"),
+                        "receive message length" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, "Vik is brill",
+                                        sizeof("Vik is brill")),
+                        "received message data intact" );
+    CYG_TEST_PASS_FAIL( 10 == prio, "received at correct priority" );
+
+    err = mq_getattr( q1, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_getattr after send" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK == (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY != (attr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY == (attr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (attr.mq_flags & O_RDWR)) &&
+                        (0 == attr.mq_curmsgs ),
+                        "getattr attributes correct #5" );
+
+    attr.mq_flags |= O_NONBLOCK;
+    err = mq_setattr( q2, &attr, &oattr );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_setattr O_NONBLOCK" );
+    CYG_TEST_PASS_FAIL( (4 == oattr.mq_maxmsg) &&
+                        (20 == oattr.mq_msgsize) &&
+                        (O_NONBLOCK != (oattr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY == (oattr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY != (oattr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (oattr.mq_flags & O_RDWR)) &&
+                        (0 == oattr.mq_curmsgs ),
+                        "old attribute correct" );
+    err = mq_getattr( q2, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_getattr after O_NONBLOCK" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK == (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY == (attr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY != (attr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (attr.mq_flags & O_RDWR)) &&
+                        (0 == attr.mq_curmsgs ),
+                        "new attribute correct" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == (ssize_t)-1,
+                        "mq_receive, empty buffer, non-blocking" );
+    CYG_TEST_PASS_FAIL( EAGAIN == errno,
+                        "errno correct for non-blocking" );
+    
+    err = mq_send( q2, "foo", sizeof("foo"), 1 );
+    CYG_TEST_PASS_FAIL( -1 == err, "error on mq_send on read-only descriptor" );
+    CYG_TEST_PASS_FAIL( EBADF == errno,
+                        "errno correct for mq_send on r/o descriptor" );
+    
+    err = mq_send( q2, "supercalifragilisticexpealidocious", 21, 2 );
+    CYG_TEST_PASS_FAIL( -1 == err, "error on mq_send (message too long)" );
+    CYG_TEST_PASS_FAIL( EMSGSIZE == errno,
+                        "errno correct for mq_send (message too long)" );
+    
+    err = mq_send( q1, "", sizeof(""), 5 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send \"\"" );
+    
+    err = mq_send( q1, "I love Vik", sizeof("I love Vik"), 7 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send (different priority)" );
+    
+    err = mq_send( q1, "a lot!", sizeof("a lot!"), 7 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send (same priority)" );
+    
+    err = mq_send( q1, "Vik is a babe", sizeof("Vik is a babe"), 6 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send (middle priority)" );
+    
+    err = mq_send( q1, "wibble", sizeof("wibble"), 6 );
+    CYG_TEST_PASS_FAIL( -1 == err, "error on mq_send with full queue" );
+    CYG_TEST_PASS_FAIL( EAGAIN == errno,
+                        "errno correct for mq_send full queue" );
+    
+    err = mq_getattr( q2, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_getattr after sends" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK == (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDONLY == (attr.mq_flags & O_RDONLY)) &&
+                        (O_WRONLY != (attr.mq_flags & O_WRONLY)) &&
+                        (O_RDWR != (attr.mq_flags & O_RDWR)) &&
+                        (4 == attr.mq_curmsgs ),
+                        "getattr attributes correct #5" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == sizeof("I love Vik"),
+                        "receive message length (prioritized) #1" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, "I love Vik",
+                                        sizeof("I love Vik")),
+                        "received message data intact (prioritized) #1" );
+    CYG_TEST_PASS_FAIL( 7 == prio,
+                        "received at correct priority (prioritized) #1" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == sizeof("a lot!"),
+                        "receive message length (prioritized) #2" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, "a lot!",
+                                        sizeof("a lot!")),
+                        "received message data intact (prioritized) #2" );
+    CYG_TEST_PASS_FAIL( 7 == prio,
+                        "received at correct priority (prioritized) #2" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == sizeof("Vik is a babe"),
+                        "receive message length (prioritized) #3" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, "Vik is a babe",
+                                        sizeof("Vik is a babe")),
+                        "received message data intact (prioritized) #3" );
+    CYG_TEST_PASS_FAIL( 6 == prio,
+                        "received at correct priority (prioritized) #3" );
+
+    recvlen = mq_receive( q2, buf, 0, &prio );
+    CYG_TEST_PASS_FAIL( recvlen == (ssize_t)-1,
+                        "mq_receive, zero-sized buffer" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == sizeof(""),
+                        "receive message length (prioritized) #4" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, "",
+                                        sizeof("")),
+                        "received message data intact (prioritized) #4" );
+    CYG_TEST_PASS_FAIL( 5 == prio,
+                        "received at correct priority (prioritzed) #4" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == (ssize_t)-1,
+                        "mq_receive, empty buffer, non-blocking #2" );
+    CYG_TEST_PASS_FAIL( EAGAIN == errno,
+                        "errno correct for non-blocking #2" );
+    
+    err = mq_send( q1, "12345678901234567890", 20, 15 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send (before closing)" );
+    
+    err = mq_unlink( "/foo" );
+    CYG_TEST_PASS_FAIL( -1 == err, "mq_unlink (wrong name)" );
+    CYG_TEST_PASS_FAIL( ENOENT == errno,
+                        "errno correct for mq_unlink (wrong name)" );
+
+    err = mq_unlink( "/mq1" );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_unlink (before closing)" );
+
+    err = mq_close( q1 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_close (send descriptor)" );
+
+    recvlen = mq_receive( q2, buf, sizeof(buf), &prio );
+    CYG_TEST_PASS_FAIL( recvlen == 20,
+                        "receive message length (mid close)" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, "12345678901234567890", 20 ),
+                        "received message data intact (mid close)" );
+    CYG_TEST_PASS_FAIL( 15 == prio,
+                        "received at correct priority (mid close)" );
+
+    err = mq_close( q2 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_close (receive descriptor)" );
+
+    q1 = mq_open( "/mq1", O_RDONLY );
+    CYG_TEST_PASS_FAIL( q1 == (mqd_t)-1, "error for non-existent queue" );
+    CYG_TEST_PASS_FAIL( ENOENT == errno,
+                        "errno correct for non-existent queue" );
+
+    CYG_TEST_EXIT("POSIX message test 1");
+
+    return 0;
+} // main()
+
+//------------------------------------------------------------------------
+
+#endif
+
+/* EOF pmqueue1.c */
diff --git a/packages/compat/posix/v2_0/tests/pmqueue2.c b/packages/compat/posix/v2_0/tests/pmqueue2.c
new file mode 100644 (file)
index 0000000..4f9c1b0
--- /dev/null
@@ -0,0 +1,276 @@
+/*========================================================================
+//
+//      pmqueue2.c
+//
+//      POSIX Message queues tests - mq_notify
+//
+//========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
+// at http://sources.redhat.com/ecos/ecos-license/
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):     jlarmour
+// Contributors:  
+// Date:          2000-05-18
+// Purpose:       This file provides tests for POSIX mqueue mq_notify
+// Description:   
+// Usage:         
+//
+//####DESCRIPTIONEND####
+//
+//======================================================================
+*/
+
+/* CONFIGURATION */
+
+#include <pkgconf/posix.h>
+
+#ifndef CYGPKG_POSIX_MQUEUES
+# define NA_MSG "Message queues not configured"
+#elif !defined(CYGPKG_POSIX_SIGNALS)
+# define NA_MSG "No POSIX signals configured"
+#endif
+
+#ifdef NA_MSG
+#include <cyg/infra/testcase.h>      // test API
+void
+cyg_user_start(void)
+{
+    CYG_TEST_INIT();
+    CYG_TEST_NA( NA_MSG );
+}
+
+#else
+
+/* INCLUDES */
+
+#include <fcntl.h>                   // O_*
+#include <errno.h>                   // errno
+#include <sys/stat.h>                // file modes
+#include <mqueue.h>                  // Mqueue Header
+#include <cyg/infra/testcase.h>      // test API
+#include <signal.h>                  // signals
+
+/* GLOBALS */
+sig_atomic_t signals=0;
+char buf[20];
+unsigned int prio;
+
+
+/* FUNCTIONS */
+
+static int
+my_memcmp(const void *m1, const void *m2, size_t n)
+{
+    char *s1 = (char *)m1;
+    char *s2 = (char *)m2;
+
+    while (n--) {
+        if (*s1 != *s2)
+            return *s1 - *s2;
+        s1++;
+        s2++;
+    }
+    return 0;
+} // my_memcmp()
+
+static char *
+my_strcpy(char *s1, const char *s2)
+{
+    char *s = s1;
+    while (*s2) {
+        *s1++ = *s2++;
+    }
+    return s;
+} // my_strcpy()
+
+static size_t
+my_strlen(const char *s)
+{
+    const char *start = s;
+    while (*s)
+        s++;
+    return (s - start);
+} // my_strcpy()
+
+
+
+//************************************************************************
+
+static void
+sigusr1_handler( int signo, siginfo_t *info, void *context )
+{
+    ssize_t recvlen;
+    char mybuf[20];
+    unsigned int myprio;
+    mqd_t *q = (mqd_t *)info->si_value.sival_ptr;
+
+    CYG_TEST_PASS_FAIL( SIGUSR1 == signo, "correct signal number #1" );
+    CYG_TEST_PASS_FAIL( SIGUSR1 == info->si_signo, "correct signal number #2" );
+    CYG_TEST_PASS_FAIL( SI_MESGQ == info->si_code, "correct signal code" );
+
+    signals++;
+
+    // retrieve message and compare with buf
+    recvlen = mq_receive( *q, mybuf, sizeof(mybuf), &myprio );
+    CYG_TEST_PASS_FAIL( recvlen == my_strlen(buf),
+                        "receive message length" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, mybuf, my_strlen(buf)),
+                        "received message data intact" );
+    CYG_TEST_PASS_FAIL( prio == myprio,
+                        "received at correct priority" );
+}
+
+//************************************************************************
+
+int
+main(void)
+{
+    mqd_t q1;
+    struct mq_attr attr;
+    mode_t mode;
+    int err;
+    ssize_t recvlen;
+    char mybuf[20];
+    unsigned int myprio;
+    struct sigevent ev;
+    struct sigaction act;
+
+    CYG_TEST_INIT();
+    CYG_TEST_INFO( "Starting POSIX message test 2" );
+
+#if 0
+    if ( 0 != pthread_create( &thr, NULL, &thread, NULL ) ) {
+        CYG_TEST_FAIL_FINISH( "Couldn't create a helper thread" );
+    }
+#endif
+
+    attr.mq_flags = 0;
+    attr.mq_maxmsg = 4;
+    attr.mq_msgsize = 20;
+    mode = S_IRWXU|S_IRWXG|S_IRWXO; // rwx for all
+
+    q1 = mq_open( "/mq1", O_CREAT|O_NONBLOCK|O_RDWR, mode, &attr );
+    CYG_TEST_PASS_FAIL( q1 != (mqd_t)-1, "simple mq_open (write only)" );
+    
+    err = mq_getattr( q1, &attr );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_getattr" );
+    CYG_TEST_PASS_FAIL( (4 == attr.mq_maxmsg) &&
+                        (20 == attr.mq_msgsize) &&
+                        (O_NONBLOCK == (attr.mq_flags & O_NONBLOCK)) &&
+                        (O_RDWR == (attr.mq_flags & O_RDWR)) &&
+                        (0 == attr.mq_curmsgs ), "getattr attributes correct" );
+
+
+    act.sa_sigaction = &sigusr1_handler;
+    sigfillset( &act.sa_mask ); // enable all signals
+    act.sa_flags = SA_SIGINFO;
+    
+    if ( 0 != sigaction( SIGUSR1, &act, NULL ) ) {
+        CYG_TEST_FAIL_FINISH( "Couldn't register signal handler" );
+    }
+
+    ev.sigev_notify = SIGEV_SIGNAL;
+    ev.sigev_signo = SIGUSR1;
+    ev.sigev_value.sival_ptr = (void *)&q1;
+
+    err = mq_notify( q1, &ev );
+    CYG_TEST_PASS_FAIL( 0 == err, "simple mq_notify" );
+
+    my_strcpy( buf, "Vik is the best" );
+    prio = 7;
+    err = mq_send( q1, buf, my_strlen(buf), prio );
+
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send #1" );
+
+    CYG_TEST_PASS_FAIL( 1 == signals, "got notification" );
+
+    my_strcpy( buf, "Scrummy Vik" );
+    prio = 6;
+    err = mq_send( q1, buf, my_strlen(buf), prio );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send #2" );
+
+    CYG_TEST_PASS_FAIL( 1 == signals, "correctly didn't get notification" );
+
+    recvlen = mq_receive( q1, mybuf, sizeof(mybuf), &myprio );
+    CYG_TEST_PASS_FAIL( recvlen == my_strlen(buf),
+                        "receive message length" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, mybuf, my_strlen(buf)),
+                        "received message data intact" );
+    CYG_TEST_PASS_FAIL( prio == myprio,
+                        "received at correct priority" );
+
+    err = mq_notify( q1, &ev );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_notify #2" );
+
+    err = mq_notify( q1, &ev );
+    CYG_TEST_PASS_FAIL( -1 == err, "second mq_notify returns error" );
+    CYG_TEST_PASS_FAIL( EBUSY == errno,
+                        "errno correct for second mq_notify error" );
+
+    err = mq_notify( q1, NULL );
+    CYG_TEST_PASS_FAIL( 0 == err, "clear notification" );
+
+    my_strcpy( buf, "Vik is k3wl" );
+    prio = 8;
+    err = mq_send( q1, buf, my_strlen(buf), prio );
+
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_send #2" );
+
+    CYG_TEST_PASS_FAIL( 1 == signals, "correctly didn't get notification #2" );
+
+    recvlen = mq_receive( q1, mybuf, sizeof(mybuf), &myprio );
+    CYG_TEST_PASS_FAIL( recvlen == my_strlen(buf),
+                        "receive message length" );
+    CYG_TEST_PASS_FAIL( 0 == my_memcmp( buf, mybuf, my_strlen(buf)),
+                        "received message data intact" );
+    CYG_TEST_PASS_FAIL( prio == myprio,
+                        "received at correct priority" );
+    
+    err = mq_close( q1 );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_close" );
+
+    err = mq_unlink( "/mq1" );
+    CYG_TEST_PASS_FAIL( 0 == err, "mq_unlink" );
+
+    CYG_TEST_EXIT("POSIX message test 2");
+
+    return 0;
+} // main()
+
+//------------------------------------------------------------------------
+
+#endif
+
+/* EOF pmqueue2.c */
diff --git a/packages/compat/posix/v2_0/tests/pmutex3.c b/packages/compat/posix/v2_0/tests/pmutex3.c
new file mode 100644 (file)
index 0000000..7d712e1
--- /dev/null
@@ -0,0 +1,672 @@
+//==========================================================================
+//
+//        pmutex3.c
+//
+//        Mutex test 3 - priority inheritance
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
+// at http://sources.redhat.com/ecos/ecos-license/
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):     hmt
+// Contributors:  hmt, nickg, jlarmour
+// Date:          2000-01-06
+// Description:   Tests mutex priority inheritance. This is simply a translation
+//                of the similarly named kernel test to the POSIX API
+//####DESCRIPTIONEND####
+
+// ------------------------------------------------------------------------
+
+#include <cyg/infra/testcase.h>
+#include <pkgconf/posix.h>
+#include <pkgconf/system.h>
+#ifdef CYGPKG_KERNEL
+#include <pkgconf/kernel.h>
+#endif
+
+#ifdef CYGPKG_ISOINFRA
+# include <sys/types.h>
+# include <pthread.h>
+# include <semaphore.h>
+# include <time.h>
+# include <unistd.h>
+#endif
+
+#if !defined(CYGPKG_POSIX_PTHREAD)
+#define NA_MSG "POSIX threads not enabled"
+
+// ------------------------------------------------------------------------
+//
+// These checks should be enough; any other scheduler which has priorities
+// should manifest as having no priority inheritance, but otherwise fine,
+// so the test should work correctly.
+
+#elif !defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
+#define NA_MSG "No POSIX thread priority scheduling enabled"
+#elif !defined(_POSIX_THREAD_PRIO_INHERIT)
+#define NA_MSG "No POSIX thread priority inheritance enabled"
+#elif !defined(_POSIX_SEMAPHORES)
+#define NA_MSG "No POSIX sempaphore support enabled enabled"
+#elif !defined(CYGFUN_KERNEL_API_C)
+#define NA_MSG "Kernel C API not enabled"
+#elif defined(CYGPKG_KERNEL_SMP_SUPPORT)
+#define NA_MSG "Test cannot run with SMP support"
+#endif
+
+#ifdef NA_MSG
+void
+cyg_start(void)
+{
+    CYG_TEST_INIT();
+    CYG_TEST_NA(NA_MSG);
+}
+#else
+
+#include <cyg/infra/cyg_ass.h>
+#include <cyg/infra/cyg_trac.h>
+#include <cyg/infra/diag.h>             // diag_printf
+
+#include <cyg/kernel/kapi.h>            // Some extras
+
+// ------------------------------------------------------------------------
+// Management functions
+//
+// Stolen from testaux.hxx and copied in here because I want to be able to
+// reset the world also.
+// ... and subsequently POSIXized out of all similarly with its progenitors.
+
+#define NTHREADS 7
+
+#define STACKSIZE (PTHREAD_STACK_MIN*2)
+
+static pthread_t thread[NTHREADS] = { 0 };
+
+typedef CYG_WORD64 CYG_ALIGNMENT_TYPE;
+
+static CYG_ALIGNMENT_TYPE stack[NTHREADS] [
+   (STACKSIZE+sizeof(CYG_ALIGNMENT_TYPE)-1)
+     / sizeof(CYG_ALIGNMENT_TYPE)                     ];
+
+// Semaphores to halt execution of threads     
+static sem_t hold[NTHREADS];
+
+// Flag to tell all threads to exit
+static int all_exit;
+
+// Application thread data is passed here, the thread
+// argument is 
+static CYG_ADDRWORD thread_data[NTHREADS];
+
+static volatile int nthreads = 0;
+
+// Sleep for 1 tick...
+static struct timespec sleeptime;
+
+
+static pthread_t new_thread( void *(*entry)(void *),
+                             CYG_ADDRWORD data,
+                             int priority,
+                             int do_resume)
+{
+    pthread_attr_t attr;
+    int _nthreads = nthreads++;
+
+    struct sched_param schedparam;
+    schedparam.sched_priority = priority;
+        
+    pthread_attr_init( &attr );
+    pthread_attr_setstackaddr( &attr, (void *)((char *)(&stack[_nthreads])+STACKSIZE) );        
+    pthread_attr_setstacksize( &attr, STACKSIZE );
+    pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
+    pthread_attr_setschedpolicy( &attr, SCHED_RR );
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    CYG_ASSERT(_nthreads < NTHREADS, 
+               "Attempt to create more than NTHREADS threads");
+
+    thread_data[_nthreads] = data;
+
+    sem_init( &hold[_nthreads], 0, do_resume ? 1 : 0 );
+    all_exit = 0;
+
+    pthread_create( &thread[_nthreads],
+                    &attr,
+                    entry,
+                    (void *)_nthreads);
+
+    return thread[_nthreads];
+}
+
+
+static void kill_threads( void )
+{
+    CYG_ASSERT(nthreads <= NTHREADS, 
+               "More than NTHREADS threads");
+    CYG_ASSERT( pthread_equal(pthread_self(),thread[0]),
+                "kill_threads() not called from thread 0");
+    all_exit = 1;
+    while ( nthreads > 1 ) {
+        nthreads--;
+        if ( 0 != thread[nthreads] ) {
+            sem_post( &hold[nthreads] );
+            pthread_cancel( thread[nthreads] );
+            pthread_join( thread[nthreads], NULL );
+            thread[nthreads] = 0;
+            sem_destroy( &hold[nthreads] );
+        }
+    }
+    CYG_ASSERT(nthreads == 1,
+               "No threads left");
+}
+
+// ------------------------------------------------------------------------
+
+#define DELAYFACTOR 1 // for debugging
+
+// ------------------------------------------------------------------------
+
+pthread_mutex_t mutex;
+
+// These are for reporting back to the master thread
+volatile int got_it  = 0;
+volatile int t3ran   = 0;
+volatile int t3ended = 0;
+volatile int extras[4] = {0,0,0,0};
+    
+volatile int go_flag = 0; // but this one controls thread 3 from thread 2
+
+// ------------------------------------------------------------------------
+// 0 to 3 of these run generally to interfere with the other processing,
+// to cause multiple prio inheritances, and clashes in any orders.
+
+static void *extra_thread( void *arg )
+{
+#define XINFO( z ) \
+    do { z[13] = '0' + data; CYG_TEST_INFO( z ); } while ( 0 )
+
+    static char running[]  = "Extra thread Xa running";
+    static char exiting[]  = "Extra thread Xa exiting";
+    static char resumed[]  = "Extra thread Xa resumed";
+    static char locked[]   = "Extra thread Xa locked";
+    static char unlocked[] = "Extra thread Xa unlocked";
+
+    int id = (int)arg;
+    CYG_ADDRWORD data = thread_data[id];
+
+    CYG_ASSERT( (id >= 4 && id <= 6), "extra_thread invalid id" );
+    
+    // Emulate resume behaviour
+    sem_wait( &hold[id] );
+    if( all_exit ) return 0;
+    
+    XINFO( running );
+
+    sem_wait( &hold[id] );
+    
+    XINFO( resumed );
+
+    pthread_mutex_lock( &mutex );
+
+    XINFO( locked );
+
+    pthread_mutex_unlock( &mutex );    
+
+    XINFO( unlocked );
+
+    extras[ data ] ++;
+
+    XINFO( exiting );
+
+    return NULL;
+}
+
+// ------------------------------------------------------------------------
+
+static void *t1( void *arg )
+{
+    int id = (int)arg;
+    //CYG_ADDRWORD data = thread_data[id];
+    
+    // Emulate resume behaviour
+    sem_wait( &hold[id] );
+    if( all_exit ) return 0;
+
+    CYG_TEST_INFO( "Thread 1 running" );
+
+    sem_wait( &hold[id] );    
+
+    pthread_mutex_lock( &mutex );
+
+    got_it++;
+
+    CYG_TEST_CHECK( 0 == t3ended, "T3 ended prematurely [T1,1]" );
+
+    pthread_mutex_unlock( &mutex );
+
+    CYG_TEST_CHECK( 0 == t3ended, "T3 ended prematurely [T1,2]" );
+
+    // That's all.
+
+    CYG_TEST_INFO( "Thread 1 exit" );
+
+    return 0;    
+}
+
+// ------------------------------------------------------------------------
+
+static void *t2( void *arg )
+{
+    int i;
+    int id = (int)arg;
+    CYG_ADDRWORD data = thread_data[id];
+    cyg_tick_count_t now, then;
+    
+    // Emulate resume behaviour
+    sem_wait( &hold[id] );
+    if( all_exit ) return 0;
+
+    CYG_TEST_INFO( "Thread 2 running" );
+
+    CYG_TEST_CHECK( 0 == (data & ~0x77), "Bad T2 arg: extra bits" );
+    CYG_TEST_CHECK( 0 == (data & (data >> 4)), "Bad T2 arg: overlap" );
+
+    sem_wait( &hold[id] );
+
+    // depending on our config argument, optionally restart some of the
+    // extra threads to throw noise into the scheduler:
+    for ( i = 0; i < 3; i++ )
+        if ( (1 << i) & data )          // bits 0-2 control
+            sem_post( &hold[i+4] );     // made sure extras are thread[4-6]
+
+    // let those threads run
+    for( i = 0; i < DELAYFACTOR * 10; i++ )
+        nanosleep( &sleeptime, NULL );
+
+    cyg_scheduler_lock();               // do this next lot atomically
+
+    go_flag = 1;                        // unleash thread 3
+    sem_post( &hold[1] );               // resume thread 1
+
+    // depending on our config argument, optionally restart some of the
+    // extra threads to throw noise into the scheduler at this later point:
+    for ( i = 4; i < 7; i++ )
+        if ( (1 << i) & data )          // bits 4-6 control
+            sem_post( &hold[i] );       // made sure extras are thread[4-6]
+
+    cyg_scheduler_unlock();             // let scheduling proceed
+
+    // Need a delay (but not a CPU yield) to allow t3 to awaken and act on
+    // the go_flag, otherwise we check these details below too soon.
+    // Actually, waiting for the clock to tick a couple of times would be
+    // better, so that is what we will do.  Must be a busy-wait.
+    then = cyg_current_time();
+    do {
+        now = cyg_current_time();
+        // Wait longer than the delay in t3 waiting on go_flag
+    } while ( now < (then + 3) );
+
+#ifdef _POSIX_THREAD_PRIO_INHERIT
+    CYG_TEST_INFO( "Checking for mutex priority inheritance" );
+    CYG_TEST_CHECK( 1 == t3ran, "Thread 3 did not run" );
+    CYG_TEST_CHECK( 1 == got_it, "Thread 1 did not get the mutex" );
+#else
+    CYG_TEST_INFO( "Checking for NO mutex priority inheritance" );
+    CYG_TEST_CHECK( 0 == t3ran, "Thread 3 DID run" );
+    CYG_TEST_CHECK( 0 == got_it, "Thread 1 DID get the mutex" );
+#endif
+
+    CYG_TEST_CHECK( 0 == t3ended, "Thread 3 ended prematurely [T2,1]" );
+
+    for( i = 0; i < DELAYFACTOR * 20; i++ )    
+        nanosleep( &sleeptime, NULL );      // let those threads run  
+
+    CYG_TEST_CHECK( 1 == t3ran, "Thread 3 did not run" );
+    CYG_TEST_CHECK( 1 == got_it, "Thread 1 did not get the mutex" );
+    CYG_TEST_CHECK( 1 == t3ended, "Thread 3 has not ended" );
+
+    for ( i = 0; i < 3; i++ )
+        if ( (1 << i) & (data | data >> 4) ) // bits 0-2 and 4-6 control
+            CYG_TEST_CHECK( 1 == extras[i+1], "Extra thread did not run" );
+        else
+            CYG_TEST_CHECK( 0 == extras[i+1], "Extra thread ran" );
+
+    CYG_TEST_PASS( "Thread 2 exiting, AOK" );
+    // That's all: restart the control thread.
+    sem_post( &hold[0] );
+
+    return 0;    
+}
+
+// ------------------------------------------------------------------------
+
+static void *t3( void *arg )
+{
+    int i;
+    int id = (int)arg;
+    //CYG_ADDRWORD data = thread_data[id];
+    
+    // Emulate resume behaviour
+    sem_wait( &hold[id] );
+    if( all_exit ) return 0;
+    
+    CYG_TEST_INFO( "Thread 3 running" );
+
+    pthread_mutex_lock( &mutex );
+
+    for( i = 0; i < DELAYFACTOR * 5; i++ )    
+        nanosleep( &sleeptime, NULL );      // let thread 3a run
+
+    sem_post( &hold[2] );               // resume thread 2
+
+    while ( 0 == go_flag )
+        nanosleep( &sleeptime, NULL );  // wait until we are told to go
+
+    t3ran ++;                           // record the fact
+
+    CYG_TEST_CHECK( 0 == got_it, "Thread 1 claims to have got my mutex" );
+
+    pthread_mutex_unlock( &mutex );
+
+    t3ended ++;                         // record that we came back
+
+    CYG_TEST_CHECK( 1 == got_it, "Thread 1 did not get the mutex" );
+
+    CYG_TEST_INFO( "Thread 3 exit" );
+
+    return 0;
+}
+
+// ------------------------------------------------------------------------
+
+static void *control_thread( void *arg )
+{
+    int i,z;
+    int id = (int)arg;
+    //CYG_ADDRWORD data = thread_data[id];
+    
+    // Emulate resume behaviour
+    sem_wait( &hold[id] );
+    if( all_exit ) return 0;
+    
+    // one tick sleep time
+    sleeptime.tv_nsec = 10000000;
+    sleeptime.tv_sec = 0;
+    
+    CYG_TEST_INIT();
+    CYG_TEST_INFO( "Control Thread running" );
+
+    // Go through the 27 possibilitied of resuming the extra threads
+    //     0: not at all
+    //     1: early in the process
+    //     2: later on
+    // which are represented by bits 0-3 and 4-6 resp in the argument to
+    // thread 2 (none set means no resume at all).
+    for ( i = 0; i < 27; i++ ) {
+        static int xx[] = { 0, 1, 16 };
+        int j = i % 3;
+        int k = (i / 3) % 3;
+        int l = (i / 9) % 3;
+
+        int d = xx[j] | (xx[k]<<1) | (xx[l]<<2) ;
+
+        if ( cyg_test_is_simulator && (0 != i && 13 != i && 26 != i) )
+            continue;    // 13 is 111 base 3, 26 is 222 base 3
+
+#ifdef _POSIX_THREAD_PRIO_INHERIT
+        // If the simple scheme plus relay enhancement, or any other
+        // *complete* scheme, we can run all three ancillary threads no
+        // problem, so no special action here.
+
+#else
+        // If no priority inheritance at all, running threads 1a and 2a is
+        // OK, but not thread 3a; it blocks the world.
+        if ( l )                        // Cannot run thread 3a if no
+            break;                      //     priority inheritance at all.
+#endif
+
+        // Reinitialize mutex to provide priority inheritance
+        {
+            pthread_mutexattr_t attr;
+            pthread_mutexattr_init( &attr );
+            pthread_mutexattr_setprotocol( &attr, PTHREAD_PRIO_INHERIT );
+            pthread_mutex_init( &mutex, &attr );
+        }
+
+        got_it  = 0;
+        t3ran   = 0;
+        t3ended = 0;
+        for ( z = 0; z < 4; z++ ) extras[z] = 0;
+        go_flag = 0;
+        
+        new_thread( t1, 0, 15, 1 );            // Slot 1
+        new_thread( t2, d, 10, 1 );            // Slot 2
+        new_thread( t3, 0,  5, 1 );            // Slot 3
+        
+        new_thread( extra_thread, 1, 17, j );  // Slot 4
+        new_thread( extra_thread, 2, 12, k );  // Slot 5
+        new_thread( extra_thread, 3,  8, l );  // Slot 6
+        
+        {
+            static char *a[] = { "inactive", "run early", "run late" };
+            diag_printf( "\n----- [%2d] New Cycle: 0x%02x, Threads 1a %s, 2a %s, 3a %s -----\n",
+                         i, d,  a[j], a[k], a[l] );
+        }
+
+        sem_wait( &hold[0] );
+        
+        kill_threads();
+        pthread_mutex_destroy( &mutex );
+    }
+    CYG_TEST_EXIT( "Control Thread exit" );
+
+    return 0;
+}
+
+// ------------------------------------------------------------------------
+
+static sem_t main_sem;
+
+externC int
+main( int argc, char **argv )
+{ 
+    new_thread( control_thread, 0, 20, 1 );
+
+    // We have nothing for main to do here, so put it to sleep on
+    // its own semaphore. We cannot let it just exit since that
+    // will end the whole program.
+
+    sem_init( &main_sem, 0, 0 );
+    
+    for(;;) sem_wait( &main_sem );
+}
+
+// ------------------------------------------------------------------------
+// Documentation: enclosed is the design of this test.
+//
+// It has been carefully constructed so that it does NOT use other kernel
+// facilities (aside from delay-task) to test that priority inheritance is
+// working, or not, as intended by the configuration.
+//
+// These notes describe the flow of control in one run of the test with the
+// ancillary tasks optionally interspersed.  The details of how those extra
+// tasks are or are not allowed to run are not described.
+// 
+// 
+// 
+// The only change in the test that depends on whether there is inheritance or
+// not is the check in thread 2 on "3-ran" and "got it" flags marked ****
+// 
+// 
+// volatile &c booleans:
+//         "got it"     = FALSE
+//         "3-ran"      = FALSE
+//         "3-ended"    = FALSE
+//         "extras"[3]  = FALSE
+// 
+// thread 1.  prio 5, self-suspend.
+// 
+// thread 1a, prio 8, self-suspend.
+// 
+// thread 2.  prio 10, self-suspend.
+// 
+// thread 2a, prio 12, self-suspend.
+// 
+// thread 3.  prio 15, runs, lock mutex, resume(2)
+// 
+// thread 3a, prio 17, self-suspend.
+// 
+//        2.  runs,
+//        2.  resume(3a) +++OPTIONAL
+//        2.  resume(2a) +++OPTIONAL
+//        2.  resume(1a) +++OPTIONAL
+//        [1a lock-fail]       thread 3->prio := 8
+// 
+//        [3. runs maybe, does the looping thing]
+// 
+//        2.  sleep a while...
+// 
+//        [2a lock-fail]       thread 3->prio := 12
+// 
+//        [3. runs maybe, does the looping thing]
+// 
+//        [3a lock-fail]   thread 3->prio unchanged
+// 
+//        [3. runs maybe, does the looping thing]
+// 
+//        2.  lock scheduler
+//        2.  set "go-flag"
+//        2.  resume(1)
+//        2.  resume(1a) +++OPTIONAL
+//        2.  resume(2a) +++OPTIONAL
+//        2.  resume(3a) +++OPTIONAL
+//        2.  unlock scheduler
+// 
+//        1.  runs, lock mutex - thread 3 has it locked
+//
+//        2.  busy-waits a bit for thread 3 to come out of its delay() loop.
+//            This must be a *busy*wait so that 3 can only run via the
+//            inherited raised priority.
+// 
+//        [xa. all do the same: lock mutex,                ]
+//        [xa. unlock mutex                                ]
+//        [xa. set a flag "extras"[x] to say we are done.  ]
+//        [xa. exit                                        ]
+// 
+// 
+// 
+// INHERIT
+// -------
+// 
+//                 thread 3->prio := 5
+// 
+//        3.  runs,
+//        3.  set a flag to say "3-ran",
+//        3.  loop with a sleep(1) until "go-flag" is set.
+//        3.  check "got it" is false,
+//        3.  then unlock mutex,
+// 
+//                 thread 3->prio := 15
+// 
+//        1.  runs, set a flag to say "got it",
+//        1.  check "3-ended" flag is false
+//        1.  unlock mutex,
+//        1.  check "3-ended" flag is still false
+//        1.  exit.
+// 
+//        [1a locks, unlocks, exits]
+// 
+//        2.  runs, check "3-ran" and "got it" flags are TRUE ****
+//        2.  check "3-ended" flag is false
+//        2.  sleeps for a while so that...
+// 
+//        [2a locks, unlocks, exits]
+//            
+//        3.  runs, set "3-ended" flag,
+//        3.  check "3-ran" and "got it" flags
+//        3.  exit
+// 
+//        [3a locks, unlocks, exits]
+// 
+//        2.  awakens, checks all flags true,
+//        2.  check that all "extra" threads that we started have indeed run
+//        2.  end of test.
+// 
+// 
+// 
+// 
+// NO-INHERIT
+// ----------
+//                 thread 1 is waiting on the mutex
+// 
+//        [1a lock-fail]
+// 
+//        2.  runs, checks that "3-ran" and "got it" flags are FALSE ****
+//        2.  check "3-ended" flag is false
+//        2.  sleeps for a while so that...
+// 
+//        [2a. lock-fail]
+//            
+//        3.  runs, set a flag to say "3-ran",
+//        3.  check "got it" is false,
+//        3.  then unlock mutex,
+// 
+//        1.  runs, set a flag to say "got it",
+//        1.  check "3-ended" flag is false
+//        1.  unlock mutex,
+//        1.  check "3-ended" flag is still false
+//        1.  exit.
+// 
+//        [1a locks, unlocks, exits]
+//        [2a locks, unlocks, exits]
+// 
+//        3.  runs, set "3-ended" flag,
+//        3.  check "3-ran" and "got it" flags
+//        3.  exit
+// 
+//        [3a locks, unlocks, exits]
+//                
+//        2.  awakens, checks all flags true, 
+//        2.  check that all "extra" threads that we started have indeed run
+//        2.  end of test.
+// 
+// 
+// (the end)
+// 
+// 
+// ------------------------------------------------------------------------
+
+#endif
+
+// EOF pmutex3.c
diff --git a/packages/compat/posix/v2_0/tests/tm_posix.cxx b/packages/compat/posix/v2_0/tests/tm_posix.cxx
new file mode 100644 (file)
index 0000000..34154e2
--- /dev/null
@@ -0,0 +1,1714 @@
+//==========================================================================
+//
+//        tm_posix.cxx
+//
+//        Basic timing test / scaffolding
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
+// Copyright (C) 2002 Jonathan Larmour
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
+// at http://sources.redhat.com/ecos/ecos-license/
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):     gthomas,nickg
+// Contributors:  jlarmour
+// Date:          1998-10-19
+// Description:   Very simple kernel timing test
+//####DESCRIPTIONEND####
+//==========================================================================
+
+
+#include <cyg/infra/testcase.h>
+#include <cyg/infra/diag.h>
+#include <pkgconf/posix.h>
+#include <pkgconf/system.h>
+#ifdef CYGPKG_KERNEL
+#include <pkgconf/kernel.h>
+#endif
+
+#ifndef CYGPKG_POSIX_SIGNALS
+#define NA_MSG "No POSIX signals"
+#elif !defined(CYGPKG_POSIX_TIMERS)
+#define NA_MSG "No POSIX timers"
+#elif !defined(CYGPKG_POSIX_PTHREAD)
+#define NA_MSG "POSIX threads not enabled"
+#elif !defined(CYGFUN_KERNEL_API_C)
+#define NA_MSG "Kernel C API not enabled"
+#elif !defined(CYGSEM_KERNEL_SCHED_MLQUEUE)
+#define NA_MSG "Kernel mlqueue scheduler not enabled"
+#elif !defined(CYGVAR_KERNEL_COUNTERS_CLOCK)
+#define NA_MSG "Kernel clock not enabled"
+#elif CYGNUM_KERNEL_SCHED_PRIORITIES <= 12
+#define NA_MSG "Kernel scheduler properties <= 12"
+#elif !defined(CYGPKG_POSIX_SEMAPHORES)
+#define NA_MSG "POSIX semaphores not enabled"
+#endif
+
+//==========================================================================
+
+#ifdef NA_MSG
+extern "C" void
+cyg_start(void)
+{
+    CYG_TEST_INIT();
+    CYG_TEST_NA(NA_MSG);
+}
+#else
+
+#include <pkgconf/kernel.h>
+#include <pkgconf/hal.h>
+
+#include <cyg/kernel/sched.hxx>
+#include <cyg/kernel/thread.hxx>
+#include <cyg/kernel/thread.inl>
+#include <cyg/kernel/mutex.hxx>
+#include <cyg/kernel/sema.hxx>
+#include <cyg/kernel/sched.inl>
+#include <cyg/kernel/clock.hxx>
+#include <cyg/kernel/clock.inl>
+#include <cyg/kernel/kapi.h>
+
+#include <cyg/infra/testcase.h>
+
+#include <cyg/kernel/test/stackmon.h>
+#include CYGHWR_MEMORY_LAYOUT_H
+
+
+// POSIX headers
+
+#include <sys/types.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <time.h>
+#include <signal.h>
+#include <errno.h>
+
+//==========================================================================
+// Define this to see the statistics with the first sample datum removed.
+// This can expose the effects of caches on the speed of operations.
+
+#undef STATS_WITHOUT_FIRST_SAMPLE
+
+//==========================================================================
+
+// Structure used to keep track of times
+typedef struct fun_times {
+    cyg_uint32 start;
+    cyg_uint32 end;
+} fun_times;
+
+//==========================================================================
+
+#define STACK_SIZE (PTHREAD_STACK_MIN*2)
+
+// Defaults
+#define NTEST_THREADS    16
+#define NMUTEXES         32
+#define NMBOXES          32
+#define NSEMAPHORES      32
+#define NTIMERS          32
+
+
+#define NSAMPLES         32
+#define NTHREAD_SWITCHES 128
+#define NSCHEDS          128
+
+#define NSAMPLES_SIM         2
+#define NTEST_THREADS_SIM    2
+#define NTHREAD_SWITCHES_SIM 4
+#define NMUTEXES_SIM         2
+#define NMBOXES_SIM          2
+#define NSEMAPHORES_SIM      2
+#define NSCHEDS_SIM          4
+#define NTIMERS_SIM          2
+
+//==========================================================================
+
+static int nsamples;
+static int ntest_threads;
+static int nthread_switches;
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+static int nmutexes;
+#endif
+static int nmboxes;
+static int nsemaphores;
+static int nscheds;
+static int ntimers;
+
+static char stacks[NTEST_THREADS][STACK_SIZE];
+static pthread_t threads[NTEST_THREADS];
+static int overhead;
+static sem_t synchro;
+static fun_times thread_ft[NTEST_THREADS];
+
+static fun_times test2_ft[NTHREAD_SWITCHES];
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+static pthread_mutex_t test_mutexes[NMUTEXES];
+static fun_times mutex_ft[NMUTEXES];
+static pthread_t mutex_test_thread_handle;
+#endif
+#if 0
+static cyg_mbox test_mboxes[NMBOXES];
+static cyg_handle_t test_mbox_handles[NMBOXES];
+static fun_times mbox_ft[NMBOXES];
+static cyg_thread mbox_test_thread;
+static cyg_handle_t mbox_test_thread_handle;
+#endif
+
+static sem_t test_semaphores[NSEMAPHORES];
+static fun_times semaphore_ft[NSEMAPHORES];
+static pthread_t semaphore_test_thread_handle;
+
+static fun_times sched_ft[NSCHEDS];
+
+static timer_t timers[NTIMERS];
+static fun_times timer_ft[NTIMERS];
+
+static long rtc_resolution[] = CYGNUM_KERNEL_COUNTERS_RTC_RESOLUTION;
+static long ns_per_system_clock;
+
+#if defined(CYGVAR_KERNEL_COUNTERS_CLOCK_LATENCY)
+// Data kept by kernel real time clock measuring clock interrupt latency
+extern cyg_tick_count total_clock_latency, total_clock_interrupts;
+extern cyg_int32 min_clock_latency, max_clock_latency;
+extern bool measure_clock_latency;
+#endif
+
+#if defined(CYGVAR_KERNEL_COUNTERS_CLOCK_DSR_LATENCY)
+extern cyg_tick_count total_clock_dsr_latency, total_clock_dsr_calls;
+extern cyg_int32 min_clock_dsr_latency, max_clock_dsr_latency;
+extern bool measure_clock_latency;
+#endif
+
+//==========================================================================
+
+void run_sched_tests(void);
+void run_thread_tests(void);
+void run_thread_switch_test(void);
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+void run_mutex_tests(void);
+void run_mutex_circuit_test(void);
+#endif
+void run_mbox_tests(void);
+void run_mbox_circuit_test(void);
+void run_semaphore_tests(void);
+void run_semaphore_circuit_test(void);
+void run_timer_tests(void);
+
+//==========================================================================
+
+#ifndef max
+#define max(n,m) (m > n ? n : m)
+#endif
+
+//==========================================================================
+// Wait until a clock tick [real time clock] has passed.  This should keep it
+// from happening again during a measurement, thus minimizing any fluctuations
+void
+wait_for_tick(void)
+{
+    cyg_tick_count_t tv0, tv1;
+    tv0 = cyg_current_time();
+    while (true) {
+        tv1 = cyg_current_time();
+        if (tv1 != tv0) break;
+    }
+}
+
+//--------------------------------------------------------------------------
+// Display a number of ticks as microseconds
+// Note: for improved calculation significance, values are kept in ticks*1000
+void
+show_ticks_in_us(cyg_uint32 ticks)
+{
+    long long ns;
+    ns = (ns_per_system_clock * (long long)ticks) / CYGNUM_KERNEL_COUNTERS_RTC_PERIOD;
+    ns += 5;  // for rounding to .01us
+    diag_printf("%5d.%02d", (int)(ns/1000), (int)((ns%1000)/10));
+}
+
+//--------------------------------------------------------------------------
+//
+// If the kernel is instrumented to measure clock interrupt latency, these
+// measurements can be drastically perturbed by printing via "diag_printf()"
+// since that code may run with interrupts disabled for long periods.
+//
+// In order to get accurate/reasonable latency figures _for the kernel 
+// primitive functions beint tested_, the kernel's latency measurements
+// are suspended while the printing actually takes place.
+//
+// The measurements are reenabled after the printing, thus allowing for
+// fair measurements of the kernel primitives, which are not distorted
+// by the printing mechanisms.
+
+#if defined(CYGVAR_KERNEL_COUNTERS_CLOCK_LATENCY) && defined(HAL_CLOCK_LATENCY)
+void
+disable_clock_latency_measurement(void)
+{
+    wait_for_tick();
+    measure_clock_latency = false;
+}
+
+void
+enable_clock_latency_measurement(void)
+{
+    wait_for_tick();
+    measure_clock_latency = true;
+}
+
+// Ensure that the measurements are reasonable (no startup anomalies)
+void
+reset_clock_latency_measurement(void)
+{
+  disable_clock_latency_measurement();
+  total_clock_latency = 0;
+  total_clock_interrupts = 0;
+  min_clock_latency = 0x7FFFFFFF;
+  max_clock_latency = 0;
+#if defined(CYGVAR_KERNEL_COUNTERS_CLOCK_DSR_LATENCY)  
+  total_clock_dsr_latency = 0;
+  total_clock_dsr_calls = 0;
+  min_clock_dsr_latency = 0x7FFFFFFF;
+  max_clock_dsr_latency = 0;
+#endif  
+  enable_clock_latency_measurement();
+  
+}
+#else
+#define disable_clock_latency_measurement()
+#define enable_clock_latency_measurement()
+#define reset_clock_latency_measurement()
+#endif
+
+//--------------------------------------------------------------------------
+
+void
+show_times_hdr(void)
+{
+    disable_clock_latency_measurement();
+    diag_printf("\n");
+    diag_printf("                                 Confidence\n");
+    diag_printf("     Ave     Min     Max     Var  Ave  Min  Function\n");
+    diag_printf("  ======  ======  ======  ====== ========== ========\n");
+    enable_clock_latency_measurement();
+}
+
+void
+show_times_detail(fun_times ft[], int nsamples, char *title, bool ignore_first)
+{
+    int i, delta, min, max, con_ave, con_min, ave_dev;
+    int start_sample, total_samples;   
+    cyg_int32 total, ave;
+
+    if (ignore_first) {
+        start_sample = 1;
+        total_samples = nsamples-1;
+    } else {
+        start_sample = 0;
+        total_samples = nsamples;
+    }
+    total = 0;
+    min = 0x7FFFFFFF;
+    max = 0;
+    for (i = start_sample;  i < nsamples;  i++) {
+        if (ft[i].end < ft[i].start) {
+            // Clock wrapped around (timer tick)
+            delta = (ft[i].end+CYGNUM_KERNEL_COUNTERS_RTC_PERIOD) - ft[i].start;
+        } else {
+            delta = ft[i].end - ft[i].start;
+        }
+        delta -= overhead;
+        if (delta < 0) delta = 0;
+        delta *= 1000;
+        total += delta;
+        if (delta < min) min = delta;
+        if (delta > max) max = delta;
+    }
+    ave = total / total_samples;
+    total = 0;
+    ave_dev = 0;
+    for (i = start_sample;  i < nsamples;  i++) {
+        if (ft[i].end < ft[i].start) {
+            // Clock wrapped around (timer tick)
+            delta = (ft[i].end+CYGNUM_KERNEL_COUNTERS_RTC_PERIOD) - ft[i].start;
+        } else {
+            delta = ft[i].end - ft[i].start;
+        }
+        delta -= overhead;
+        if (delta < 0) delta = 0;
+        delta *= 1000;
+        delta = delta - ave;
+        if (delta < 0) delta = -delta;
+        ave_dev += delta;
+    }
+    ave_dev /= total_samples;
+    con_ave = 0;
+    con_min = 0;
+    for (i = start_sample;  i < nsamples;  i++) {
+        if (ft[i].end < ft[i].start) {
+            // Clock wrapped around (timer tick)
+            delta = (ft[i].end+CYGNUM_KERNEL_COUNTERS_RTC_PERIOD) - ft[i].start;
+        } else {
+            delta = ft[i].end - ft[i].start;
+        }
+        delta -= overhead;
+        if (delta < 0) delta = 0;
+        delta *= 1000;
+        if ((delta <= (ave+ave_dev)) && (delta >= (ave-ave_dev))) con_ave++;
+        if ((delta <= (min+ave_dev)) && (delta >= (min-ave_dev))) con_min++;
+    }
+    con_ave = (con_ave * 100) / total_samples;
+    con_min = (con_min * 100) / total_samples;
+    show_ticks_in_us(ave);
+    show_ticks_in_us(min);
+    show_ticks_in_us(max);
+    show_ticks_in_us(ave_dev);
+    disable_clock_latency_measurement();
+    diag_printf("  %3d%% %3d%%", con_ave, con_min);
+    diag_printf(" %s\n", title);
+    enable_clock_latency_measurement();
+}
+
+void
+show_times(fun_times ft[], int nsamples, char *title)
+{
+    show_times_detail(ft, nsamples, title, false);
+#ifdef STATS_WITHOUT_FIRST_SAMPLE
+    show_times_detail(ft, nsamples, "", true);
+#endif
+}
+
+//--------------------------------------------------------------------------
+
+void
+show_test_parameters(void)
+{
+    disable_clock_latency_measurement();
+    diag_printf("\nTesting parameters:\n");
+    diag_printf("   Clock samples:         %5d\n", nsamples);
+    diag_printf("   Threads:               %5d\n", ntest_threads);
+    diag_printf("   Thread switches:       %5d\n", nthread_switches);
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+    diag_printf("   Mutexes:               %5d\n", nmutexes);
+#endif
+    diag_printf("   Mailboxes:             %5d\n", nmboxes);
+    diag_printf("   Semaphores:            %5d\n", nsemaphores);
+    diag_printf("   Scheduler operations:  %5d\n", nscheds);
+    diag_printf("   Timers:                %5d\n", ntimers);
+    diag_printf("\n"); 
+    enable_clock_latency_measurement();
+}
+
+void
+end_of_test_group(void)
+{
+    disable_clock_latency_measurement();
+    diag_printf("\n"); 
+    enable_clock_latency_measurement();
+}
+
+//--------------------------------------------------------------------------
+// Compute a name for a thread
+
+char *
+thread_name(char *basename, int indx) {
+    return "<<NULL>>";  // Not currently used
+}
+
+//--------------------------------------------------------------------------
+// test0 - null test, just return
+
+void *
+test0(void *indx)
+{
+    return indx;
+}
+
+//--------------------------------------------------------------------------
+// test3 - loop, yeilding repeatedly and checking for cancellation
+
+void *
+test3(void *indx)
+{
+    for(;;)
+    {
+        sched_yield();
+        pthread_testcancel();
+    }
+    
+    return indx;
+}
+
+//--------------------------------------------------------------------------
+// test1 - empty test, simply exit.  Last thread signals parent.
+
+void *
+test1( void *indx)
+{
+    if ((cyg_uint32)indx == (cyg_uint32)(ntest_threads-1)) {
+        sem_post(&synchro);  // Signal that last thread is dying
+    }
+    return indx;
+}
+
+//--------------------------------------------------------------------------
+// test2 - measure thread switch times
+
+void *
+test2(void *indx)
+{
+    int i;
+    for (i = 0;  i < nthread_switches;  i++) {
+        if ((int)indx == 0) {
+            HAL_CLOCK_READ(&test2_ft[i].start);
+        } else {
+            HAL_CLOCK_READ(&test2_ft[i].end);
+        }
+        sched_yield();
+    }
+    if ((int)indx == 1) {
+        sem_post(&synchro);
+    }
+
+    return indx;
+}
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+//--------------------------------------------------------------------------
+// Full-circuit mutex unlock/lock test
+
+void *
+mutex_test(void * indx)
+{
+    int i;
+    pthread_mutex_lock(&test_mutexes[0]);
+    for (i = 0;  i < nmutexes;  i++) {
+        sem_wait(&synchro);
+        wait_for_tick(); // Wait until the next clock tick to minimize aberations
+        HAL_CLOCK_READ(&mutex_ft[i].start);
+        pthread_mutex_unlock(&test_mutexes[0]);
+        pthread_mutex_lock(&test_mutexes[0]);
+        sem_post(&synchro);
+    }
+    return indx;
+}
+
+//--------------------------------------------------------------------------
+// Full-circuit mbox put/get test
+
+#if 0
+void
+mbox_test(cyg_uint32 indx)
+{
+    void *item;
+    do {
+        item = cyg_mbox_get(test_mbox_handles[0]);
+        HAL_CLOCK_READ(&mbox_ft[(int)item].end);
+        cyg_semaphore_post(&synchro);
+    } while ((int)item != (nmboxes-1));
+    cyg_thread_exit(0);
+}
+#endif
+#endif
+//--------------------------------------------------------------------------
+// Full-circuit semaphore post/wait test
+
+void *
+semaphore_test(void * indx)
+{
+    int i;
+    for (i = 0;  i < nsemaphores;  i++) {
+        sem_wait(&test_semaphores[0]);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+        sem_post(&synchro);
+    }
+    return indx;
+}
+
+//--------------------------------------------------------------------------
+//
+// This set of tests is used to measure kernel primitives that deal with threads
+//
+
+void
+run_thread_tests(void)
+{
+
+    
+    int i;
+    struct sched_param schedparam;
+    pthread_attr_t attr;
+    int policy;
+    void *retval;
+    
+    // Set my priority higher than any I plan to create
+    schedparam.sched_priority = 30;
+    pthread_setschedparam( pthread_self(), SCHED_RR, &schedparam );
+
+    // Initiaize thread creation attributes
+
+    pthread_attr_init( &attr );
+    pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
+    pthread_attr_setschedpolicy( &attr, SCHED_RR );
+    schedparam.sched_priority = 10;
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+
+        pthread_attr_setstackaddr( &attr, &stacks[i][STACK_SIZE] );
+        pthread_attr_setstacksize( &attr, STACK_SIZE );
+        pthread_create( &threads[i],
+                        &attr,
+                        test0,
+                        (void *)i
+                        );
+        
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Create thread");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+        sched_yield();
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Yield thread [all lower priority]");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+
+        schedparam.sched_priority = 11;
+        pthread_attr_setschedparam( &attr, &schedparam );
+        pthread_setschedparam(threads[i], SCHED_RR, &schedparam);
+
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Set priority");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+        pthread_getschedparam( threads[i], &policy, &schedparam );
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Get priority");
+
+    cyg_thread_delay(1);        // Let the test threads run
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+        pthread_join(threads[i], &retval);
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Join exited thread");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+        sched_yield();
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Yield [no other] thread");
+
+    
+    // Recreate the test set
+
+    schedparam.sched_priority = 10;
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    for (i = 0;  i < ntest_threads;  i++) {
+        pthread_attr_setstackaddr( &attr, &stacks[i][STACK_SIZE] );
+        pthread_attr_setstacksize( &attr, STACK_SIZE );
+        pthread_create( &threads[i],
+                        &attr,
+                        test3,
+                        (void *)i
+                        );
+    }
+
+    cyg_thread_delay(1);        // Let the test threads run    
+    
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+        pthread_cancel(threads[i]);
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Cancel [running] thread");
+
+    cyg_thread_delay(1);        // Let the test threads do their cancellations
+    
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+        pthread_join(threads[i], &retval);
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Join [cancelled] thread");
+
+    
+    // Set my priority lower than any I plan to create
+    schedparam.sched_priority = 5;
+    pthread_setschedparam( pthread_self(), SCHED_RR, &schedparam );
+    
+    // Set up the end-of-threads synchronizer
+    sem_init(&synchro, 0, 0);
+
+    schedparam.sched_priority = 10;
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntest_threads;  i++) {
+        HAL_CLOCK_READ(&thread_ft[i].start);
+
+        pthread_attr_setstackaddr( &attr, &stacks[i][STACK_SIZE] );
+        pthread_attr_setstacksize( &attr, STACK_SIZE );
+        pthread_create( &threads[i],
+                        &attr,
+                        test2,
+                        (void *)i
+                        );
+        
+        HAL_CLOCK_READ(&thread_ft[i].end);
+    }
+    show_times(thread_ft, ntest_threads, "Create [high priority] thread");
+
+    sem_wait(&synchro);  // Wait for all threads to finish
+
+    // Make sure they are all dead
+    for (i = 0;  i < ntest_threads;  i++) {
+        pthread_join(threads[i], &retval);
+    }
+
+    run_thread_switch_test();
+    end_of_test_group();
+
+}
+
+//--------------------------------------------------------------------------
+
+void
+run_thread_switch_test(void)
+{
+
+    int i;
+    struct sched_param schedparam;
+    pthread_attr_t attr;
+    void *retval;
+
+    // Set my priority higher than any I plan to create
+    schedparam.sched_priority = 30;
+    pthread_setschedparam( pthread_self(), SCHED_RR, &schedparam );
+
+    // Initiaize thread creation attributes
+
+    pthread_attr_init( &attr );
+    pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
+    pthread_attr_setschedpolicy( &attr, SCHED_RR );
+    schedparam.sched_priority = 10;
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    // Set up the end-of-threads synchronizer
+
+    sem_init(&synchro, 0, 0);
+        
+    // Set up for thread context switch 
+
+    for (i = 0;  i < 2;  i++) {
+        pthread_attr_setstackaddr( &attr, &stacks[i][STACK_SIZE] );
+        pthread_attr_setstacksize( &attr, STACK_SIZE );
+        pthread_create( &threads[i],
+                        &attr,
+                        test2,
+                        (void *)i
+                        );
+    }
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations    
+    
+    sem_wait(&synchro);
+
+    show_times(test2_ft, nthread_switches, "Thread switch");
+
+    // Clean up
+    for (i = 0;  i < 2;  i++) {
+        pthread_join(threads[i], &retval);
+    }
+
+}
+
+
+//--------------------------------------------------------------------------
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+void
+run_mutex_tests(void)
+{
+
+    int i;
+    pthread_mutexattr_t attr;
+
+    pthread_mutexattr_init( &attr );
+    
+    // Mutex primitives
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmutexes;  i++) {
+        HAL_CLOCK_READ(&mutex_ft[i].start);
+        pthread_mutex_init(&test_mutexes[i], &attr);
+        HAL_CLOCK_READ(&mutex_ft[i].end);
+    }
+    show_times(mutex_ft, nmutexes, "Init mutex");
+
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmutexes;  i++) {
+        HAL_CLOCK_READ(&mutex_ft[i].start);
+        pthread_mutex_lock(&test_mutexes[i]);
+        HAL_CLOCK_READ(&mutex_ft[i].end);
+    }
+    show_times(mutex_ft, nmutexes, "Lock [unlocked] mutex");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmutexes;  i++) {
+        HAL_CLOCK_READ(&mutex_ft[i].start);
+        pthread_mutex_unlock(&test_mutexes[i]);
+        HAL_CLOCK_READ(&mutex_ft[i].end);
+    }
+    show_times(mutex_ft, nmutexes, "Unlock [locked] mutex");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmutexes;  i++) {
+        HAL_CLOCK_READ(&mutex_ft[i].start);
+        pthread_mutex_trylock(&test_mutexes[i]);
+        HAL_CLOCK_READ(&mutex_ft[i].end);
+    }
+    show_times(mutex_ft, nmutexes, "Trylock [unlocked] mutex");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmutexes;  i++) {
+        HAL_CLOCK_READ(&mutex_ft[i].start);
+        pthread_mutex_trylock(&test_mutexes[i]);
+        HAL_CLOCK_READ(&mutex_ft[i].end);
+    }
+    show_times(mutex_ft, nmutexes, "Trylock [locked] mutex");
+
+    // Must unlock mutices before destroying them.
+    for (i = 0;  i < nmutexes;  i++) {
+        pthread_mutex_unlock(&test_mutexes[i]);
+    }
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmutexes;  i++) {
+        HAL_CLOCK_READ(&mutex_ft[i].start);
+        pthread_mutex_destroy(&test_mutexes[i]);
+        HAL_CLOCK_READ(&mutex_ft[i].end);
+    }
+    show_times(mutex_ft, nmutexes, "Destroy mutex");
+
+
+    run_mutex_circuit_test();
+    end_of_test_group();
+}
+
+//--------------------------------------------------------------------------
+
+void
+run_mutex_circuit_test(void)
+{
+    int i;
+    pthread_mutexattr_t mattr;
+    struct sched_param schedparam;
+    pthread_attr_t attr;
+    void *retval;
+
+    // Set my priority lower than any I plan to create
+    schedparam.sched_priority = 5;
+    pthread_setschedparam( pthread_self(), SCHED_RR, &schedparam );
+
+    // Initiaize thread creation attributes
+
+    pthread_attr_init( &attr );
+    pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
+    pthread_attr_setschedpolicy( &attr, SCHED_RR );
+    schedparam.sched_priority = 10;
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    // Set up for full mutex unlock/lock test
+    pthread_mutexattr_init( &mattr );    
+    pthread_mutex_init(&test_mutexes[0], &mattr);
+    sem_init(&synchro, 0, 0);
+
+    pthread_attr_setstackaddr( &attr, &stacks[0][STACK_SIZE] );
+    pthread_attr_setstacksize( &attr, STACK_SIZE );
+    pthread_create( &mutex_test_thread_handle,
+                    &attr,
+                    mutex_test,
+                    (void *)0
+        );
+    
+    // Need to raise priority so that this thread will block on the "lock"
+    schedparam.sched_priority = 20;
+    pthread_setschedparam( pthread_self(), SCHED_RR, &schedparam );
+    
+    for (i = 0;  i < nmutexes;  i++) {
+        sem_post(&synchro);
+        pthread_mutex_lock(&test_mutexes[0]);
+        HAL_CLOCK_READ(&mutex_ft[i].end);
+        pthread_mutex_unlock(&test_mutexes[0]);
+        sem_wait(&synchro);
+    }
+    pthread_join(mutex_test_thread_handle, &retval);
+    show_times(mutex_ft, nmutexes, "Unlock/Lock mutex");
+
+}
+
+#endif
+//--------------------------------------------------------------------------
+// Message queue tests
+
+// Currently disabled, pending implementation of POSIX message queues
+
+#if 0
+void
+run_mbox_tests(void)
+{
+    int i, cnt;
+    void *item;
+    // Mailbox primitives
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_create(&test_mbox_handles[i], &test_mboxes[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Create mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cnt = cyg_mbox_peek(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Peek [empty] mbox");
+
+#ifdef CYGMFN_KERNEL_SYNCH_MBOXT_PUT_CAN_WAIT
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_put(test_mbox_handles[i], (void *)i);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Put [first] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cnt = cyg_mbox_peek(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Peek [1 msg] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_put(test_mbox_handles[i], (void *)i);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Put [second] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cnt = cyg_mbox_peek(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Peek [2 msgs] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        item = cyg_mbox_get(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Get [first] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        item = cyg_mbox_get(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Get [second] mbox");
+#endif // ifdef CYGMFN_KERNEL_SYNCH_MBOXT_PUT_CAN_WAIT
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_tryput(test_mbox_handles[i], (void *)i);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Tryput [first] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        item = cyg_mbox_peek_item(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Peek item [non-empty] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        item = cyg_mbox_tryget(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Tryget [non-empty] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        item = cyg_mbox_peek_item(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Peek item [empty] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        item = cyg_mbox_tryget(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Tryget [empty] mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_waiting_to_get(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Waiting to get mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_waiting_to_put(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Waiting to put mbox");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nmboxes;  i++) {
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_delete(test_mbox_handles[i]);
+        HAL_CLOCK_READ(&mbox_ft[i].end);
+    }
+    show_times(mbox_ft, nmboxes, "Delete mbox");
+
+    run_mbox_circuit_test();
+    end_of_test_group();
+}
+
+//--------------------------------------------------------------------------
+
+void
+run_mbox_circuit_test(void)
+{
+#ifdef CYGMFN_KERNEL_SYNCH_MBOXT_PUT_CAN_WAIT
+    int i;
+    // Set my priority lower than any I plan to create
+    cyg_thread_set_priority(cyg_thread_self(), 3);
+    // Set up for full mbox put/get test
+    cyg_mbox_create(&test_mbox_handles[0], &test_mboxes[0]);
+    cyg_semaphore_init(&synchro, 0);
+    cyg_thread_create(2,              // Priority - just a number
+                      mbox_test,           // entry
+                      0,               // index
+                      thread_name("thread", 0),     // Name
+                      &stacks[0][0],   // Stack
+                      STACK_SIZE,      // Size
+                      &mbox_test_thread_handle,   // Handle
+                      &mbox_test_thread    // Thread data structure
+        );
+    cyg_thread_resume(mbox_test_thread_handle);
+    for (i = 0;  i < nmboxes;  i++) {
+        wait_for_tick(); // Wait until the next clock tick to minimize aberations
+        HAL_CLOCK_READ(&mbox_ft[i].start);
+        cyg_mbox_put(test_mbox_handles[0], (void *)i);
+        cyg_semaphore_wait(&synchro);
+    }
+    cyg_thread_delete(mbox_test_thread_handle);
+    show_times(mbox_ft, nmboxes, "Put/Get mbox");
+#endif
+}
+
+#endif
+
+//--------------------------------------------------------------------------
+
+void
+run_semaphore_tests(void)
+{
+
+    int i;
+    int sem_val;
+
+    // Semaphore primitives
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nsemaphores;  i++) {
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_init(&test_semaphores[i], 0, 0);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+    }
+    show_times(semaphore_ft, nsemaphores, "Init semaphore");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nsemaphores;  i++) {
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_post(&test_semaphores[i]);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+    }
+    show_times(semaphore_ft, nsemaphores, "Post [0] semaphore");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nsemaphores;  i++) {
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_wait(&test_semaphores[i]);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+    }
+    show_times(semaphore_ft, nsemaphores, "Wait [1] semaphore");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nsemaphores;  i++) {
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_trywait(&test_semaphores[i]);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+    }
+    show_times(semaphore_ft, nsemaphores, "Trywait [0] semaphore");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nsemaphores;  i++) {
+        sem_post(&test_semaphores[i]);
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_trywait(&test_semaphores[i]);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+    }
+    show_times(semaphore_ft, nsemaphores, "Trywait [1] semaphore");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nsemaphores;  i++) {
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_getvalue(&test_semaphores[i], &sem_val);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+    }
+    show_times(semaphore_ft, nsemaphores, "Get value of semaphore");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < nsemaphores;  i++) {
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_destroy(&test_semaphores[i]);
+        HAL_CLOCK_READ(&semaphore_ft[i].end);
+    }
+    show_times(semaphore_ft, nsemaphores, "Destroy semaphore");
+
+    run_semaphore_circuit_test();
+    end_of_test_group();
+}
+
+//--------------------------------------------------------------------------
+
+void
+run_semaphore_circuit_test(void)
+{
+
+    int i;
+    struct sched_param schedparam;
+    pthread_attr_t attr;
+    void *retval;
+
+    // Set my priority lower than any I plan to create
+    schedparam.sched_priority = 5;
+    pthread_setschedparam( pthread_self(), SCHED_RR, &schedparam );
+
+    // Initiaize thread creation attributes
+
+    pthread_attr_init( &attr );
+    pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
+    pthread_attr_setschedpolicy( &attr, SCHED_RR );
+    schedparam.sched_priority = 10;
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    // Set up for full semaphore post/wait test
+    sem_init(&test_semaphores[0], 0, 0);
+    sem_init(&synchro, 0, 0);
+
+    pthread_attr_setstackaddr( &attr, &stacks[0][STACK_SIZE] );
+    pthread_attr_setstacksize( &attr, STACK_SIZE );
+    pthread_create( &semaphore_test_thread_handle,
+                    &attr,
+                    semaphore_test,
+                    (void *)0
+        );
+    
+    
+    for (i = 0;  i < nsemaphores;  i++) {
+        wait_for_tick(); // Wait until the next clock tick to minimize aberations
+        HAL_CLOCK_READ(&semaphore_ft[i].start);
+        sem_post(&test_semaphores[0]);
+        sem_wait(&synchro);
+    }
+    pthread_join(semaphore_test_thread_handle, &retval);
+    
+    show_times(semaphore_ft, nsemaphores, "Post/Wait semaphore");
+
+
+}
+
+//--------------------------------------------------------------------------
+
+// Timer callback function
+void
+sigrt0(int signo, siginfo_t *info, void *context)
+{
+    diag_printf("sigrt0 called\n");
+    // empty call back
+}
+
+// Callback used to test determinancy
+static volatile int timer_cnt;
+void
+sigrt1(int signo, siginfo_t *info, void *context)
+{
+    if (timer_cnt == nscheds) return;
+    sched_ft[timer_cnt].start = 0;
+    HAL_CLOCK_READ(&sched_ft[timer_cnt++].end);
+    if (timer_cnt == nscheds) {
+        sem_post(&synchro);
+    }
+}
+
+static sem_t timer_sem;
+
+static void
+sigrt2(int signo, siginfo_t *info, void *context)
+{
+    if (timer_cnt == nscheds) {
+        sem_post(&synchro);
+        sem_post(&timer_sem);        
+    } else {
+        sched_ft[timer_cnt].start = 0;
+        sem_post(&timer_sem);
+    }
+}
+
+// Null thread, used to keep scheduler busy
+void *
+timer_test(void * id)
+{
+    while (true) {
+        cyg_thread_yield();
+        pthread_testcancel();
+    }
+
+    return id;
+}
+
+// Thread that suspends itself at the first opportunity
+void *
+timer_test2(void *id)
+{
+    while (timer_cnt != nscheds) {
+        HAL_CLOCK_READ(&sched_ft[timer_cnt++].end);
+        sem_wait(&timer_sem);
+    }
+    return id;
+}
+
+void
+run_timer_tests(void)
+{
+    int res;
+    int i;
+    struct sigaction sa;
+    struct sigevent sigev;
+    struct itimerspec tp;
+    
+    // Install signal handlers
+    sigemptyset( &sa.sa_mask );
+    sa.sa_flags = SA_SIGINFO;
+
+    sa.sa_sigaction = sigrt0;
+    sigaction( SIGRTMIN, &sa, NULL );
+
+    sa.sa_sigaction = sigrt1;
+    sigaction( SIGRTMIN+1, &sa, NULL );
+
+    sa.sa_sigaction = sigrt2;
+    sigaction( SIGRTMIN+2, &sa, NULL );
+
+    // Set up common bits of sigevent
+
+    sigev.sigev_notify = SIGEV_SIGNAL;
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntimers;  i++) {
+        HAL_CLOCK_READ(&timer_ft[i].start);
+        sigev.sigev_signo = SIGRTMIN;
+        sigev.sigev_value.sival_ptr = (void*)(&timers[i]);
+        res = timer_create( CLOCK_REALTIME, &sigev, &timers[i]);
+        HAL_CLOCK_READ(&timer_ft[i].end);
+        CYG_ASSERT( res == 0 , "timer_create() returned error");
+    }
+    show_times(timer_ft, ntimers, "Create timer");
+
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    tp.it_value.tv_sec = 0;
+    tp.it_value.tv_nsec = 0;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 0;
+    for (i = 0;  i < ntimers;  i++) {
+        HAL_CLOCK_READ(&timer_ft[i].start);
+        res = timer_settime( timers[i], 0, &tp, NULL );
+        HAL_CLOCK_READ(&timer_ft[i].end);
+        CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    }
+    show_times(timer_ft, ntimers, "Initialize timer to zero");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    tp.it_value.tv_sec = 1;
+    tp.it_value.tv_nsec = 250000000;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 0;
+    for (i = 0;  i < ntimers;  i++) {
+        HAL_CLOCK_READ(&timer_ft[i].start);
+        res = timer_settime( timers[i], 0, &tp, NULL );
+        HAL_CLOCK_READ(&timer_ft[i].end);
+        CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    }
+    show_times(timer_ft, ntimers, "Initialize timer to 1.25 sec");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    tp.it_value.tv_sec = 0;
+    tp.it_value.tv_nsec = 0;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 0;
+    for (i = 0;  i < ntimers;  i++) {
+        HAL_CLOCK_READ(&timer_ft[i].start);
+        res = timer_settime( timers[i], 0, &tp, NULL );
+        HAL_CLOCK_READ(&timer_ft[i].end);
+        CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    }
+    show_times(timer_ft, ntimers, "Disable timer");
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    for (i = 0;  i < ntimers;  i++) {
+        HAL_CLOCK_READ(&timer_ft[i].start);
+        res = timer_delete( timers[i] );
+        HAL_CLOCK_READ(&timer_ft[i].end);
+        CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    }
+    show_times(timer_ft, ntimers, "Delete timer");
+    
+    
+
+    sigev.sigev_signo = SIGRTMIN+1;
+    sigev.sigev_value.sival_ptr = (void*)(&timers[i]);
+    res = timer_create( CLOCK_REALTIME, &sigev, &timers[0]);
+    CYG_ASSERT( res == 0 , "timer_create() returned error");
+    tp.it_value.tv_sec = 0;
+    tp.it_value.tv_nsec = 50000000;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 50000000;;
+    timer_cnt = 0;
+    res = timer_settime( timers[0], 0, &tp, NULL );
+    CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    sem_init(&synchro, 0, 0);
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    do
+    { res = sem_wait(&synchro);
+    } while( res == -1 && errno == EINTR );
+    CYG_ASSERT( res == 0 , "sem_wait() returned error");        
+    tp.it_value.tv_sec = 0;
+    tp.it_value.tv_nsec = 0;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 0;
+    res = timer_settime( timers[0], 0, &tp, NULL );
+    CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    res = timer_delete( timers[0] );
+    CYG_ASSERT( res == 0 , "timer_delete() returned error");
+    show_times(sched_ft, nscheds, "Timer latency [0 threads]");
+
+
+    
+
+    struct sched_param schedparam;
+    pthread_attr_t attr;
+    void *retval;
+    
+    // Set my priority higher than any I plan to create
+    schedparam.sched_priority = 20;
+    pthread_setschedparam( pthread_self(), SCHED_RR, &schedparam );
+
+    
+    // Initiaize thread creation attributes
+
+    pthread_attr_init( &attr );
+    pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
+    pthread_attr_setschedpolicy( &attr, SCHED_RR );
+    schedparam.sched_priority = 10;
+    pthread_attr_setschedparam( &attr, &schedparam );
+    
+    for (i = 0;  i < 2;  i++) {
+        pthread_attr_setstackaddr( &attr, &stacks[i][STACK_SIZE] );
+        pthread_attr_setstacksize( &attr, STACK_SIZE );
+        res = pthread_create( &threads[i],
+                        &attr,
+                        timer_test,
+                        (void *)i
+                        );
+        CYG_ASSERT( res == 0 , "pthread_create() returned error");
+    }
+
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+
+    sigev.sigev_signo = SIGRTMIN+1;
+    sigev.sigev_value.sival_ptr = (void*)(&timers[i]);
+    res = timer_create( CLOCK_REALTIME, &sigev, &timers[0]);
+    CYG_ASSERT( res == 0 , "timer_create() returned error");
+    tp.it_value.tv_sec = 0;
+    tp.it_value.tv_nsec = 50000000;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 50000000;;
+    timer_cnt = 0;
+    res = timer_settime( timers[0], 0, &tp, NULL );
+    CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    
+    sem_init(&synchro, 0, 0);
+    do
+    { res = sem_wait(&synchro);
+    } while( res == -1 && errno == EINTR );
+    CYG_ASSERT( res == 0 , "sem_wait() returned error");        
+    res = timer_delete(timers[0]);
+    CYG_ASSERT( res == 0 , "timerdelete() returned error");    
+    show_times(sched_ft, nscheds, "Timer latency [2 threads]");
+    for (i = 0;  i < 2;  i++) {
+        pthread_cancel(threads[i]);
+        pthread_join(threads[i], &retval);
+    }
+
+
+    
+    for (i = 0;  i < ntest_threads;  i++) {
+        pthread_attr_setstackaddr( &attr, &stacks[i][STACK_SIZE] );
+        pthread_attr_setstacksize( &attr, STACK_SIZE );
+        res = pthread_create( &threads[i],
+                        &attr,
+                        timer_test,
+                        (void *)i
+                        );
+        CYG_ASSERT( res == 0 , "pthread_create() returned error");
+    }
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    sigev.sigev_signo = SIGRTMIN+1;
+    sigev.sigev_value.sival_ptr = (void*)(&timers[i]);
+    res = timer_create( CLOCK_REALTIME, &sigev, &timers[0]);
+    CYG_ASSERT( res == 0 , "timer_create() returned error");
+    tp.it_value.tv_sec = 0;
+    tp.it_value.tv_nsec = 50000000;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 50000000;;
+    timer_cnt = 0;
+    res = timer_settime( timers[0], 0, &tp, NULL );
+    CYG_ASSERT( res == 0 , "timer_settime() returned error");
+    
+    sem_init(&synchro, 0, 0);
+    do
+    { res = sem_wait(&synchro);
+    } while( res == -1 && errno == EINTR );
+    CYG_ASSERT( res == 0 , "sem_wait() returned error");        
+    res = timer_delete(timers[0]);
+    CYG_ASSERT( res == 0 , "timerdelete() returned error");        
+    show_times(sched_ft, nscheds, "Timer latency [many threads]");
+    for (i = 0;  i < ntest_threads;  i++) {
+        pthread_cancel(threads[i]);
+        pthread_join(threads[i], &retval);
+    }
+
+    sem_init(&synchro, 0, 0);
+    sem_init(&timer_sem, 0, 0);    
+    pthread_attr_setstackaddr( &attr, &stacks[0][STACK_SIZE] );
+    pthread_attr_setstacksize( &attr, STACK_SIZE );
+    res = pthread_create( &threads[0],
+                          &attr,
+                          timer_test2,
+                          (void *)0
+        );
+    CYG_ASSERT( res == 0 , "pthread_create() returned error");
+    
+    wait_for_tick(); // Wait until the next clock tick to minimize aberations
+    sigev.sigev_signo = SIGRTMIN+2;
+    sigev.sigev_value.sival_ptr = (void*)(threads[0]);
+    res = timer_create( CLOCK_REALTIME, &sigev, &timers[0]);
+    CYG_ASSERT( res == 0 , "timer_create() returned error");
+    tp.it_value.tv_sec = 0;
+    tp.it_value.tv_nsec = 50000000;
+    tp.it_interval.tv_sec = 0;
+    tp.it_interval.tv_nsec = 50000000;;
+    timer_cnt = 0;
+    res = timer_settime( timers[0], 0, &tp, NULL );
+    CYG_ASSERT( res == 0 , "timer_settime() returned error");
+
+    do
+    { res = sem_wait(&synchro);
+    } while( res == -1 && errno == EINTR );
+    CYG_ASSERT( res == 0 , "sem_wait() returned error");        
+    res = timer_delete(timers[0]);
+    CYG_ASSERT( res == 0 , "timerdelete() returned error");        
+    show_times(sched_ft, nscheds, "Timer -> thread post latency");
+    sem_post(&timer_sem);
+//    pthread_cancel(threads[0]);
+    pthread_join(threads[0], &retval);
+
+
+    end_of_test_group();
+}
+
+
+//--------------------------------------------------------------------------
+
+void 
+run_all_tests()
+{
+    int i;
+    cyg_uint32 tv[nsamples], tv0, tv1;
+//    cyg_uint32 min_stack, max_stack, total_stack, actual_stack, j;
+    cyg_tick_count_t ticks, tick0, tick1;
+#ifdef CYG_SCHEDULER_LOCK_TIMINGS
+    cyg_uint32 lock_ave, lock_max;
+#endif
+#if defined(CYGVAR_KERNEL_COUNTERS_CLOCK_LATENCY) && defined(HAL_CLOCK_LATENCY)
+    cyg_int32 clock_ave;
+#endif
+
+    disable_clock_latency_measurement();
+
+//    cyg_test_dump_thread_stack_stats( "Startup, main stack", thread[0] );
+    cyg_test_dump_interrupt_stack_stats( "Startup" );
+    cyg_test_dump_idlethread_stack_stats( "Startup" );
+    cyg_test_clear_interrupt_stack();
+
+    diag_printf("\neCos Kernel Timings\n");
+    diag_printf("Notes: all times are in microseconds (.000001) unless otherwise stated\n");
+#ifdef STATS_WITHOUT_FIRST_SAMPLE
+    diag_printf("       second line of results have first sample removed\n");
+#endif
+
+    cyg_thread_delay(2);  // Make sure the clock is actually running
+
+    ns_per_system_clock = 1000000/rtc_resolution[1];
+
+    for (i = 0;  i < nsamples;  i++) {
+        HAL_CLOCK_READ(&tv[i]);
+    }
+    tv0 = 0;
+    for (i = 1;  i < nsamples;  i++) {
+        tv0 += tv[i] - tv[i-1];
+    }
+    end_of_test_group();
+    
+    overhead = tv0 / (nsamples-1);
+    diag_printf("Reading the hardware clock takes %d 'ticks' overhead\n", overhead);
+    diag_printf("... this value will be factored out of all other measurements\n");
+
+    // Try and measure how long the clock interrupt handling takes
+    for (i = 0;  i < nsamples;  i++) {
+        tick0 = cyg_current_time();
+        while (true) {
+            tick1 = cyg_current_time();
+            if (tick0 != tick1) break;
+        }
+        HAL_CLOCK_READ(&tv[i]);
+    }
+    tv1 = 0;
+    for (i = 0;  i < nsamples;  i++) {
+        tv1 += tv[i] * 1000;
+    }
+    tv1 = tv1 / nsamples;
+    tv1 -= overhead;  // Adjust out the cost of getting the timer value
+    diag_printf("Clock interrupt took");
+    show_ticks_in_us(tv1);
+    diag_printf(" microseconds (%d raw clock ticks)\n", tv1/1000);
+    enable_clock_latency_measurement();
+
+    ticks = cyg_current_time();
+
+    show_test_parameters();
+    show_times_hdr();
+
+    reset_clock_latency_measurement();
+
+    run_thread_tests();
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+    run_mutex_tests();
+//    run_mbox_tests();
+#endif
+    run_semaphore_tests();
+    run_timer_tests();
+
+#ifdef CYG_SCHEDULER_LOCK_TIMINGS
+    Cyg_Scheduler::get_lock_times(&lock_ave, &lock_max);
+    diag_printf("\nMax lock:");
+    show_ticks_in_us(lock_max);
+    diag_printf(", Ave lock:");
+    show_ticks_in_us(lock_ave);
+    diag_printf("\n");
+#endif
+
+#if defined(CYGVAR_KERNEL_COUNTERS_CLOCK_LATENCY) && defined(HAL_CLOCK_LATENCY)
+    // Display latency figures in same format as all other numbers
+    disable_clock_latency_measurement();
+    clock_ave = (total_clock_latency*1000) / total_clock_interrupts;
+    show_ticks_in_us(clock_ave);
+    show_ticks_in_us(min_clock_latency*1000);
+    show_ticks_in_us(max_clock_latency*1000);
+    show_ticks_in_us(0);
+    diag_printf("            Clock/interrupt latency\n\n");
+    enable_clock_latency_measurement();    
+#endif
+
+#if defined(CYGVAR_KERNEL_COUNTERS_CLOCK_DSR_LATENCY)
+    disable_clock_latency_measurement();    
+    clock_ave = (total_clock_dsr_latency*1000) / total_clock_dsr_calls;
+    show_ticks_in_us(clock_ave);
+    show_ticks_in_us(min_clock_dsr_latency*1000);
+    show_ticks_in_us(max_clock_dsr_latency*1000);
+    show_ticks_in_us(0);
+    diag_printf("            Clock DSR latency\n\n");
+    enable_clock_latency_measurement();
+#endif
+
+#if 0    
+    disable_clock_latency_measurement();
+    min_stack = STACK_SIZE;
+    max_stack = 0;
+    total_stack = 0;
+    for (i = 0;  i < (int)NTEST_THREADS;  i++) {
+        for (j = 0;  j < STACK_SIZE;  j++) {
+            if (stacks[i][j]) break;
+        }
+        actual_stack = STACK_SIZE-j;
+        if (actual_stack < min_stack) min_stack = actual_stack;
+        if (actual_stack > max_stack) max_stack = actual_stack;
+        total_stack += actual_stack;
+    }
+    for (j = 0;  j < STACKSIZE;  j++) {
+        if (((char *)stack[0])[j]) break;
+    }
+    diag_printf("%5d   %5d   %5d  (main stack: %5d)  Thread stack used (%d total)\n", 
+                total_stack/NTEST_THREADS, min_stack, max_stack, 
+                STACKSIZE - j, STACK_SIZE);
+#endif
+    
+//    cyg_test_dump_thread_stack_stats( "All done, main stack", thread[0] );
+    cyg_test_dump_interrupt_stack_stats( "All done" );
+    cyg_test_dump_idlethread_stack_stats( "All done" );
+
+    enable_clock_latency_measurement();
+
+    ticks = cyg_current_time();
+    diag_printf("\nTiming complete - %d ms total\n\n", (int)((ticks*ns_per_system_clock)/1000));
+
+    CYG_TEST_PASS_FINISH("Basic timing OK");
+}
+
+int main( int argc, char **argv )
+{
+    CYG_TEST_INIT();
+
+    if (cyg_test_is_simulator) {
+        nsamples = NSAMPLES_SIM;
+        ntest_threads = NTEST_THREADS_SIM;
+        nthread_switches = NTHREAD_SWITCHES_SIM;
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+        nmutexes = NMUTEXES_SIM;
+#endif
+        nmboxes = NMBOXES_SIM;
+        nsemaphores = NSEMAPHORES_SIM;
+        nscheds = NSCHEDS_SIM;
+        ntimers = NTIMERS_SIM;  
+    } else {
+        nsamples = NSAMPLES;
+        ntest_threads = NTEST_THREADS;
+        nthread_switches = NTHREAD_SWITCHES;
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+        nmutexes = NMUTEXES; 
+#endif
+        nmboxes = NMBOXES;
+        nsemaphores = NSEMAPHORES;
+        nscheds = NSCHEDS;
+        ntimers = NTIMERS;
+    }
+
+    // Sanity
+#ifdef WORKHORSE_TEST
+    ntest_threads = max(512, ntest_threads);
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+    nmutexes = max(1024, nmutexes);
+#endif
+    nsemaphores = max(1024, nsemaphores);
+    nmboxes = max(1024, nmboxes);
+    ncounters = max(1024, ncounters);
+    ntimers = max(1024, ntimers);
+#else
+    ntest_threads = max(64, ntest_threads);
+#ifdef CYGPKG_POSIX_PTHREAD_MUTEX
+    nmutexes = max(32, nmutexes);
+#endif
+    nsemaphores = max(32, nsemaphores);
+    nmboxes = max(32, nmboxes);
+    ntimers = max(32, ntimers);
+#endif
+
+    run_all_tests();
+   
+}
+
+#endif // CYGFUN_KERNEL_API_C, etc.
+
+// EOF tm_posix.cxx
diff --git a/packages/net/.cvsignore b/packages/net/.cvsignore
new file mode 100644 (file)
index 0000000..fc538ed
--- /dev/null
@@ -0,0 +1 @@
+openssl
\ No newline at end of file
diff --git a/packages/net/athttpd/v2_0/ChangeLog b/packages/net/athttpd/v2_0/ChangeLog
new file mode 100644 (file)
index 0000000..d3c7d08
--- /dev/null
@@ -0,0 +1,241 @@
+2008-06-18  Oyvind Harboe  <oyvind.harboe@zylin.com>
+
+       * src/jim-aio.c (JimAioHandlerCommand): GCC 4.3.1 pointed out a
+       buffer overrun.
+
+2008-06-17 Anthony Tonizzo <atonizzo@gmail.com>
+
+       Jumbo patch containing many individual patches from a number of
+       different contributors on different days. The ChangeLog entries
+       for all these individual patches are:
+       
+        2007-12-02  Anthony Tonizzo <atonizzo@gmail.com>
+
+       * src/socket.c src/httpd.c: Corrected a bug in
+       cyg_httpd_write_chunked(): Now the CRLF that terminates a chunk is
+       added by the function and not expected to be there already in the
+       data supplied by the user. Modified the function
+       cyg_httpd_end_chunked() so that the flag
+       CYG_HTTPD_MODE_TRANSFER_CHUNKED is always cleared after it
+       terminates. The cyg_httpd_process_request() now loops as many
+       times as the number of full requests received.  Renamed header_end
+       to request_end to better reflect its real use, and the fact that
+       the former name was misleading for POST requests (Danny
+       Sade). Changed the function that collects a request: Now the
+       remaining part of an incomplete request is copied back to the
+       beginning of the buffer. This avoids that multiple split headers
+       might creep towards the end of the buffer.
+
+        2007-11-28  Rene' Nielsen <rbn@vitesse.com> and 
+                   Anthony Tonizzo <atonizzo@gmail.com>
+
+       * doc/athttpd.sgml: Included Digest (MD5) authentication as fully
+       supported.
+       * cdl/httpd.cdl: Updated the cdl to reflect the fact that MD5
+       authentication is now a fully tested feature, at least on some
+       clients (Thanks to Tad for testing this!)
+       * src/httpd.c: Added the initialization of the global variable
+       cyg_httpd_md5_response. This corrects a security hole that could
+       allow unauthenticated browsers to access pages that require
+       authentication. This required a minor change (switch of variables
+       used) in the authentication code. Added code to avoid a buffer
+       overflow during the parsing of headers for authenticated
+       pages. Clear the CYG_HTTPD_MODE_SEND_HEADER_ONLY at the beginning
+       of any request.
+       * src/auth.c: Removed dead code and made static a bunch of
+       functions and variables.
+       * src/auth.h: The AUTH_STORAGE_BUFFER_LENGTH value is now split
+       into two numbers, one that gives the maximum length of the login
+       phrase and one for the password.
+       * src/socket.c: Added a NULL terminator after each header packet
+       that is received. Now the strstr() is guaranteed to find
+       terminated string.
+
+        2007-11-27  Tad Artis <ecos@ds3switch.com>
+
+       * src/auth.c: Modified the cyg_httpd_digest_data() and
+       cyg_httpd_digest_skip() functions to support IE7. A careful read
+       of the augmented BNF in RFC2616 indicates that spaces within the
+       elements of the authentication header are optional. The original
+       atHTTPD code incorrectly relied on a space after the comma. Moved
+       the authentication check inside cyg_httpd_process_method() so that
+       each request, regardless of the type, will have to go through
+       authentication.
+
+        2007-11-26  Tad Artis <ecos@ds3switch.com> and 
+                   Anthony Tonizzo <atonizzo@gmail.com>
+
+       * src/forms.c: Checked for a null terminator inside
+       cyg_httpd_store_form_variable, so that we do not scan past the end
+       of the packet. Check the form variables for both length and
+       content, to avoid false positives. Modified cyg_httpd_from_hex()
+       to return -1 in case of error.
+       * src/httpd.c: Corrected the strings sent back by the server to
+       challenge the client to an MD5 authentication. Adds a couple of
+       commas to separate the items in the string.
+       * src/http.h:
+       * src/socket.h: Corrected a number of indexes where
+       CYGNUM_FILEIO_NFILE was used instead of the correct
+       CYGPKG_NET_MAXSOCKETS.
+
+2008-03-04  Danny Sade  <danny@channelot.com>
+
+       * src/socket.c: put NULL at the end of inbuff on each iteration,
+       preventing strstr from looking at old data beyond inbuffer_len
+
+2007-11-12  Oyvind Harboe  <oyvind.harboe@zylin.com>
+2007-11-12  Jonathan Larmour  <jifl@eCosCentric.com>
+
+       * doc/athttpd.sgml: added an example of a tcl script.
+       * src/http.c, forms.c: serve cgi requests before file system requests,
+       that way it isn't possible to download the actual cgi/.o script and
+       cgi works even if the http root directory is above the cgi directory.
+       * src/http.c: if only tcl cgi is enabled, cgi requests are now
+       forwarded to tcl
+       * include/jim.h: include file order fix; now compiles again.
+       * doc/athttpd.sgml: Fixed typos in doc. Return value from handler is
+       not used, recommend returning 0 in doc.
+
+2006-12-03  Anthony Tonizzo  <atonizzo@gmail.com>
+
+       * cdl/httpd.cdl: Corrected a CDL error in the requirements of
+       CYGOPT_NET_ATHTTPD_USE_FS
+
+2006-11-27  Jonathan Larmour  <jifl@eCosCentric.com>
+
+       * cdl/httpd.cdl: Improve CDL dependencies.
+
+2006-11-08  Anthony Tonizzo  <atonizzo@gmail.com>
+
+       * doc/athttpd.sgml: Updated to describe lasted changes and corrected
+       minor typos.
+       * src/http.c: Check for "Content-Type" header. This is needed if we
+       want to support parsing form variables in POST requests.
+       * src/jim.c: Updated with latest release from Jim CVS.
+       * src/cgi.c: streamlined cyg_httpd_exec_cgi_tcl(), now uses the 'source'
+       command of tcl to execute a tcl script.
+       * src/forms.c: Modified cyg_handle_method_POST so that the variables in the
+       payload are scanned only if the request has a Content-Type 
+       of 'application/x-www-form-urlencoded'
+       * src/jim-aio.c: Added to package. Now tcl has IO functions to access a
+       file system.
+       * include/httpd.h: Added a new mode, CYG_HTTPD_MODE_FORM_DATA which is set
+       when a POST request has a Content-Type of 
+       'application/x-www-form-urlencoded'
+           
+2006-10-16  Lars Povlsen  <lpovlsen@vitesse.com> and Anthony Tonizzo  <atonizzo@gmail.com>
+
+       * cdl/httpd.cdl: add CYGOPT_NET_ATHTTPD_CLOSE_CHUNKED_CONNECTIONS. Default
+       is set to CLOSE, so it is backward compatible with 
+       previous versions of the browser.
+       * src/socket.c: cyg_httpd_process_request() uses a loop to collect at least
+       one full frame (til a header terminator is found), 
+       cyg_httpd_start_chunked() only close if configured to do so.
+       * src/httpd.c: Overhaul of cyg_httpd_send_error to avoid the use of
+       inbuffer as temporary storage (conflicts with pipelined frames),
+       removed the option to send a page after calling a C language
+       handler
+       * include/httpd.h: Added a new mode, CYG_HTTPD_MODE_NO_CACHE
+           
+2006-10-12  Lars Povlsen  <lpovlsen@vitesse.com> and Anthony Tonizzo  <atonizzo@gmail.com>
+
+       * cdl/httpd.cdl: add CYGNUM_ATHTTPD_SERVER_MAX_POST to limit POST'ed data
+       * include/http.h: Added header_end, post_data fields to httpstate,
+       Added "302 Found" for POST handler redirect (CYG_HTTPD_STATUS_MOVED_TEMPORARILY)
+       * src/forms.c: Fixed variable decoding, fixed large POST processing
+       * src/http.c: Fixed some debug ouptuts, cleanup after POST processing, 
+       overhaul of the pipelined requests code which can now
+       handle multiple requests per frame.
+       * src/socket.c: Removed assert for socket write failure, Accumulating receiving
+       of requests (Browsers (Firefox) may pass partial headers in separate 
+       fragments). Fixed some diagnostics output.
+
+2006-07-19  Anthony Tonizzo  <atonizzo@gmail.com> and Sergei Gavrikov  <w3sg@softhome.net>
+
+       * cdl/httpd.cdl: 
+       * doc/athttpd.sgml: Corrected some typos and rectified some omissions.
+       * include/jim.h:    Added an inline to Jim_InitExtension()
+       * src/cgi.c:        used malloc() instead of cyg_ldr_malloc();
+       * src/forms.c:      Added a #define to be able tio use the TCL scripting
+       without OBJLOADER
+       * src/http.c:       
+       * src/socket.c:     Lots of typos stamped out, and some better comments too.
+                            
+2006-07-19  Anthony Tonizzo  <atonizzo@gmail.com>
+
+       * src/socket.c: Corrected a typo that generated an assertion.
+       Modified slightly the source of cyg_httpd_write and cyg_httpd_writev
+       to make the code more consistent as to when assertions are thrown.
+
+2006-07-19  Sergei Gavrikov  <w3sg@softhome.net>
+
+       * doc/athttpd.sgml: jade doesn't allow underscores in
+       id attributes, so fix.
+
+2006-07-18  Jonathan Larmour  <jifl@eCosCentric.com>
+
+       * cdl/httpd.cdl: Add -D __ECOS in compiler flags.
+       Change include_dir to cyg/athttpd.
+       Rename all CDL options from *_HTTPD_* to *_ATHTTPD_*.
+       * All files: Rename cyg/httpd include directory to cyg/athttpd.
+       Rename all CDL options from *_HTTPD_* to *_ATHTTPD_*.
+       * doc/athttpd.sgml: Document MD5 algorithm licensing.
+       * src/socket.c: Remove unused SNTP include.
+
+2006-06-13  Anthony Tonizzo  <atonizzo@gmail.com>
+
+       * cdl/httpd.cdl: 
+       * doc/athttpd.sgml: 
+       * doc/mime_types.txt: 
+       * include/auth.h: 
+       * include/cgi.h: 
+       * include/digcalc.h: 
+       * include/forms.h: 
+       * include/global.h: 
+       * include/handler.h: 
+       * include/http.h: 
+       * include/jim.h: 
+       * include/md5.h: 
+       * include/socket.h: 
+       * src/auth.c: 
+       * src/cgi.c: 
+       * src/forms.c: 
+       * src/handler.c: 
+       * src/http.c: 
+       * src/jim.c: 
+       * src/md5c.c: 
+       * src/socket.c: 
+       Created ATHTTPD package.
+       
+//===========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 2005, 2006 eCosCentric Ltd.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//===========================================================================
diff --git a/packages/net/athttpd/v2_0/cdl/httpd.cdl b/packages/net/athttpd/v2_0/cdl/httpd.cdl
new file mode 100644 (file)
index 0000000..2813d1f
--- /dev/null
@@ -0,0 +1,353 @@
+# ====================================================================
+#
+#      httpd.cdl
+#
+#      HTTP server configuration data
+#
+# ====================================================================
+#####ECOSGPLCOPYRIGHTBEGIN####
+## -------------------------------------------
+## This file is part of eCos, the Embedded Configurable Operating System.
+## Copyright (C) 2005 eCosCentric Ltd.
+##
+## eCos 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.
+##
+## eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+## 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+##
+## As a special exception, if other files instantiate templates or use macros
+## or inline functions from this file, or you compile this file and link it
+## with other works to produce a work based on this file, this file does not
+## by itself cause the resulting work to be covered by the GNU General Public
+## License. However the source code for this file must still be made available
+## in accordance with section (3) of the GNU General Public License.
+##
+## This exception does not invalidate any other reasons why a work based on
+## this file might be covered by the GNU General Public License.
+##
+## -------------------------------------------
+#####ECOSGPLCOPYRIGHTEND####
+# ====================================================================
+######DESCRIPTIONBEGIN####
+#
+# Author(s):      Anthony Tonizzo (atonizzo@gmail.com)
+# Contributors:   Lars Povlsen    (lpovlsen@vitesse.com)
+# Date:           2006-06-09
+#
+#####DESCRIPTIONEND####
+#
+# ====================================================================
+
+cdl_package CYGPKG_ATHTTPD {
+    display       "Another Tiny HTTP server"
+    description   "This package provides a small footprint web server for eCos
+                   with configurable features."
+    include_dir   cyg/athttpd
+    include_files auth.h digcalc.h forms.h global.h handler.h http.h md5.h socket.h cgi.h jim.h
+    compile       forms.c handler.c http.c socket.c cgi.c
+    requires      CYGPKG_NET
+    requires      CYGPKG_NET_STACK_INET
+    requires      !CYGPKG_HTTPD
+    requires      CYGINT_ISO_STDIO_STREAMS
+    requires      CYGINT_ISO_STDIO_FILEACCESS
+    requires      CYGINT_ISO_STDIO_FORMATTED_IO
+    requires      CYGINT_ISO_STRING_MEMFUNCS
+    requires      CYGINT_ISO_STRING_STRFUNCS
+    requires      CYGINT_ISO_STRING_BSD_FUNCS
+    requires      CYGINT_ISO_C_CLOCK_FUNCS
+    requires      CYGINT_ISO_MALLOC
+    requires      CYGINT_ISO_CTYPE
+
+# ====================================================================
+   
+    cdl_component CYGPKG_NET_ATHTTPD_THREADOPT {
+        display "Thread settings"
+        flavor  none
+        no_define
+        description   "Options to change certain thread values."
+
+      cdl_option CYGNUM_NET_ATHTTPD_THREADOPT_PRIORITY {
+          display "Thread priority"
+          flavor data
+          default_value { CYGNUM_KERNEL_SCHED_PRIORITIES/2 }
+          legal_values 0 to CYGNUM_KERNEL_SCHED_PRIORITIES
+          description "The HTTP server threads can be run at any
+                       priority.  The exact priority depends on the
+                       importance of the server relative to the rest
+                       of the system. The default is to put it in the
+                       middle of the priority range to provide
+                       reasonable response without impacting genuine
+                       high priority threads."  
+      }
+
+      cdl_option CYGNUM_NET_ATHTTPD_THREADOPT_STACKSIZE {
+          display "Thread stack size"
+          flavor data
+          default_value 4096
+          description "This is the amount of extra stack to be
+                       allocated for the HTTPD thread. This value is
+                       added to CYGNUM_HAL_STACK_SIZE_MINIMUM to
+                       determine the final size of the stack for the
+                       server."  
+      } 
+    }
+
+    cdl_component CYGOPT_NET_ATHTTPD_SERVEROPT {
+        display "Server settings"
+        flavor  none
+        no_define
+        description   "Options to change certain server options."
+
+      cdl_option CYGNUM_NET_ATHTTPD_SERVEROPT_PORT {
+          display "Server Port"
+          flavor data
+          default_value 80
+          description "This is the port on which the server will be listening
+                      for requests. Unless overridden in the request by the 
+                      client, the well known port for HTTP is 80."
+      }
+
+      cdl_option CYGDAT_NET_ATHTTPD_SERVEROPT_SERVERID {
+          display "Server ID string"
+          flavor data
+          default_value {"\"eCos Embedded Web Server\""}
+          description "This is the string sent out in the 'Server:' 
+                       header line."
+      }
+      
+      cdl_option CYGNUM_ATHTTPD_SERVER_BUFFER_SIZE {
+          display "IO buffer size"
+          flavor data
+          default_value 2048
+          description "This option defines the size of the buffers used to 
+                       receive and transmit transmit data to and from the 
+                       TCP/IP stack."
+      }
+
+      cdl_option CYGNUM_ATHTTPD_SERVER_MAX_POST {
+          display "Maximum data received upon POST"
+          flavor data
+          default_value 2048
+          description "This option defines the size of maximum amount of data 
+                       the web server will accept from POST'ed forms."
+      }
+
+      cdl_option CYGDAT_NET_ATHTTPD_SERVEROPT_ROOTDIR {
+          display "HTTPD root directory"
+          flavor data
+          default_value {"\"/\""}
+          description "This is the absolute path in the eCos file
+                       system to the HTML documents, including cgi-bin
+                       files and error files and it is generally where
+                       the web server will look for the index
+                       file. Include a trailing slash."
+      }
+      
+      cdl_option CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR {
+          display "cgi-bin directory"
+          active_if    { 0 != CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER || 
+                         0 != CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL }
+          flavor data
+          default_value {"\"cgi-bin/\""}
+          description "This is the path, relative to
+                       CYGDAT_NET_ATHTTPD_SERVEROPT_ROOTDIR, where the
+                       cgi-bin files are stored. Based on the
+                       extension of the cgi-bin file requested, the
+                       appropriate interpreter will be used. Include a
+                       trailing slash."
+      }
+      
+      cdl_option CYGDAT_NET_ATHTTPD_SERVEROPT_ERRORDIR {
+          display "Error files directory"
+          flavor data
+          default_value {"\"errors/\""}
+          description "This is the path, relative to the
+                       CYGDAT_NET_ATHTTPD_SERVEROPT_ROOTDIR, that
+                       contains the user-defined files that are sent
+                       out by the server in case of error. The files
+                       are named error_XXX.html where XXX is the 3
+                       digit HTML code.  For example, for a 404 error
+                       the server file will be named
+                       error_404.html. Upon a 404 error, the server
+                       will check the existence of such a file in this
+                       directory and if found, it will send it
+                       out. Missing that file, a standard simple
+                       message will be sent instead. Include a
+                       trailing slash."
+      }
+
+      cdl_option CYGDAT_NET_ATHTTPD_DEFAULT_MIME_TYPE {
+          display "Default MIME type"
+          flavor data
+          default_value {"\"text/plain\""}
+          description "When accessing internal resources or a file
+                       system, the MIME type is determined by first
+                       finding the extension of the file itself and
+                       then by looking up the extension in the MIME
+                       table. In case no extension is found the user
+                       can define the default MIME type to use. Notice
+                       that this is the full MIME type and not the
+                       extension.  A list of standard MIME types
+                       sorted by extension can be found in the
+                       current/doc directory" 
+      }
+      
+      cdl_option CYGDAT_NET_ATHTTPD_ALTERNATE_HOME {
+          display "User defined Home Page"
+          flavor booldata
+          default_value {"\"/index.html\""}
+          description "This file name defines the name of a custom index file 
+                       and is used in case none of the default index files are 
+                       found in a directory. Notice that this file name is
+                       only appended to GET requests for \"/\""
+      }
+    }  
+
+    cdl_option CYGOPT_NET_ATHTTPD_USE_FS {
+        display       "Support for file system access"
+        flavor        bool
+        default_value 1
+        active_if     CYGPKG_IO_FILEIO
+        description   "
+            This option enables the use of a file system to access the pages
+             to be served. It is the responsibility of the user to properly
+             mount the file system(s) required by the web server. If this
+             option is not selected each URL requested must be serviced using
+             either c language callbacks or internal resources." 
+    }
+
+    cdl_option CYGOPT_NET_ATHTTPD_USE_AUTH {
+        display       "Support for basic and digest authentication"
+        flavor        bool
+        default_value 0
+        description   "
+            This option enables the use basic authentication in web pages.
+            Not all clients have been tested." 
+       compile md5c.c
+       compile auth.c
+    }
+
+    cdl_option CYGOPT_NET_ATHTTPD_CLOSE_CHUNKED_CONNECTIONS {
+        display       "Close connections used for chunked transfers"
+        flavor        bool
+        default_value 1
+        description   "
+            This option causes connections used for chunked transfer
+            to be closed after use. Persisting the connection will use
+            less network resources and will improve latency, but may
+            do so at the risk of compatibility with older browsers."
+    }
+
+    cdl_option CYGOPT_NET_ATHTTPD_DOCUMENT_EXPIRATION_TIME {
+        display          "Maximum lifetime of a document in seconds"
+        flavor           data
+        default_value    0
+        description      "
+            This options causes documents to 'expire' after a set number
+            of seconds. If certain pages are updated frequently, it might be a
+            good idea to assign them an expitation time in seconds. If the
+            client needs to reload a page that has expired, it will request
+            it again, otherwise it will use the copy in the cache. A value
+            of 0 means that this option is disabled. Any other value
+            represents the number of seconds (after the last modification to
+            the document) after which the page becomes stale. This option
+            applies to all the pages (including those that reside in ROM
+            and thus, by definition, won't change) and thus is it preferable
+            to use the CYG_HTTPD_MODE_NO_CACHE mode for pages that need to be
+            refreshed frequently."
+    }
+
+    cdl_option CYGOPT_NET_ATHTTPD_USE_DIRLIST {
+        display       "Support for directory listing"
+        flavor        bool
+        default_value 0
+        active_if     CYGPKG_IO_FILEIO
+        active_if     CYGOPT_NET_ATHTTPD_USE_FS
+        description   "
+            When a client issues a request that ends in '/' the server will
+            try to locate anyone of a number of index files. Failing to find
+            one, it will list the directory contents."
+    }
+
+    cdl_component CYGOPT_NET_ATHTTPD_CGIBIN {
+        display "Supported CGI Types"
+        flavor  none
+        no_define
+        description   "Options to select which CGI types are supported."
+
+      cdl_option CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER {
+          display       "Support cgi via the OBJLOADER package"
+          flavor        bool
+          default_value 0
+          active_if     CYGPKG_OBJLOADER
+          description   "This option enables the use of the object loader 
+                         package as a means of providing on-demand loading and 
+                         execution of code, thus providing a simple cgi
+                         capability that does not involve scripting." 
+      }
+
+      cdl_option CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL {
+          display       "Support cgi via the a simple tcl interpreter (jim)"
+          flavor        bool
+          default_value 0
+          description   "This option enables the use of a small tcl
+                         interpreter as a means of providing a simple cgi
+                         capability. Checking this option increases 
+                         considerably the size of the executable." 
+          compile       jim.c jim-aio.c
+          define        JIM_ANSIC
+          define        JIM_STATICEXT
+      }
+    }  
+
+    cdl_option CYGOPT_NET_ATHTTPD_DEBUG_LEVEL {
+        display          "Verbosity of debug output"
+        flavor           data
+        legal_values     0 1 2
+        default_value    0
+        description      "This option allows controls over the verbosity of
+                         the debug output. 1 mostly reports opening and
+                         closing of socket descriptors, 2 is very
+                         verbose, including the name of all files sent
+                         out, including internal resources."
+    }
+    cdl_component CYGPKG_ATHTTPD_OPTIONS {
+        display "AT HTTP server build options"
+        flavor  none
+        no_define
+
+        cdl_option CYGPKG_ATHTTPD_CFLAGS_ADD {
+            display "Additional compiler flags"
+            flavor  data
+            no_define
+            default_value { "-D__ECOS" }
+            description   "
+                This option modifies the set of compiler flags for
+                building the HTTP server package.
+                These flags are used in addition
+                to the set of global flags."
+        }
+
+        cdl_option CYGPKG_ATHTTPD_CFLAGS_REMOVE {
+            display "Suppressed compiler flags"
+            flavor  data
+            no_define
+            default_value { "" }
+            description   "
+                This option modifies the set of compiler flags for
+                building the HTTP server package. These flags are removed from
+                the set of global flags if present."
+        }
+    }
+}
+
+# ====================================================================
+# EOF httpd.cdl
diff --git a/packages/net/athttpd/v2_0/doc/athttpd.sgml b/packages/net/athttpd/v2_0/doc/athttpd.sgml
new file mode 100644 (file)
index 0000000..c14b333
--- /dev/null
@@ -0,0 +1,640 @@
+<!-- DOCTYPE part  PUBLIC "-//OASIS//DTD DocBook V3.1//EN" -->
+<!-- =============================================================== -->
+<!--                                                                 -->
+<!--     athttpd.sgml                                                -->
+<!--                                                                 -->
+<!--     Another Tiny HTTPD Server for eCos                          -->
+<!--                                                                 -->
+<!-- =============================================================== -->
+<!-- ####COPYRIGHTBEGIN####                                          -->
+<!--                                                                 -->
+<!-- =============================================================== -->
+<!-- Copyright (C) 2003, 2004, 2007 eCosCentric Ltd.                       -->
+<!-- This material may be distributed only subject to the terms      -->
+<!-- and conditions set forth in the Open Publication License, v1.0  -->
+<!-- or later (the latest version is presently available at          -->
+<!-- http://www.opencontent.org/openpub/)                            -->
+<!-- =============================================================== -->
+<!--                                                                 -->      
+<!-- ####COPYRIGHTEND####                                            -->
+<!-- =============================================================== -->
+<!-- #####DESCRIPTIONBEGIN####                                       -->
+<!--                                                                 -->
+<!-- ####DESCRIPTIONEND####                                          -->
+<!-- =============================================================== -->
+
+<!-- }}} -->
+
+
+<part id="athttpd">
+<title>Another Tiny HTTP Server for <productname>eCos</productname></title>
+
+<partintro>
+<para>
+This package provides an extensible, small footprint, full featured HTTP
+server for <productname>eCos</productname>. Many of these features can be
+disabled via the configuration tool, thus reducing the footprint of the server.
+The server has been written for the FreeBSD network stack. 
+</para>
+</partintro>
+
+<chapter id="net-athttpd">
+<title>The ATHTTP Server</title>
+<sect1 id="athttpd-features">
+<title>Features</title>
+<para>This ATHTTP implementation provides the following features:</para>
+<itemizedlist>
+  <listitem><para>GET, POST and HEAD Methods</para></listitem>
+  <listitem><para>File system Access</para></listitem>
+  <listitem><para>Callbacks to C functions</para></listitem>
+  <listitem><para>MIME type support</para></listitem>
+  <listitem><para>CGI mechanism through the OBJLOADER package or through a
+                  simple tcl interpreter</para></listitem>
+  <listitem><para>Basic and Digest (MD5) Authentication</para></listitem>
+  <listitem><para>Directory Listing</para></listitem>
+  <listitem><para>Extendable Internal Resources</para></listitem>
+</itemizedlist>
+
+<para>
+Ecos tables are used extensively throught the server to provide a high degree
+of customization.</para>
+</sect1>
+
+<sect1 id="athttpd-using">
+<title>Starting the server</title>
+<para>
+In order to start the web server, the user needs to call the function:</para>
+
+<programlisting width=72>
+cyg_httpd_start();
+</programlisting>
+
+<para>in the application code. The server initialization code spawns a new 
+thread which calls <command>init_all_network_interfaces()</command> to 
+initialize the TCP/IP stack and then starts the deamon. The function is safe
+to call multiple times.
+</para>
+</sect1>
+
+<sect1 id="athttpd-mime-types">
+<title>MIME types</title>
+<para>
+The server has an internal table with all the recognized mime types. Each time
+a file or an internal resource is sent out by the server, its extension is 
+searched in this table and if a match is found, the associated MIME type is
+then sent out in the header. 
+
+The server already provides entries for the following standard file extensions:
+
+'html', 'htm', 'gif', 'jpg', 'css', 'js', 'png'
+
+and the user is responsible for adding any further entry. The syntax for 
+adding an entry is the following:</para>
+
+<para><programlisting width=72>
+CYG_HTTPD_MIME_TABLE_ENTRY(entry_label, extension_string, mime_tipe_sting);
+
+entry table      : an identifier unique to this entry
+extension string : a string containing the extension for this entry
+type_string      : the mime string. The strings for many more mime types 
+                   is included in a file in the "doc" directory.
+</programlisting></para>
+
+<para>
+The following is an example of how to add the Adobe Portable Document Format
+<command>pdf</command> MIME type to the table:</para>
+
+<para><programlisting width=72>
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_pdf_entry, "pdf", "application/pdf");
+</programlisting></para>
+
+<sect2 id="athttpd-mime-types-chunked">
+<title>MIME Types for Chunked Frames</title>
+<para>
+For chunked frames, which are generally used inside c language callbacks, there
+is no file name to match an extension to, and thus the extension to be used
+must be passed in the <command>cyg_httpd_start_chunked()</command> call. The
+server will then scan the MIME table to find a MIME type to match the extension.
+
+For example, to start a chunked transfer of an <command>html</command> file, 
+the following call is used:</para>
+
+<para><programlisting width=72>
+cyg_httpd_start_chunked("html");
+</programlisting></para>
+
+<para>
+In any event, it is the responsibility of the user to make sure that a match to
+all used extensions is found in the table search. Failing this, 
+the default MIME type specified in the CYGDAT_NET_ATHTTPD_DEFAULT_MIME_TYPE
+string is returned.</para>
+</sect2>
+</sect1>
+
+<sect1 id="athttpd-callback">
+<title>C language callback functions</title>
+<para>
+The server allows the association of particular URLs to C language callback 
+functions. eCos tables are used to define the association between a URL and its
+corresponding callback. The syntax of the macro to add callback entries to 
+the table is:
+</para>
+
+<para><programlisting width=72>
+CYG_HTTPD_HANDLER_TABLE_ENTRY(entry_label, url_string, callback);
+
+entry table      : an identifier unique to this entry.
+url_string       : a string with the extension url that will be appended to the
+                   default directory.
+callback         : a function with a prototype:
+                   cyg_int32 callback_function(CYG_HTTPD_STATE*); 
+                   Return value is ignored - just return 0.
+</programlisting></para>
+
+<para>
+<command>CYG_HTTPD_STATE*</command> is a pointer to a structure that
+contains, among others, a buffer (outbuffer) that can be used to send data
+out. The definitions of the structure is in http.h.</para>
+
+<para>
+The following is an example of how to add a callback to a function myForm()
+whenever the URL /myform.cgi is requested:
+</para>
+
+<programlisting width=72>
+CYG_HTTPD_HANDLER_TABLE_ENTRY(hal_cb_entry, "/myform.cgi", myForm);
+</programlisting>
+
+<para>
+and somewhere in the source tree there is a function:</para>
+
+<programlisting>
+cyg_int32 myForm(CYG_HTTPD_STATE* p)
+{
+   cyg_httpd_start_chunked("html");
+   strcpy(p->outbuffer, "eCos Web Server");
+   cyg_httpd_write_chunked(p->outbuffer, strlen(p->outbuffer))
+   cyg_httpd_end_chunked();
+}  
+</programlisting>
+
+<para>This function also shows the correct method of using the chunked frames
+API inside a c language callback and also shows the use of outbuffer to
+collect data to send out.</para>
+
+<para>Chunked frames are useful when the size of the frame is not known upfront. 
+In this case it possible to send a response in chunks of various sizes, and
+terminate it with a null chunk (See RFC 2616 for details). To use chunked 
+frames, the <command>cyg_httpd_start_chunked()</command> function is used. 
+The prototype is the following:</para>
+
+<programlisting>
+ssize_t cyg_httpd_start_chunked(char *);
+</programlisting>
+
+<para>The only parameter is the <command>extension</command> to use in the 
+search for the MIME type. For most files this will be "html" or "htm" and
+it will be searched in the MIME table for an approriate MIME type that will
+be sent along in the header. The function returns the number of bytes sent
+out.</para>
+
+<para>The chunked frame must be terminated by a call to 
+<command>cyg_httpd_end_chunked()</command>:</para>
+
+<programlisting>
+void cyg_httpd_end_chunked()(void);
+</programlisting>
+
+<para>In between these two calls, the user can call the function
+<command>cyg_httpd_write_chunked()</command> to send out data any number of
+times. It is important that <command>cyg_httpd_write_chunked()</command> be
+the only function used to send data out for chunked frames. This
+guarantees that proper formatting of the response is respected.
+The prototype for the function is:</para>
+
+<programlisting>
+ssize_t cyg_httpd_write_chunked(char* p, int len);
+</programlisting>
+
+<para>The 'char*' points to the data to send out, the 'int' is the length of the
+data to send.</para>
+
+<para>In the case in which the size of the data is known upfront, the
+callback can instead create the header with a call to
+<command>cyg_httpd_create_std_header()</command> with the following
+prototype:</para>
+
+<programlisting>
+void cyg_httpd_create_std_header(char *ext, int len);
+
+extension   : the extension used in the search of the MIME type
+len         : length of the data to send out
+</programlisting>
+
+<para>and use
+<command>cyg_httpd_write()</command> to send data out to the client. The
+ prototype of <command>cyg_httpd_write()</command> is the same as 
+<command>cyg_httpd_write_chunked()</command></para></sect1>
+
+<sect1 id="athttpd-cgi">
+<title>CGI</title>
+<para>
+The web server allows writing of pseudo-CGI programs. This is helpful in order
+to modify the functionality of the server without having to recompile it and
+reflash it.</para>
+
+<para>One way to implement CGI is, of course, the C language callback mechanism
+described above: This assumes, of course, that all the callbacks are written
+by compile time and cannot be modified later on. Another way to perform the
+same functionality is the use of a library in the form of an object file. 
+These object files reside in the file system and are loaded, executed and 
+unloaded on demand.</para>
+
+<para>Yet a third way is the use of a scripting language. Since full fledged
+implementation of the most popular scripting languages such as Python or Perl
+are too large for most embedded systems, a slim down implementation of tcl
+was chosen for this server. Most of the tcl functionality is still there,
+and makes writing cgi a lot easier.</para>
+
+<para>In order to limit the footprint of the operating system support for both
+the objloader and the tcl script for dealing with cgi files can be 
+independently selected out. Tcl support in particular increases the memory
+requirements considerably.
+</para>
+
+<sect2 id="athttpd-cgi-objloader">
+<title>CGI via objloader</title>
+<para>
+In order to use the cgi mechanism the CYGPKG_OBJLOADER must be included
+when building the operating system. This will enable the proper option in the
+configuration tool and if selected, the necessary code will be compiled
+in the eCos kernel. The user will then have to compile the necessary libraries
+and place them in the file system under a directory defined by 
+CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR.
+When a request is made, the web server checks if the root directory of the 
+requested URL is inside the CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR directory.
+If so, the server assumes that the user requested a cgi file and looks into the
+directory to see if a library by the same name is present, and if so load it
+and tries to execute a function inside the library with the following prototype:
+</para>
+
+<programlisting width=72>void exec_cgi(CYG_HTTPD_STATE *)
+</programlisting>
+
+<para>
+The pointer <command>CYG_HTTPD_STATE*</command> gives access to the socket 
+data: The user will use this pointer to access the 'outbuffer' and use it to
+copy data to send data out.
+</para>
+
+<para>
+When using the OBJLOADER package within the HTTP server a number of functions 
+are automatically added to the externals table of the OBJLOADER package. These
+functions are likely to be used inside the library and the relocator need to 
+have a pointer to them. In order to add more functions, see the OBJLOADER
+documentation. The complete list of the functions automatically added is:
+</para>
+
+<itemizedlist>
+  <listitem><para>cyg_httpd_start_chunked()</para></listitem>
+  <listitem><para>cyg_httpd_write_chunked()</para></listitem>
+  <listitem><para>cyg_httpd_end_chunked()</para></listitem>
+  <listitem><para>cyg_httpd_write()</para></listitem>
+  <listitem><para>cyg_httpd_find_form_variable()</para></listitem>
+  <listitem><para>cyg_httpd_find_ires()</para></listitem>
+  <listitem><para>cyg_httpd_send_ires()</para></listitem>
+  <listitem><para>diag_printf()</para></listitem>
+  <listitem><para>cyg_httpd_format_header()</para></listitem>
+  <listitem><para>cyg_httpd_find_mime_string()</para></listitem>
+</itemizedlist>
+
+<para>Every time the web client issues a GET or POST request for a file with an 
+extension of '.o'in the /cgi-bin directory (or whatever path the user chooses 
+to hold the libraries) then the library by that name is loaded, run and
+when the execution is over, it is dumped from memory.
+
+The library must be compiled separately, using the same toolchain used to 
+compile the server and then added to the file system.</para>
+
+<para>In order to reduce the footprint of the server, CGI through OBJLOADER
+can be compiled out by unchecking CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER
+in the configuration tool.</para>
+</sect2>
+
+<sect2 id="athttpd-cgi-tcl">
+<title>CGI via the simple tcl interpreter</title>
+<para>A small tcl interpreter has been added to the web server, and it can
+be used to write simple cgi scripts. The interpreter is admittedly very
+minimal, and it is only useful for very simple applications, but it is an
+excellent starting point for further development.</para>
+
+<para>In order for the scripting language to be useful, it has to access
+the form variables passed on during the GET or POST request. Because of
+this, all form variables registered with the CYG_HTTPD_FVAR_TABLE_ENTRY()
+macro are accessible via tcl. For example, if we have registered a
+form variable called foo, and during the GET request we are defining foo
+as being "1":</para>
+
+<programlisting width=72>GET /myForm.cgi?foo=1</programlisting>
+
+<para>then tcl will be able to access the variable foo as $foo. The data
+in the body of a POST request is also accessible through the use of the variable
+$post_data. This is useful if the data is not in "multipart/form-data"
+and tcl has to perform any type of processing on the data itself.</para>
+
+<para>In order to send back a response to the client a few functions have been
+added to the interpreter. These functions are:</para>
+
+<sect3 id="athttpd-start-chunked">
+<title>start_chunked</title>
+<programlisting width=72>start_chunked "extension";</programlisting>
+<para>"extension" is a string used to search the 
+table of the mime types. For example, to send back to the client an HTML file, 
+we can use: start_chunked "html";
+</para>
+</sect3>
+
+<sect3 id="athttpd-write-chunked">
+<title>write_chunked</title>
+<programlisting width=72>write_chunked content;</programlisting>
+<para>content is a string to send back to the client. 
+</para>
+</sect3>
+
+<sect3 id="athttpd-end-chunked">
+<title>end_chunked</title>
+<programlisting width=72>end_chunked;</programlisting>
+<para>No parameters. Send back an end of frame to the client.</para>
+</sect3>
+
+<sect3 id="athttpd-tcl-hello-world">
+<title>tcl hello world example</title>
+<para>
+The following example demonstrates how to send a log file in the file
+<filename>/ram/log</filename> to a web client. It replaces
+newline characters with <literal>&lt;br&gt;</literal> so that it is formatted on the
+browser correctly.
+<programlisting width=72>
+start_chunked "html";
+
+set fp [aio.open "/ram/log" r];
+$fp seek 0 end;
+set fsize [$fp tell];
+$fp seek 0 start;
+set data "abcxxx";
+set data [$fp read $fsize];
+$fp close;
+set data [string map {\n &lt;br&gt;} $data];
+
+set datax "";
+append datax "&lt;html&gt;&lt;body&gt;" $data "&lt;/body&gt;&lt;/html&gt;";
+
+write_chunked $datax;
+end_chunked;
+</programlisting>
+</para>
+<para>
+The above file should exist on a filesystem
+on the embedded target within its <filename class=directory>cgi-bin</filename>
+directory, for example as <filename>/cgi-bin/hello.tcl</filename>. Thereafter
+it may be accessed at the URL
+<literal>http://<replaceable>TARGET_NAME</replaceable>/cgi-bin/hello.tcl</literal>.
+</para>
+</sect3>
+</sect2>
+</sect1>
+
+<sect1 id="athttpd-authentication">
+<title>Authentication</title>
+<para>
+The server supports both Basic (base64) and Digest (MD5) authentication, 
+although they have not been tested with all clients. In this implementation, 
+the contents of certain directories of the file system can be protected, such
+that the user will be required to issue a username/password to access the
+content of the directory.</para>
+
+<para>To protect a directory with a basic authentication, there is a 
+specific macro:</para>
+
+<programlisting>
+CYG_HTTPD_AUTH_TABLE_ENTRY(entry, path, domain, un, pw, mode)
+
+entry            : an identifier unique to this entry.
+path             : the path to the directory whose content must be
+                    authenticated before it is sent out
+domain           : a domain identifier for this directory.
+un               : username for authentication
+pw               : password for authentication
+mode             : CYG_HTTPD_AUTH_BASIC for base64 encoding or 
+                   CYG_HTTPD_AUTH_DIGEST for MD5 encoding
+</programlisting>
+
+<para>for example, to require basic authentication of the content of directory 
+"/ecos/" with a username of "foo" and password "bar", the following is used:
+</para>
+
+<programlisting>
+CYG_HTTPD_AUTH_TABLE_ENTRY(hal_domain1_entry,          \
+                           "/ecos/",    "ecos_domain", \
+                           "foo",       "bar",         \
+                           CYG_HTTPD_AUTH_BASIC);
+</programlisting>
+
+<para>Any request for a file in the directory /ecos/ will now trigger a
+credential check. These credentials, once provided, are automatically sent by
+the client for every request within the particular domain.</para>
+
+<para>It must be noticed that the path name set in the macro is relative to the
+HTML document directory, CYGDAT_NET_HTTPD_SERVEROPT_HTMLDIR and it is the
+first part of the path provided by the client request (including the leading
+slash).</para>
+
+<para>In order to reduce the footprint of the server, authentication
+is not enabled by default, and so the option CYGOPT_NET_ATHTTPD_USE_AUTH must
+be used to enable support for basic and digest authentication.</para>
+
+<para>The MD5 digest authentication support is implemented using the RSA
+Data Security, Inc. MD5 Message-Digest Algorithm. Derivative works with
+MD5 digest authentication included must be identified as "derived from the
+RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work. See the file md5.c within this
+package for license details.</para>
+</sect1>
+
+<sect1 id="athttpd-dirlist">
+<title>Directory Listing</title>
+
+<para>If the user issues a "GET" request with a URL terminating in a slash, the
+server will try to locate one of the following index files in the directory,
+choosing one in the following order:</para>
+
+<itemizedlist>
+  <listitem><para>index.html</para></listitem>
+  <listitem><para>index.htm</para></listitem>
+  <listitem><para>default.html</para></listitem>
+  <listitem><para>home.html</para></listitem>
+</itemizedlist>
+
+<para>If any of these files is found, its contents are sent back
+to the client. If no such file is found the server uses the user-provided
+index file name (if any is specified with the CYGDAT_NET_ATHTTPD_ALTERNATE_HOME
+setting. Failing all this a directory listing is sent.</para>
+
+<para>Trailing slash redirection for directory names is supported.</para>
+
+<para>In order to reduce the footprint of the server, directory listing can
+be disabled by unchecking CYGOPT_NET_ATHTTPD_USE_DIRLIST. The savings are
+substantial since directory listing also makes use of a few internal
+resources (gif files) which are also compiled out.</para>
+</sect1>
+
+<sect1 id="athttpd-formvars">
+<title>Form Variables</title>
+
+<para>The server will automatically try to parse form variables when a form is
+submitted in the following cases:
+
+<itemizedlist>
+  <listitem><para>In a GET request, when the URL is followed by a question
+                  mark sign</para></listitem>
+  <listitem><para>In a POST request, when the the 'Content-Type' header line
+                  is set to 'application/x-www-form-urlencoded'</para></listitem>
+</itemizedlist>
+
+The variable names to look for during the parsing are held in
+an eCos table. In order to take advantage of this feature, the user first
+adds the variable names to the table, which also requires providing a buffer 
+where the parsed value will eventually be stored. The values will then be
+available in the buffers during the processing of the request, presumably in
+the body of a c language callback or CGI script.</para>
+
+<para>For example, if the user wants two form variables, "foo" and "bar", to 
+be parsed automatically, those variable names must be added to the table 
+with the following macro:</para>
+
+<programlisting>
+CYG_HTTPD_FVAR_TABLE_ENTRY(entry, name, buffp, bufflen)
+
+entry            : an identifier unique to this entry.
+name             : name of the form variable
+buffp            : a pointer to a buffer of characters where to store the value
+                   of the form variable.
+bufflen          : The length of the buffer. Must include a trailing string
+                   terminator.
+</programlisting>
+
+<para>or, in the specific instance mentioned above:</para>
+
+<programlisting>
+#define HTML_VAR_LEN   20
+char var_foo[HTML_VAR_LEN];
+char var_bar[HTML_VAR_LEN];
+CYG_HTTPD_FVAR_TABLE_ENTRY(hal_form_entry_foo, "foo", var_foo, HTML_VAR_LEN);
+CYG_HTTPD_FVAR_TABLE_ENTRY(hal_form_entry_bar, "bar", var_bar, HTML_VAR_LEN);
+</programlisting>
+
+<para>and after the GET or POST submissions, the list will contain the value 
+for "foo" and "bar" (if they were found in the form data.) It is the 
+responsability of the user to make sure that the buffer is large enough
+to hold all the data parsed (including the string terminator). The parser will
+write only up to the length of the buffer minus one (the last being the
+terminator) and discard any additional data.</para>
+
+<para>The values parsed are likely going to be used in c language callback, or
+in CGI files. In a c language callback the user can directly access the pointers
+of individual variables for further processing, keeping in mind that the parsing 
+always result in a string of characters to be produced, and any conversion
+(e.g. from strings to integer) must be performed within the callback. In
+a TCL script the user can just access a variable by its name. For example,
+in the case of the variables 'foo' and 'bar' shown above, it is possible
+to do something like 'write_chunked "You wrote $foo". The data that was sent in
+the body of a POST request is accessible in through a variable called
+'post_data'. In CGI functions
+implemented using the objloader the pointers to the
+variables cannot be accessed directly, since the library will likely not
+know their location in memory. The proper way to access them is by using the
+cyg_httpd_find_form_variable() function from within the library:</para>
+
+<programlisting>
+char* cyg_httpd_find_form_variable(char* name)
+
+name             : name of the form variable to look up
+
+returns a pointer to the buffer, or 0 if the variable was not found.
+</programlisting>
+
+<para>When using the OBJLOADER package within the web server, an entry
+for the cyg_httpd_find_form_variable() function is automatically added to the
+externals table the OBJLOADER for relocation. See the OBLOADER paragraph of 
+the ATHTTP user's guide for the full list of the exported functions.</para>
+
+<para>In order to avoid stale data, all the buffers in the table are cleared
+before running the parser and thus any variable in the list that was not
+assigned a new value dureing the request will be an empty string.</para>
+</sect1>
+
+<sect1 id="athttpd-ires">
+<title>Internal Resources</title>
+
+<para>When the server does not use a file system the user must be responsible
+to provide a C language callback function for each URL that will be
+requested by the client. This means locating the data and sending it out
+using either <command>cyg_httpd_write()</command> or
+<command>cyg_httpd_write_chunked()</command>.</para>
+
+<para>In order to simplify this process the server allows registering
+any number of URLs as internal resources, by providing the URL name, the
+pointer to the resource data and its size. When a URL is requested the
+server will look it up among all internal resources, and if found, it
+will send out the resource.</para>
+
+<para>Internal resource can also be used along with a file system. In this
+case the file system is searched first, and if a file is found, it it
+sent. If a file is not found, the internal resources are searched and
+if a match if found it is sent.</para>
+
+<para>The drawback of this approach is, of course, that all these
+resources are going to add to the size of the operating system image, and thus
+it should be used only when memory is not a major constraint of the 
+design.</para>
+
+<para>As always, to provide this type of customization, ecos tables are used.
+The format for adding a new resource to the internal table is the following:
+</para>
+
+<programlisting>
+CYG_HTTPD_IRES_TABLE_ENTRY(entry, name, buffp, len)
+
+entry            : an identifier unique to this entry.
+name             : name of the URL including leading '/'
+buffp            : a pointer to a buffer of characters where to store the value
+                   of the form variable.
+len              : size of the array                   
+</programlisting>
+
+<para>As an example, if the user wants to provide his own web page by
+hardcoding it in the application code, here is how he would do it:</para>
+
+<programlisting>
+#define MY_OWN_HOME_PAGE "eCos RTOS"
+CYG_HTTPD_IRES_TABLE_ENTRY(cyg_httpd_ires_home,       \
+                           "/index.html",             \
+                           MY_OWN_HOME_PAGE,          \
+                           9);
+</programlisting>
+
+<para>The extension of the file name determines the MIME type to be used for
+internal resources.</para>
+
+<para>When using directory listing you are implicitly making use of internal
+resources. The small icons that appear to the left of file names and
+directories are internal resources. Unchecking CYGOPT_NET_HTTP_USE_DIRLIST
+will prevent the addition of these files.</para>
+
+<para>In order to use internal resources, a generic file must first be
+turned into a c language array, which is then compiled in the application
+code. To create this array you can use the tcl script that comes with the
+ecos distribution at packages/fs/rom/current/support/file2.tcl.</para>
+</sect1>
+</chapter>
+</part>
diff --git a/packages/net/athttpd/v2_0/doc/mime_types.txt b/packages/net/athttpd/v2_0/doc/mime_types.txt
new file mode 100644 (file)
index 0000000..f22df57
--- /dev/null
@@ -0,0 +1,202 @@
+// mime_types.txt
+//
+// Because this web server is designed for small, constrained systems, there
+//  is no need to include all different MIME types. They would take up a
+//  considerable amount of memory and they would rarely, if ever, be used 
+//  since in embedded environments the type of web pages is mostly known
+//  upfront and only the MIME types for those pages can me inserted in the table.
+// At any rate, for those of you out there that feel shortchanged, this is a
+//  fairly long list of MIME types that I found out there. If you need any
+//  of them, add them to the mime table using the CYG_HTTPD_MIME_TABLE_ENTRY()
+//  macro.
+
+a       application/octet-stream
+aab     application/x-authorware-bin
+aam     application/x-authorware-map
+aas     application/x-authorware-seg
+ai      application/postscript
+aif     audio/x-aiff
+aifc    audio/x-aiff
+aiff    audio/x-aiff
+asc     text/plain
+asf     video/x-ms-asf
+asx     video/x-ms-asf
+au      audio/basic
+avi     video/x-msvideo
+bcpio   application/x-bcpio
+bin     application/octet-stream
+bmp     image/bmp
+cdf     application/x-netcdf
+class   application/x-java-vm
+cpio    application/x-cpio
+cpt     application/mac-compactpro
+crl     application/x-pkcs7-crl
+crt     application/x-x509-ca-cert
+csh     application/x-csh
+css     text/css
+dcr     application/x-director
+dir     application/x-director
+djv     image/vnd.djvu
+djvu    image/vnd.djvu
+dll     application/octet-stream
+dms     application/octet-stream
+doc     application/msword
+dtd     text/xml
+dump    application/octet-stream
+dvi     application/x-dvi
+dxr     application/x-director
+eps     application/postscript
+etx     text/x-setext
+exe     application/octet-stream
+ez      application/andrew-inset
+fgd     application/x-director
+fh      image/x-freehand
+fh4     image/x-freehand
+fh5     image/x-freehand
+fh7     image/x-freehand
+fhc     image/x-freehand
+gif     image/gif
+gtar    application/x-gtar
+hdf     application/x-hdf
+hqx     application/mac-binhex40
+htm     text/html; charset=%s
+html    text/html; charset=%s
+ice     x-conference/x-cooltalk
+ief     image/ief
+iges    model/iges
+igs     model/iges
+iv      application/x-inventor
+jar     application/x-java-archive
+jfif    image/jpeg
+jpe     image/jpeg
+jpeg    image/jpeg
+jpg     image/jpeg
+js      application/x-javascript
+kar     audio/midi
+latex   application/x-latex
+lha     application/octet-stream
+lzh     application/octet-stream
+m3u     audio/x-mpegurl
+man     application/x-troff-man
+mathml  application/mathml+xml
+me      application/x-troff-me
+mesh    model/mesh
+mid     audio/midi
+midi    audio/midi
+mif     application/vnd.mif
+mime    message/rfc822
+mml     application/mathml+xml
+mov     video/quicktime
+movie   video/x-sgi-movie
+mp2     audio/mpeg
+mp3     audio/mpeg
+mp4     video/mp4
+mpe     video/mpeg
+mpeg    video/mpeg
+mpg     video/mpeg
+mpga    audio/mpeg
+ms      application/x-troff-ms
+msh     model/mesh
+mv      video/x-sgi-movie
+mxu     video/vnd.mpegurl
+nc      application/x-netcdf
+o       application/octet-stream
+oda     application/oda
+ogg     application/x-ogg
+pac     application/x-ns-proxy-autoconfig
+pbm     image/x-portable-bitmap
+pdb     chemical/x-pdb
+pdf     application/pdf
+pgm     image/x-portable-graymap
+pgn     application/x-chess-pgn
+png     image/png
+pnm     image/x-portable-anymap
+ppm     image/x-portable-pixmap
+ppt     application/vnd.ms-powerpoint
+ps      application/postscript
+qt      video/quicktime
+ra      audio/x-realaudio
+ram     audio/x-pn-realaudio
+ras     image/x-cmu-raster
+rdf     application/rdf+xml
+rgb     image/x-rgb
+rm      audio/x-pn-realaudio
+roff    application/x-troff
+rpm     audio/x-pn-realaudio-plugin
+rss     application/rss+xml
+rtf     text/rtf
+rtx     text/richtext
+sgm     text/sgml
+sgml    text/sgml
+sh      application/x-sh
+shar    application/x-shar
+silo    model/mesh
+sit     application/x-stuffit
+skd     application/x-koan
+skm     application/x-koan
+skp     application/x-koan
+skt     application/x-koan
+smi     application/smil
+smil    application/smil
+snd     audio/basic
+so      application/octet-stream
+spl     application/x-futuresplash
+src     application/x-wais-source
+stc     application/vnd.sun.xml.calc.template
+std     application/vnd.sun.xml.draw.template
+sti     application/vnd.sun.xml.impress.template
+stw     application/vnd.sun.xml.writer.template
+sv4cpio application/x-sv4cpio
+sv4crc  application/x-sv4crc
+svg     image/svg+xml
+svgz    image/svg+xml
+swf     application/x-shockwave-flash
+sxc     application/vnd.sun.xml.calc
+sxd     application/vnd.sun.xml.draw
+sxg     application/vnd.sun.xml.writer.global
+sxi     application/vnd.sun.xml.impress
+sxm     application/vnd.sun.xml.math
+sxw     application/vnd.sun.xml.writer
+t       application/x-troff
+tar     application/x-tar
+tcl     application/x-tcl
+tex     application/x-tex
+texi    application/x-texinfo
+texinfo application/x-texinfo
+tif     image/tiff
+tiff    image/tiff
+tr      application/x-troff
+tsp     application/dsptype
+tsv     text/tab-separated-values
+txt     text/plain; charset=%s
+ustar   application/x-ustar
+vcd     application/x-cdlink
+vrml    model/vrml
+vx      video/x-rad-screenplay
+wav     audio/x-wav
+wax     audio/x-ms-wax
+wbmp    image/vnd.wap.wbmp
+wbxml   application/vnd.wap.wbxml
+wm      video/x-ms-wm
+wma     audio/x-ms-wma
+wmd     application/x-ms-wmd
+wml     text/vnd.wap.wml
+wmlc    application/vnd.wap.wmlc
+wmls    text/vnd.wap.wmlscript
+wmlsc   application/vnd.wap.wmlscriptc
+wmv     video/x-ms-wmv
+wmx     video/x-ms-wmx
+wmz     application/x-ms-wmz
+wrl     model/vrml
+wsrc    application/x-wais-source
+wvx     video/x-ms-wvx
+xbm     image/x-xbitmap
+xht     application/xhtml+xml
+xhtml   application/xhtml+xml
+xls     application/vnd.ms-excel
+xml     text/xml
+xpm     image/x-xpixmap
+xsl     text/xml
+xwd     image/x-xwindowdump
+xyz     chemical/x-xyz
+zip     application/zip
diff --git a/packages/net/athttpd/v2_0/include/auth.h b/packages/net/athttpd/v2_0/include/auth.h
new file mode 100644 (file)
index 0000000..062bd8c
--- /dev/null
@@ -0,0 +1,127 @@
+/* =================================================================
+ *
+ *      auth.h
+ *
+ *      Improved HTTPD server.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#ifndef __AUTH_H__
+#define __AUTH_H__
+
+#include <pkgconf/system.h>
+#include <pkgconf/isoinfra.h>
+#include <cyg/hal/hal_tables.h>
+
+#define badchar(c,p) (!(p = memchr(b64string, c, 64)))
+
+extern cyg_uint8 *cyg_httpd_current_authName;
+
+typedef enum cyg_httpd_auth_type
+{
+    CYG_HTTPD_AUTH_BASIC = 0, 
+    CYG_HTTPD_AUTH_DIGEST = 1
+} cyg_httpd_auth_type;
+
+#define AUTH_STORAGE_BUFFER_LENGTH_LOGIN             32
+#define AUTH_STORAGE_BUFFER_LENGTH_PASSWORD          32
+#define AUTH_STORAGE_BUFFER_LENGTH        (AUTH_STORAGE_BUFFER_LENGTH_LOGIN +\
+                                           AUTH_STORAGE_BUFFER_LENGTH_PASSWORD)
+// It must be stressed that the auth_dirname field is the directory name
+//  that will be requested by the web server, and _not_ the absolute name
+//  in the eCos file system. 
+// Lets' make an example. Let's say that the files of your web site reside in 
+//  the directory '/fs/jffs2/html'. Your CYG_HTTPD_DEFAULT_PATH will likely be
+//  set to '/fs/jffs2/' and the CYG_HTTPD_DEFAULT_HTML_DIR will likely be
+//  set to 'html/'. The web server will then request a file 
+//  (i.e. 'images/foo.jpg') whose absolute location in the eCos file system is
+//  '/fs/jffs2/html/images/foo.jpg', and if we want to protect the 'images/'
+//  directory with some kind of authentication, the auth_dirname must be 
+//  pointing to a string such as "images/".
+struct cyg_httpd_auth_table_entry
+{
+    char                *auth_dirname;
+    char                *auth_domainname;
+    char                *auth_username;
+    char                *auth_password;
+    cyg_httpd_auth_type  auth_mode;
+} CYG_HAL_TABLE_TYPE;
+
+typedef struct cyg_httpd_auth_table_entry cyg_httpd_auth_table_entry;
+#define CYG_HTTPD_AUTH_TABLE_ENTRY( __name, __path, __domain, __un, __pw, __mode )  \
+ cyg_httpd_auth_table_entry __name CYG_HAL_TABLE_ENTRY( httpd_auth_table ) =  \
+                             { __path, __domain, __un, __pw, __mode } 
+
+cyg_httpd_auth_table_entry* cyg_httpd_auth_entry_from_path(char *);
+cyg_httpd_auth_table_entry* cyg_httpd_auth_entry_from_domain(char *);
+cyg_httpd_auth_table_entry* cyg_httpd_is_authenticated(char*);
+char* cyg_httpd_digest_data(char *, char *);
+char* cyg_httpd_digest_skip(char *);
+
+// The following code is a slightly modified version of those available at the
+//  end of RFC1270.
+#define HASHLEN 16
+typedef char HASH[HASHLEN];
+#define HASHHEXLEN 32
+typedef char HASHHEX[HASHHEXLEN+1];
+
+//extern char cyg_httpd_md5_username[];
+//extern char cyg_httpd_md5_opaque[];
+//extern char cyg_httpd_md5_alg[];
+//extern char cyg_httpd_md5_realm[];
+extern char cyg_httpd_md5_nonce[];
+extern char cyg_httpd_md5_cnonce[];
+extern char cyg_httpd_md5_digest[];
+extern char cyg_httpd_md5_qop[];
+extern char cyg_httpd_md5_response[];
+extern char cyg_httpd_md5_noncecount[];
+extern char cyg_httpd_md5_ha2[];
+extern char cyg_httpd_md5_ha1[];
+
+#endif // __AUTH_H__
diff --git a/packages/net/athttpd/v2_0/include/cgi.h b/packages/net/athttpd/v2_0/include/cgi.h
new file mode 100644 (file)
index 0000000..1e81d9e
--- /dev/null
@@ -0,0 +1,61 @@
+/* =================================================================
+ *
+ *      cgi.h
+ *
+ *      
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#ifndef __CGI_H__
+#define __CGI_H__
+
+cyg_int32 cyg_httpd_exec_cgi(void);
+void cyg_httpd_init_tcl_interpreter(void);
+
+#endif
diff --git a/packages/net/athttpd/v2_0/include/digcalc.h b/packages/net/athttpd/v2_0/include/digcalc.h
new file mode 100644 (file)
index 0000000..e7d53b3
--- /dev/null
@@ -0,0 +1,30 @@
+#define HASHLEN 16
+typedef char HASH[HASHLEN];
+#define HASHHEXLEN 32
+typedef char HASHHEX[HASHHEXLEN+1];
+#define IN
+#define OUT
+
+/* calculate H(A1) as per HTTP Digest spec */
+void DigestCalcHA1(
+    IN char * pszAlg,
+    IN char * pszUserName,
+    IN char * pszRealm,
+    IN char * pszPassword,
+    IN char * pszNonce,
+    IN char * pszCNonce,
+    OUT HASHHEX SessionKey
+    );
+
+/* calculate request-digest/response-digest as per HTTP Digest spec */
+void DigestCalcResponse(
+    IN HASHHEX HA1,           /* H(A1) */
+    IN char * pszNonce,       /* nonce from server */
+    IN char * pszNonceCount,  /* 8 hex digits */
+    IN char * pszCNonce,      /* client nonce */
+    IN char * pszQop,         /* qop-value: "", "auth", "auth-int" */
+    IN char * pszMethod,      /* method from the request */
+    IN char * pszDigestUri,   /* requested URL */
+    IN HASHHEX HEntity,       /* H(entity body) if qop="auth-int" */
+    OUT HASHHEX Response      /* request-digest or response-digest */
+    );
diff --git a/packages/net/athttpd/v2_0/include/forms.h b/packages/net/athttpd/v2_0/include/forms.h
new file mode 100644 (file)
index 0000000..1a1794b
--- /dev/null
@@ -0,0 +1,79 @@
+/* =================================================================
+ *
+ *      forms.h
+ *
+ *      Improved HTTPD server.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#ifndef __FORMS_H__
+#define __FORMS_H__
+
+struct cyg_httpd_fvars_table_entry
+{
+    char *name;
+    char *buf; 
+    int  buflen; 
+} CYG_HAL_TABLE_TYPE;
+
+typedef struct cyg_httpd_fvars_table_entry cyg_httpd_fvars_table_entry;
+
+#define CYG_HTTPD_FVAR_TABLE_ENTRY(__name, __fvar, __val, __len) \
+cyg_httpd_fvars_table_entry __name CYG_HAL_TABLE_ENTRY( httpd_fvars_table ) = \
+                                                      {__fvar, __val, __len} 
+
+__externC cyg_httpd_fvars_table_entry cyg_httpd_fvars_table[];
+__externC cyg_httpd_fvars_table_entry cyg_httpd_fvars_table_end[];
+
+// Prototypes.
+char *cyg_httpd_store_form_data(char*);
+void cyg_httpd_handle_method_POST(void);
+cyg_int8 cyg_httpd_from_hex (cyg_int8);
+char *cyg_httpd_find_form_variable(char*);
+#endif
diff --git a/packages/net/athttpd/v2_0/include/global.h b/packages/net/athttpd/v2_0/include/global.h
new file mode 100644 (file)
index 0000000..e6c689c
--- /dev/null
@@ -0,0 +1,35 @@
+#ifndef __GLOBAL_H__
+#define __GLOBAL_H__
+
+/* GLOBAL.H - RSAREF types and constants
+ */
+
+/* PROTOTYPES should be set to one if and only if the compiler supports
+  function argument prototyping.
+The following makes PROTOTYPES default to 0 if it has not already
+  been defined with C compiler flags.
+ */
+#ifndef PROTOTYPES
+#define PROTOTYPES 0
+#endif
+
+/* POINTER defines a generic pointer type */
+typedef unsigned char *POINTER;
+
+/* UINT2 defines a two byte word */
+typedef unsigned short int UINT2;
+
+/* UINT4 defines a four byte word */
+typedef unsigned long int UINT4;
+
+/* PROTO_LIST is defined depending on how PROTOTYPES is defined above.
+If using PROTOTYPES, then PROTO_LIST returns the list, otherwise it
+  returns an empty list.
+ */
+#if PROTOTYPES
+#define PROTO_LIST(list) list
+#else
+#define PROTO_LIST(list) ()
+#endif
+
+#endif
diff --git a/packages/net/athttpd/v2_0/include/handler.h b/packages/net/athttpd/v2_0/include/handler.h
new file mode 100644 (file)
index 0000000..028be12
--- /dev/null
@@ -0,0 +1,99 @@
+/* =================================================================
+ *
+ *      handler.h
+ *
+ *      Improved HTTPD server.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#ifndef __HANDLER_H__
+#define __HANDLER_H__
+
+// =============================================================================
+// Internal Resources
+// =============================================================================
+struct cyg_httpd_ires_table_entry
+{
+    char *f_pname;
+    char *f_ptr;
+    int   f_size; 
+} CYG_HAL_TABLE_TYPE;
+
+typedef struct cyg_httpd_ires_table_entry cyg_httpd_ires_table_entry;
+
+#define CYG_HTTPD_IRES_TABLE_ENTRY(__name, __path_name, __pmem, __size) \
+cyg_httpd_ires_table_entry __name \
+   CYG_HAL_TABLE_ENTRY(httpd_ires_table) = {(char*)__path_name, \
+                                            (char*)__pmem, (int)__size} 
+      
+cyg_httpd_ires_table_entry *cyg_httpd_find_ires(char *);
+void cyg_httpd_send_ires(cyg_httpd_ires_table_entry *);
+
+// =============================================================================
+// C callbacks
+// =============================================================================
+typedef cyg_int32  (*handler)(CYG_HTTPD_STATE*);
+struct cyg_httpd_handler_table_entry
+{
+    char     *path;
+    handler   h;
+} CYG_HAL_TABLE_TYPE;
+
+typedef struct cyg_httpd_handler_table_entry cyg_httpd_handler_table_entry;
+
+#define CYG_HTTPD_HANDLER_TABLE_ENTRY(__name, __pattern, __arg) \
+cyg_httpd_handler_table_entry __name \
+      CYG_HAL_TABLE_ENTRY(httpd_handler_table) = { __pattern, __arg } 
+
+handler cyg_httpd_find_handler(void);
+cyg_int32 cyg_httpd_exec_cgi(void);
+void cyg_httpd_send_directory_listing(char*);
+
+#endif
+
diff --git a/packages/net/athttpd/v2_0/include/http.h b/packages/net/athttpd/v2_0/include/http.h
new file mode 100644 (file)
index 0000000..112c654
--- /dev/null
@@ -0,0 +1,226 @@
+/* =================================================================
+ *
+ *      http.h
+ *
+ *      Improved HTTPD server.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#ifndef __HTTP_H__
+#define __HTTP_H__
+
+#include <pkgconf/system.h>
+#include <pkgconf/isoinfra.h>
+#include <cyg/hal/hal_tables.h>
+
+#include <pkgconf/athttpd.h>
+#include <cyg/athttpd/auth.h>
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL
+#include <cyg/athttpd/jim.h>
+#endif
+
+
+typedef enum cyg_httpd_req_type
+{
+    CYG_HTTPD_METHOD_GET  = 1,
+    CYG_HTTPD_METHOD_HEAD = 2,
+    CYG_HTTPD_METHOD_POST = 3
+} cyg_httpd_req_type;
+
+#define CYG_HTTPD_MAXURL                    128
+#define CYG_HTTPD_MAXPATH                   128
+
+#define CYG_HTTPD_MAXINBUFFER               CYGNUM_ATHTTPD_SERVER_BUFFER_SIZE
+#define CYG_HTTPD_MAXOUTBUFFER              CYGNUM_ATHTTPD_SERVER_BUFFER_SIZE
+
+#define CYG_HTTPD_DEFAULT_CGIBIN_OBJLOADER_EXTENSION ".o"
+#define CYG_HTTPD_DEFAULT_CGIBIN_TCL_EXTENSION       ".tcl"
+
+#define CYG_HTTPD_TIME_STRING_LEN                 32
+
+#define CYG_HTTPD_STATUS_OK                      200
+#define CYG_HTTPD_STATUS_MOVED_PERMANENTLY       301
+#define CYG_HTTPD_STATUS_MOVED_TEMPORARILY       302
+#define CYG_HTTPD_STATUS_NOT_MODIFIED            304
+#define CYG_HTTPD_STATUS_BAD_REQUEST             400
+#define CYG_HTTPD_STATUS_NOT_AUTHORIZED          401
+#define CYG_HTTPD_STATUS_FORBIDDEN               403
+#define CYG_HTTPD_STATUS_NOT_FOUND               404
+#define CYG_HTTPD_STATUS_METHOD_NOT_ALLOWED      405
+#define CYG_HTTPD_STATUS_SYSTEM_ERROR            500
+#define CYG_HTTPD_STATUS_NOT_IMPLEMENTED         501
+
+#define CYG_HTTPD_MODE_CLOSE_CONN             0x0001
+#define CYG_HTTPD_MODE_TRANSFER_CHUNKED       0x0002
+#define CYG_HTTPD_MODE_SEND_HEADER_ONLY       0x0004
+#define CYG_HTTPD_MODE_NO_CACHE               0x0008
+#define CYG_HTTPD_MODE_FORM_DATA              0x0010
+
+// This must be generated at random...
+#define CYG_HTTPD_MD5_AUTH_NAME                "MD5"
+#define CYG_HTTPD_MD5_AUTH_QOP                 "auth"
+#define CYG_HTTPD_MD5_AUTH_OPAQUE              "0000000000000000"
+
+#define TIME_FORMAT_RFC1123                    "%a, %d %b %Y %H:%H:%S GMT"
+
+typedef struct __socket_entry
+{
+    cyg_int32 descriptor;
+    time_t    timestamp;
+} socket_entry; 
+
+// =============================================================================
+// Main HTTP structure.
+// =============================================================================
+typedef struct
+{
+    cyg_httpd_req_type method;    
+    fd_set       rfds;
+
+    cyg_int32    host[4];
+
+    char         url[CYG_HTTPD_MAXURL+1];
+    char         inbuffer[CYG_HTTPD_MAXINBUFFER+1];
+    cyg_int32    inbuffer_len, content_len;
+    
+    // Packet status.
+    //
+    //   bit      Description
+    // -------------------------------------------------------------------------
+    //    0       A 1 means that the connection will be closed after the request
+    //             has been served (i.e. Connection: close" will appear in
+    //             the header. Otherwise the connection will be kept alive
+    //             "Connection: keep-alive"
+    //    1       Set when the transfer will be chunked
+    //    2       Set when the we need to send only the header
+    //    3       Set when the we do not want this document to be cached (i.e.
+    //             "Cache-Control: no-cache" will appear in the header) which
+    //             is meant for c language callbacks and GCI.
+    //    4       Set when the the frame we just received contains form data.
+    //             In this case we call the function that parsed the data into
+    //             user-defined form variables.
+    cyg_uint16   mode;
+    
+    // Ouptut data.
+    cyg_uint16   status_code;
+    char        *mime_type;
+    cyg_int32    payload_len;
+    char         outbuffer[CYG_HTTPD_MAXOUTBUFFER+1];
+    
+    socket_entry sockets[CYGPKG_NET_MAXSOCKETS];
+    cyg_int32    fdmax;
+    
+    // Socket handle.
+    cyg_int32    client_index;
+
+    // Modified-since is always reset to -1 before parsing the headers of a
+    //  request. If the "Modified-Since" element is present in the header then
+    //  we'll copy the value in this variable, otherwise it will remain to -1.
+    // This will tell us if we can send a CYG_HTTPD_STATUS_NOT_MODIFIED back to
+    //  the client or instead we'll have to send the whole page again.
+    time_t       modified_since;
+    time_t       last_modified;
+    
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL
+    Jim_Interp *jim_interp;
+#endif    
+
+    // Pointer to the data immediately following the last byte of the header.
+    // In a POST request, this is where the goods are. After the post request
+    //  is handles it will point to the start of the new request, if any.
+    char        *request_end;
+
+    // This pointer points to the buffer where we collected all the post
+    //  data (it might come in more than one frame)  and must be visible to
+    //  handlers and cgi scripts.
+    char        *post_data;
+
+    // This pointer points to the information about the domain that needs
+    //  to be authenticated. It is only used by the function that builds the
+    //  header.
+    cyg_httpd_auth_table_entry *needs_auth;
+
+    struct sockaddr_in server_conn;
+    struct sockaddr_in client_conn;
+} CYG_HTTPD_STATE;
+
+extern CYG_HTTPD_STATE httpstate;
+
+extern const char *day_of_week[];
+extern const char *month_of_year[]; 
+
+struct cyg_httpd_mime_table_entry
+{
+    char *extension;
+    char *mime_string;
+} CYG_HAL_TABLE_TYPE;
+
+typedef struct cyg_httpd_mime_table_entry cyg_httpd_mime_table_entry;
+
+#define CYG_HTTPD_MIME_TABLE_ENTRY(__name, __pattern, __arg) \
+cyg_httpd_mime_table_entry __name CYG_HAL_TABLE_ENTRY(httpd_mime_table) = \
+                                                          { __pattern, __arg } 
+
+extern cyg_int32 debug_print;
+
+void cyg_httpd_set_home_page(cyg_int8*);
+char* cyg_httpd_find_mime_string(char*);
+cyg_int32 cyg_httpd_initialize(void);
+void cyg_httpd_cleanup_filename(char*);
+char* cyg_httpd_parse_GET(char*);
+char* cyg_httpd_parse_POST(char*);
+void cyg_httpd_handle_method_GET(void);
+void cyg_httpd_handle_method_HEAD(void);
+void cyg_httpd_process_method(void);
+void cyg_httpd_send_file(char*);
+void cyg_httpd_send_error(cyg_int32);
+cyg_int32 cyg_httpd_format_header(void);
+
+#endif
diff --git a/packages/net/athttpd/v2_0/include/jim.h b/packages/net/athttpd/v2_0/include/jim.h
new file mode 100644 (file)
index 0000000..8ce202d
--- /dev/null
@@ -0,0 +1,954 @@
+/* Jim - A small embeddable Tcl interpreter
+ * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
+ * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
+ *
+ * $Id$
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * A copy of the license is also included in the source distribution
+ * of Jim, as a TXT file name called LICENSE.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __JIM__H
+#define __JIM__H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <time.h>
+#include <limits.h>
+#include <stdio.h>  /* for the FILE typedef definition */
+#include <stdlib.h> /* In order to export the Jim_Free() macro */
+
+/* -----------------------------------------------------------------------------
+* Some /very/ old compiler maybe do not know how to
+* handle 'const'. They even do not know, how to ignore
+* it. For those compiler it may be better to compile with
+* define JIM_NO_CONST activated
+* ---------------------------------------------------------------------------*/
+
+#ifdef JIM_NO_CONST
+#  define const
+#endif
+
+/* -----------------------------------------------------------------------------
+ * System configuration
+ * For most modern systems, you can leave the default.
+ * For embedded systems some change may be required.
+ * ---------------------------------------------------------------------------*/
+
+#define HAVE_LONG_LONG
+
+/* -----------------------------------------------------------------------------
+ * Compiler specific fixes.
+ * ---------------------------------------------------------------------------*/
+
+/* MSC has _stricmp instead of strcasecmp */
+#ifdef _MSC_VER
+#  define strcasecmp _stricmp
+#endif /* _MSC_VER */
+
+/* Long Long type and related issues */
+#ifdef HAVE_LONG_LONG
+#  ifdef _MSC_VER /* MSC compiler */
+#    define jim_wide _int64
+#    ifndef LLONG_MAX
+#      define LLONG_MAX    9223372036854775807I64
+#    endif
+#    ifndef LLONG_MIN
+#      define LLONG_MIN    (-LLONG_MAX - 1I64)
+#    endif
+#    define JIM_WIDE_MIN LLONG_MIN
+#    define JIM_WIDE_MAX LLONG_MAX
+#  else /* Other compilers (mainly GCC) */
+#    define jim_wide long long
+#    ifndef LLONG_MAX
+#      define LLONG_MAX    9223372036854775807LL
+#    endif
+#    ifndef LLONG_MIN
+#      define LLONG_MIN    (-LLONG_MAX - 1LL)
+#    endif
+#    define JIM_WIDE_MIN LLONG_MIN
+#    define JIM_WIDE_MAX LLONG_MAX
+#  endif
+#else
+#  define jim_wide long
+#  define JIM_WIDE_MIN LONG_MIN
+#  define JIM_WIDE_MAX LONG_MAX
+#endif
+
+/* -----------------------------------------------------------------------------
+ * LIBC specific fixes
+ * ---------------------------------------------------------------------------*/
+
+#ifdef HAVE_LONG_LONG
+# if defined(_MSC_VER) || defined(__MSVCRT__)
+#    define JIM_WIDE_MODIFIER "I64d"
+# else
+#    define JIM_WIDE_MODIFIER "lld"
+# endif
+#else
+#    define JIM_WIDE_MODIFIER "ld"
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Exported defines
+ * ---------------------------------------------------------------------------*/
+
+/* Jim version numbering: every version of jim is marked with a
+ * successive integer number. This is version 0. The first
+ * stable version will be 1, then 2, 3, and so on. */
+#define JIM_VERSION 51
+
+#define JIM_OK 0
+#define JIM_ERR 1
+#define JIM_RETURN 2
+#define JIM_BREAK 3
+#define JIM_CONTINUE 4
+#define JIM_EVAL 5
+#define JIM_EXIT 6
+#define JIM_MAX_NESTING_DEPTH 10000 /* default max nesting depth */
+
+/* Some function get an integer argument with flags to change
+ * the behaviour. */
+#define JIM_NONE 0    /* no flags set */
+#define JIM_ERRMSG 1    /* set an error message in the interpreter. */
+
+/* Flags for Jim_SubstObj() */
+#define JIM_SUBST_NOVAR 1 /* don't perform variables substitutions */
+#define JIM_SUBST_NOCMD 2 /* don't perform command substitutions */
+#define JIM_SUBST_NOESC 4 /* don't perform escapes substitutions */
+
+/* Unused arguments generate annoying warnings... */
+#define JIM_NOTUSED(V) ((void) V)
+
+/* Flags used by API calls getting a 'nocase' argument. */
+#define JIM_CASESENS    0   /* case sensitive */
+#define JIM_NOCASE      1   /* no case */
+
+/* Filesystem related */
+#define JIM_PATH_LEN 1024
+
+/* Newline, some embedded system may need -DJIM_CRLF */
+#ifdef JIM_CRLF
+#define JIM_NL "\r\n"
+#else
+#define JIM_NL "\n"
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Stack
+ * ---------------------------------------------------------------------------*/
+
+typedef struct Jim_Stack {
+    int len;
+    int maxlen;
+    void **vector;
+} Jim_Stack;
+
+/* -----------------------------------------------------------------------------
+ * Hash table
+ * ---------------------------------------------------------------------------*/
+
+typedef struct Jim_HashEntry {
+    const void *key;
+    void *val;
+    struct Jim_HashEntry *next;
+} Jim_HashEntry;
+
+typedef struct Jim_HashTableType {
+    unsigned int (*hashFunction)(const void *key);
+    const void *(*keyDup)(void *privdata, const void *key);
+    void *(*valDup)(void *privdata, const void *obj);
+    int (*keyCompare)(void *privdata, const void *key1, const void *key2);
+    void (*keyDestructor)(void *privdata, const void *key);
+    void (*valDestructor)(void *privdata, void *obj);
+} Jim_HashTableType;
+
+typedef struct Jim_HashTable {
+    Jim_HashEntry **table;
+    Jim_HashTableType *type;
+    unsigned int size;
+    unsigned int sizemask;
+    unsigned int used;
+    unsigned int collisions;
+    void *privdata;
+} Jim_HashTable;
+
+typedef struct Jim_HashTableIterator {
+    Jim_HashTable *ht;
+    int index;
+    Jim_HashEntry *entry, *nextEntry;
+} Jim_HashTableIterator;
+
+/* This is the initial size of every hash table */
+#define JIM_HT_INITIAL_SIZE     16
+
+/* ------------------------------- Macros ------------------------------------*/
+#define Jim_FreeEntryVal(ht, entry) \
+    if ((ht)->type->valDestructor) \
+        (ht)->type->valDestructor((ht)->privdata, (entry)->val)
+
+#define Jim_SetHashVal(ht, entry, _val_) do { \
+    if ((ht)->type->valDup) \
+        entry->val = (ht)->type->valDup((ht)->privdata, _val_); \
+    else \
+        entry->val = (_val_); \
+} while(0)
+
+#define Jim_FreeEntryKey(ht, entry) \
+    if ((ht)->type->keyDestructor) \
+        (ht)->type->keyDestructor((ht)->privdata, (entry)->key)
+
+#define Jim_SetHashKey(ht, entry, _key_) do { \
+    if ((ht)->type->keyDup) \
+        entry->key = (ht)->type->keyDup((ht)->privdata, _key_); \
+    else \
+        entry->key = (_key_); \
+} while(0)
+
+#define Jim_CompareHashKeys(ht, key1, key2) \
+    (((ht)->type->keyCompare) ? \
+        (ht)->type->keyCompare((ht)->privdata, key1, key2) : \
+        (key1) == (key2))
+
+#define Jim_HashKey(ht, key) (ht)->type->hashFunction(key)
+
+#define Jim_GetHashEntryKey(he) ((he)->key)
+#define Jim_GetHashEntryVal(he) ((he)->val)
+#define Jim_GetHashTableCollisions(ht) ((ht)->collisions)
+#define Jim_GetHashTableSize(ht) ((ht)->size)
+#define Jim_GetHashTableUsed(ht) ((ht)->used)
+
+/* -----------------------------------------------------------------------------
+ * Jim_Obj structure
+ * ---------------------------------------------------------------------------*/
+
+/* -----------------------------------------------------------------------------
+ * Jim object. This is mostly the same as Tcl_Obj itself,
+ * with the addition of the 'prev' and 'next' pointers.
+ * In Jim all the objects are stored into a linked list for GC purposes,
+ * so that it's possible to access every object living in a given interpreter
+ * sequentially. When an object is freed, it's moved into a different
+ * linked list, used as object pool.
+ *
+ * The refcount of a freed object is always -1.
+ * ---------------------------------------------------------------------------*/
+typedef struct Jim_Obj {
+    int refCount; /* reference count */
+    char *bytes; /* string representation buffer. NULL = no string repr. */
+    int length; /* number of bytes in 'bytes', not including the numterm. */
+    struct Jim_ObjType *typePtr; /* object type. */
+    /* Internal representation union */
+    union {
+        /* integer number type */
+        jim_wide wideValue;
+        /* hashed object type value */
+        int hashValue;
+        /* index type */
+        int indexValue;
+        /* return code type */
+        int returnCode;
+        /* double number type */
+        double doubleValue;
+        /* Generic pointer */
+        void *ptr;
+        /* Generic two pointers value */
+        struct {
+            void *ptr1;
+            void *ptr2;
+        } twoPtrValue;
+        /* Variable object */
+        struct {
+            unsigned jim_wide callFrameId;
+            struct Jim_Var *varPtr;
+        } varValue;
+        /* Command object */
+        struct {
+            unsigned jim_wide procEpoch;
+            struct Jim_Cmd *cmdPtr;
+        } cmdValue;
+        /* List object */
+        struct {
+            struct Jim_Obj **ele;    /* Elements vector */
+            int len;        /* Length */
+            int maxLen;        /* Allocated 'ele' length */
+        } listValue;
+        /* String type */
+        struct {
+            int maxLength;
+        } strValue;
+        /* Reference type */
+        struct {
+            jim_wide id;
+            struct Jim_Reference *refPtr;
+        } refValue;
+        /* Source type */
+        struct {
+            const char *fileName;
+            int lineNumber;
+        } sourceValue;
+        /* Dict substitution type */
+        struct {
+            struct Jim_Obj *varNameObjPtr;
+            struct Jim_Obj *indexObjPtr;
+        } dictSubstValue;
+        /* tagged binary type */
+        struct {
+            unsigned char *data;
+            size_t         len;
+        } binaryValue;
+    } internalRep;
+    /* This are 8 or 16 bytes more for every object
+     * but this is required for efficient garbage collection
+     * of Jim references. */
+    struct Jim_Obj *prevObjPtr; /* pointer to the prev object. */
+    struct Jim_Obj *nextObjPtr; /* pointer to the next object. */
+} Jim_Obj;
+
+/* Jim_Obj related macros */
+#define Jim_IncrRefCount(objPtr) \
+    ++(objPtr)->refCount
+#define Jim_DecrRefCount(interp, objPtr) \
+    if (--(objPtr)->refCount <= 0) Jim_FreeObj(interp, objPtr)
+#define Jim_IsShared(objPtr) \
+    ((objPtr)->refCount > 1)
+
+/* This macro is used when we allocate a new object using
+ * Jim_New...Obj(), but for some error we need to destroy it.
+ * Instead to use Jim_IncrRefCount() + Jim_DecrRefCount() we
+ * can just call Jim_FreeNewObj. To call Jim_Free directly
+ * seems too raw, the object handling may change and we want
+ * that Jim_FreeNewObj() can be called only against objects
+ * that are belived to have refcount == 0. */
+#define Jim_FreeNewObj Jim_FreeObj
+
+/* Free the internal representation of the object. */
+#define Jim_FreeIntRep(i,o) \
+    if ((o)->typePtr && (o)->typePtr->freeIntRepProc) \
+        (o)->typePtr->freeIntRepProc(i, o)
+
+/* Get the internal representation pointer */
+#define Jim_GetIntRepPtr(o) (o)->internalRep.ptr
+
+/* Set the internal representation pointer */
+#define Jim_SetIntRepPtr(o, p) \
+    (o)->internalRep.ptr = (p)
+
+/* The object type structure.
+ * There are four methods.
+ *
+ * - FreeIntRep is used to free the internal representation of the object.
+ *   Can be NULL if there is nothing to free.
+ * - DupIntRep is used to duplicate the internal representation of the object.
+ *   If NULL, when an object is duplicated, the internalRep union is
+ *   directly copied from an object to another.
+ *   Note that it's up to the caller to free the old internal repr of the
+ *   object before to call the Dup method.
+ * - UpdateString is used to create the string from the internal repr.
+ * - setFromAny is used to convert the current object into one of this type.
+ */
+
+struct Jim_Interp;
+
+typedef void (Jim_FreeInternalRepProc)(struct Jim_Interp *interp,
+        struct Jim_Obj *objPtr);
+typedef void (Jim_DupInternalRepProc)(struct Jim_Interp *interp,
+        struct Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+typedef void (Jim_UpdateStringProc)(struct Jim_Obj *objPtr);
+    
+typedef struct Jim_ObjType {
+    const char *name; /* The name of the type. */
+    Jim_FreeInternalRepProc *freeIntRepProc;
+    Jim_DupInternalRepProc *dupIntRepProc;
+    Jim_UpdateStringProc *updateStringProc;
+    int flags;
+} Jim_ObjType;
+
+/* Jim_ObjType flags */
+#define JIM_TYPE_NONE 0        /* No flags */
+#define JIM_TYPE_REFERENCES 1    /* The object may contain referneces. */
+
+/* Starting from 1 << 20 flags are reserved for private uses of
+ * different calls. This way the same 'flags' argument may be used
+ * to pass both global flags and private flags. */
+#define JIM_PRIV_FLAG_SHIFT 20
+
+/* -----------------------------------------------------------------------------
+ * Call frame, vars, commands structures
+ * ---------------------------------------------------------------------------*/
+
+/* Call frame */
+typedef struct Jim_CallFrame {
+    unsigned jim_wide id; /* Call Frame ID. Used for caching. */
+    struct Jim_HashTable vars; /* Where local vars are stored */
+    struct Jim_HashTable *staticVars; /* pointer to procedure static vars */
+    struct Jim_CallFrame *parentCallFrame;
+    Jim_Obj *const *argv; /* object vector of the current procedure call. */
+    int argc; /* number of args of the current procedure call. */
+    Jim_Obj *procArgsObjPtr; /* arglist object of the running procedure */
+    Jim_Obj *procBodyObjPtr; /* body object of the running procedure */
+    struct Jim_CallFrame *nextFramePtr;
+} Jim_CallFrame;
+
+/* The var structure. It just holds the pointer of the referenced
+ * object. If linkFramePtr is not NULL the variable is a link
+ * to a variable of name store on objPtr living on the given callframe
+ * (this happens when the [global] or [upvar] command is used).
+ * The interp in order to always know how to free the Jim_Obj associated
+ * with a given variable because In Jim objects memory managment is
+ * bound to interpreters. */
+typedef struct Jim_Var {
+    Jim_Obj *objPtr;
+    struct Jim_CallFrame *linkFramePtr;
+} Jim_Var;
+    
+/* The cmd structure. */
+typedef int (*Jim_CmdProc)(struct Jim_Interp *interp, int argc,
+    Jim_Obj *const *argv);
+typedef void (*Jim_DelCmdProc)(struct Jim_Interp *interp, void *privData);
+
+/* A command is implemented in C if funcPtr is != NULL, otherwise
+ * it's a Tcl procedure with the arglist and body represented by the
+ * two objects referenced by arglistObjPtr and bodyoObjPtr. */
+typedef struct Jim_Cmd {
+    Jim_CmdProc cmdProc; /* Not-NULL for a C command. */
+    void *privData; /* Only used for C commands. */
+    Jim_DelCmdProc delProc; /* Called when the command is deleted if != NULL */
+    Jim_Obj *argListObjPtr;
+    Jim_Obj *bodyObjPtr;
+    Jim_HashTable *staticVars; /* Static vars hash table. NULL if no statics. */
+    int arityMin; /* Min number of arguments. */
+    int arityMax; /* Max number of arguments. */
+} Jim_Cmd;
+
+/* Pseudo Random Number Generator State structure */
+typedef struct Jim_PrngState {
+    unsigned char sbox[256];
+    unsigned int i, j;
+} Jim_PrngState;
+
+/* -----------------------------------------------------------------------------
+ * Jim interpreter structure.
+ * Fields similar to the real Tcl interpreter structure have the same names.
+ * ---------------------------------------------------------------------------*/
+typedef struct Jim_Interp {
+    Jim_Obj *result; /* object returned by the last command called. */
+    int errorLine; /* Error line where an error occurred. */
+    const char *errorFileName; /* Error file where an error occurred. */
+    int numLevels; /* Number of current nested calls. */
+    int maxNestingDepth; /* Used for infinite loop detection. */
+    int returnCode; /* Completion code to return on JIM_RETURN. */
+    int exitCode; /* Code to return to the OS on JIM_EXIT. */
+    Jim_CallFrame *framePtr; /* Pointer to the current call frame */
+    Jim_CallFrame *topFramePtr; /* toplevel/global frame pointer. */
+    struct Jim_HashTable commands; /* Commands hash table */
+    unsigned jim_wide procEpoch; /* Incremented every time the result
+                of procedures names lookup caching
+                may no longer be valid. */
+    unsigned jim_wide callFrameEpoch; /* Incremented every time a new
+                callframe is created. This id is used for the
+                'ID' field contained in the Jim_CallFrame
+                structure. */
+    Jim_Obj *liveList; /* Linked list of all the live objects. */
+    Jim_Obj *freeList; /* Linked list of all the unused objects. */
+    const char *scriptFileName; /* File name of the script currently in execution. */
+    Jim_Obj *emptyObj; /* Shared empty string object. */
+    unsigned jim_wide referenceNextId; /* Next id for reference. */
+    struct Jim_HashTable references; /* References hash table. */
+    jim_wide lastCollectId; /* reference max Id of the last GC
+                execution. It's set to -1 while the collection
+                is running as sentinel to avoid to recursive
+                calls via the [collect] command inside
+                finalizers. */
+    time_t lastCollectTime; /* unix time of the last GC execution */
+    struct Jim_HashTable sharedStrings; /* Shared Strings hash table */
+    Jim_Obj *stackTrace; /* Stack trace object. */
+    Jim_Obj *unknown; /* Unknown command cache */
+    int errorFlag; /* Set if an error occurred during execution. */
+    int evalRetcodeLevel; /* Level where the last return with code JIM_EVAL
+                             happened. */
+    void *cmdPrivData; /* Used to pass the private data pointer to
+                  a command. It is set to what the user specified
+                  via Jim_CreateCommand(). */
+
+    struct Jim_HashTable stub; /* Stub hash table to export API */
+    /* Jim_GetApi() function pointer, used to bootstrap the STUB table */
+    int (*getApiFuncPtr)(struct Jim_Interp *, const char *, void *);
+    struct Jim_CallFrame *freeFramesList; /* list of CallFrame structures. */
+    struct Jim_HashTable assocData; /* per-interp storage for use by packages */
+    Jim_PrngState *prngState; /* per interpreter Random Number Gen. state. */
+    struct Jim_HashTable packages; /* Provided packages hash table */
+    FILE *stdin; /* input file pointer, 'stdin' by default */
+    FILE *stdout; /* output file pointer, 'stdout' by default */
+    FILE *stderr; /* errors file pointer, 'stderr' by default */
+} Jim_Interp;
+
+/* Currently provided as macro that performs the increment.
+ * At some point may be a real function doing more work.
+ * The proc epoch is used in order to know when a command lookup
+ * cached can no longer considered valid. */
+#define Jim_InterpIncrProcEpoch(i) (i)->procEpoch++
+#define Jim_SetResultString(i,s,l) Jim_SetResult(i, Jim_NewStringObj(i,s,l))
+#define Jim_SetEmptyResult(i) Jim_SetResult(i, (i)->emptyObj)
+#define Jim_GetResult(i) ((i)->result)
+#define Jim_CmdPrivData(i) ((i)->cmdPrivData)
+
+/* Note that 'o' is expanded only one time inside this macro,
+ * so it's safe to use side effects. */
+#define Jim_SetResult(i,o) do {     \
+    Jim_Obj *_resultObjPtr_ = (o);    \
+    Jim_IncrRefCount(_resultObjPtr_); \
+    Jim_DecrRefCount(i,(i)->result);  \
+    (i)->result = _resultObjPtr_;     \
+} while(0)
+
+/* Reference structure. The interpreter pointer is held within privdata member in HashTable */
+#define JIM_REFERENCE_TAGLEN 7 /* The tag is fixed-length, because the reference
+                                  string representation must be fixed length. */
+typedef struct Jim_Reference {
+    Jim_Obj *objPtr;
+    Jim_Obj *finalizerCmdNamePtr;
+    char tag[JIM_REFERENCE_TAGLEN+1];
+} Jim_Reference;
+
+/* -----------------------------------------------------------------------------
+ * Exported API prototypes.
+ * ---------------------------------------------------------------------------*/
+
+/* Macros that are common for extensions and core. */
+#define Jim_NewEmptyStringObj(i) Jim_NewStringObj(i, "", 0)
+
+/* The core includes real prototypes, extensions instead
+ * include a global function pointer for every function exported.
+ * Once the extension calls Jim_InitExtension(), the global
+ * functon pointers are set to the value of the STUB table
+ * contained in the Jim_Interp structure.
+ *
+ * This makes Jim able to load extensions even if it is statically
+ * linked itself, and to load extensions compiled with different
+ * versions of Jim (as long as the API is still compatible.) */
+
+/* Macros are common for core and extensions */
+#define Jim_FreeHashTableIterator(iter) Jim_Free(iter)
+
+#ifndef __JIM_CORE__
+# if defined JIM_EXTENSION || defined JIM_EMBEDDED
+#  define JIM_API(x) (*x)
+#  define JIM_STATIC
+# else
+#  define JIM_API(x) (*x)
+#  define JIM_STATIC extern
+# endif
+#else
+# define JIM_API(x) x
+# define JIM_STATIC static
+#endif /* __JIM_CORE__ */
+
+/* Memory allocation */
+JIM_STATIC void * JIM_API(Jim_Alloc) (int size);
+JIM_STATIC void JIM_API(Jim_Free) (void *ptr);
+JIM_STATIC char * JIM_API(Jim_StrDup) (const char *s);
+
+/* evaluation */
+JIM_STATIC int JIM_API(Jim_Eval)(Jim_Interp *interp, const char *script);
+JIM_STATIC int JIM_API(Jim_EvalGlobal)(Jim_Interp *interp, const char *script);
+JIM_STATIC int JIM_API(Jim_EvalFile)(Jim_Interp *interp, const char *filename);
+JIM_STATIC int JIM_API(Jim_EvalObj) (Jim_Interp *interp, Jim_Obj *scriptObjPtr);
+JIM_STATIC int JIM_API(Jim_EvalObjBackground) (Jim_Interp *interp,
+        Jim_Obj *scriptObjPtr);
+JIM_STATIC int JIM_API(Jim_EvalObjVector) (Jim_Interp *interp, int objc,
+        Jim_Obj *const *objv);
+JIM_STATIC int JIM_API(Jim_SubstObj) (Jim_Interp *interp, Jim_Obj *substObjPtr,
+        Jim_Obj **resObjPtrPtr, int flags);
+
+/* stack */
+JIM_STATIC void JIM_API(Jim_InitStack)(Jim_Stack *stack);
+JIM_STATIC void JIM_API(Jim_FreeStack)(Jim_Stack *stack);
+JIM_STATIC int JIM_API(Jim_StackLen)(Jim_Stack *stack);
+JIM_STATIC void JIM_API(Jim_StackPush)(Jim_Stack *stack, void *element);
+JIM_STATIC void * JIM_API(Jim_StackPop)(Jim_Stack *stack);
+JIM_STATIC void * JIM_API(Jim_StackPeek)(Jim_Stack *stack);
+JIM_STATIC void JIM_API(Jim_FreeStackElements)(Jim_Stack *stack, void (*freeFunc)(void *ptr));
+
+/* hash table */
+JIM_STATIC int JIM_API(Jim_InitHashTable) (Jim_HashTable *ht,
+        Jim_HashTableType *type, void *privdata);
+JIM_STATIC int JIM_API(Jim_ExpandHashTable) (Jim_HashTable *ht,
+        unsigned int size);
+JIM_STATIC int JIM_API(Jim_AddHashEntry) (Jim_HashTable *ht, const void *key,
+        void *val);
+JIM_STATIC int JIM_API(Jim_ReplaceHashEntry) (Jim_HashTable *ht,
+        const void *key, void *val);
+JIM_STATIC int JIM_API(Jim_DeleteHashEntry) (Jim_HashTable *ht,
+        const void *key);
+JIM_STATIC int JIM_API(Jim_FreeHashTable) (Jim_HashTable *ht);
+JIM_STATIC Jim_HashEntry * JIM_API(Jim_FindHashEntry) (Jim_HashTable *ht,
+        const void *key);
+JIM_STATIC int JIM_API(Jim_ResizeHashTable) (Jim_HashTable *ht);
+JIM_STATIC Jim_HashTableIterator *JIM_API(Jim_GetHashTableIterator)
+        (Jim_HashTable *ht);
+JIM_STATIC Jim_HashEntry * JIM_API(Jim_NextHashEntry)
+        (Jim_HashTableIterator *iter);
+
+/* objects */
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewObj) (Jim_Interp *interp);
+JIM_STATIC void JIM_API(Jim_FreeObj) (Jim_Interp *interp, Jim_Obj *objPtr);
+JIM_STATIC void JIM_API(Jim_InvalidateStringRep) (Jim_Obj *objPtr);
+JIM_STATIC void JIM_API(Jim_InitStringRep) (Jim_Obj *objPtr, const char *bytes,
+        int length);
+JIM_STATIC Jim_Obj * JIM_API(Jim_DuplicateObj) (Jim_Interp *interp,
+        Jim_Obj *objPtr);
+JIM_STATIC const char * JIM_API(Jim_GetString)(Jim_Obj *objPtr,
+        int *lenPtr);
+JIM_STATIC int JIM_API(Jim_Length)(Jim_Obj *objPtr);
+
+/* string object */
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewStringObj) (Jim_Interp *interp,
+        const char *s, int len);
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewStringObjNoAlloc) (Jim_Interp *interp,
+        char *s, int len);
+JIM_STATIC void JIM_API(Jim_AppendString) (Jim_Interp *interp, Jim_Obj *objPtr,
+        const char *str, int len);
+JIM_STATIC void JIM_API(Jim_AppendObj) (Jim_Interp *interp, Jim_Obj *objPtr,
+        Jim_Obj *appendObjPtr);
+JIM_STATIC void JIM_API(Jim_AppendStrings) (Jim_Interp *interp,
+        Jim_Obj *objPtr, ...);
+JIM_STATIC int JIM_API(Jim_StringEqObj) (Jim_Obj *aObjPtr,
+        Jim_Obj *bObjPtr, int nocase);
+JIM_STATIC int JIM_API(Jim_StringMatchObj) (Jim_Obj *patternObjPtr,
+        Jim_Obj *objPtr, int nocase);
+JIM_STATIC Jim_Obj * JIM_API(Jim_StringRangeObj) (Jim_Interp *interp,
+        Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr,
+        Jim_Obj *lastObjPtr);
+JIM_STATIC Jim_Obj * JIM_API(Jim_FormatString) (Jim_Interp *interp,
+        Jim_Obj *fmtObjPtr, int objc, Jim_Obj *const *objv);
+JIM_STATIC Jim_Obj * JIM_API(Jim_ScanString) (Jim_Interp *interp, Jim_Obj *strObjPtr,
+        Jim_Obj *fmtObjPtr, int flags);
+JIM_STATIC int JIM_API(Jim_CompareStringImmediate) (Jim_Interp *interp,
+        Jim_Obj *objPtr, const char *str);
+
+/* reference object */
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewReference) (Jim_Interp *interp,
+        Jim_Obj *objPtr, Jim_Obj *tagPtr, Jim_Obj *cmdNamePtr);
+JIM_STATIC Jim_Reference * JIM_API(Jim_GetReference) (Jim_Interp *interp,
+        Jim_Obj *objPtr);
+JIM_STATIC int JIM_API(Jim_SetFinalizer) (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr);
+JIM_STATIC int JIM_API(Jim_GetFinalizer) (Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr);
+
+/* interpreter */
+JIM_STATIC Jim_Interp * JIM_API(Jim_CreateInterp) (void);
+JIM_STATIC void JIM_API(Jim_FreeInterp) (Jim_Interp *i);
+JIM_STATIC int JIM_API(Jim_GetExitCode) (Jim_Interp *interp);
+JIM_STATIC FILE * JIM_API(Jim_SetStdin) (Jim_Interp *interp, FILE *fp);
+JIM_STATIC FILE * JIM_API(Jim_SetStdout) (Jim_Interp *interp, FILE *fp);
+JIM_STATIC FILE * JIM_API(Jim_SetStderr) (Jim_Interp *interp, FILE *fp);
+
+/* commands */
+JIM_STATIC void JIM_API(Jim_RegisterCoreCommands) (Jim_Interp *interp);
+JIM_STATIC int JIM_API(Jim_CreateCommand) (Jim_Interp *interp, 
+        const char *cmdName, Jim_CmdProc cmdProc, void *privData,
+         Jim_DelCmdProc delProc);
+JIM_STATIC int JIM_API(Jim_CreateProcedure) (Jim_Interp *interp, 
+        const char *cmdName, Jim_Obj *argListObjPtr, Jim_Obj *staticsListObjPtr,
+        Jim_Obj *bodyObjPtr, int arityMin, int arityMax);
+JIM_STATIC int JIM_API(Jim_DeleteCommand) (Jim_Interp *interp,
+        const char *cmdName);
+JIM_STATIC int JIM_API(Jim_RenameCommand) (Jim_Interp *interp, 
+        const char *oldName, const char *newName);
+JIM_STATIC Jim_Cmd * JIM_API(Jim_GetCommand) (Jim_Interp *interp,
+        Jim_Obj *objPtr, int flags);
+JIM_STATIC int JIM_API(Jim_SetVariable) (Jim_Interp *interp,
+        Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr);
+JIM_STATIC int JIM_API(Jim_SetVariableStr) (Jim_Interp *interp,
+        const char *name, Jim_Obj *objPtr);
+JIM_STATIC int JIM_API(Jim_SetGlobalVariableStr) (Jim_Interp *interp,
+        const char *name, Jim_Obj *objPtr);
+JIM_STATIC int JIM_API(Jim_SetVariableStrWithStr) (Jim_Interp *interp,
+        const char *name, const char *val);
+JIM_STATIC int JIM_API(Jim_SetVariableLink) (Jim_Interp *interp,
+        Jim_Obj *nameObjPtr, Jim_Obj *targetNameObjPtr,
+        Jim_CallFrame *targetCallFrame);
+JIM_STATIC Jim_Obj * JIM_API(Jim_GetVariable) (Jim_Interp *interp,
+        Jim_Obj *nameObjPtr, int flags);
+JIM_STATIC Jim_Obj * JIM_API(Jim_GetGlobalVariable) (Jim_Interp *interp,
+        Jim_Obj *nameObjPtr, int flags);
+JIM_STATIC Jim_Obj * JIM_API(Jim_GetVariableStr) (Jim_Interp *interp,
+        const char *name, int flags);
+JIM_STATIC Jim_Obj * JIM_API(Jim_GetGlobalVariableStr) (Jim_Interp *interp,
+        const char *name, int flags);
+JIM_STATIC int JIM_API(Jim_UnsetVariable) (Jim_Interp *interp,
+        Jim_Obj *nameObjPtr, int flags);
+
+/* call frame */
+JIM_STATIC int JIM_API(Jim_GetCallFrameByLevel) (Jim_Interp *interp,
+        Jim_Obj *levelObjPtr, Jim_CallFrame **framePtrPtr,
+        int *newLevelPtr);
+
+/* garbage collection */
+JIM_STATIC int JIM_API(Jim_Collect) (Jim_Interp *interp);
+JIM_STATIC void JIM_API(Jim_CollectIfNeeded) (Jim_Interp *interp);
+
+/* index object */
+JIM_STATIC int JIM_API(Jim_GetIndex) (Jim_Interp *interp, Jim_Obj *objPtr,
+        int *indexPtr);
+
+/* list object */
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewListObj) (Jim_Interp *interp,
+        Jim_Obj *const *elements, int len);
+JIM_STATIC void JIM_API(Jim_ListInsertElements) (Jim_Interp *interp,
+        Jim_Obj *listPtr, int index, int objc, Jim_Obj *const *objVec);
+JIM_STATIC void JIM_API(Jim_ListAppendElement) (Jim_Interp *interp,
+        Jim_Obj *listPtr, Jim_Obj *objPtr);
+JIM_STATIC void JIM_API(Jim_ListAppendList) (Jim_Interp *interp,
+        Jim_Obj *listPtr, Jim_Obj *appendListPtr);
+JIM_STATIC void JIM_API(Jim_ListLength) (Jim_Interp *interp, Jim_Obj *listPtr,
+        int *intPtr);
+JIM_STATIC int JIM_API(Jim_ListIndex) (Jim_Interp *interp, Jim_Obj *listPrt,
+        int index, Jim_Obj **objPtrPtr, int seterr);
+JIM_STATIC int JIM_API(Jim_SetListIndex) (Jim_Interp *interp,
+        Jim_Obj *varNamePtr, Jim_Obj *const *indexv, int indexc,
+        Jim_Obj *newObjPtr);
+JIM_STATIC Jim_Obj * JIM_API(Jim_ConcatObj) (Jim_Interp *interp, int objc,
+        Jim_Obj *const *objv);
+
+/* dict object */
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewDictObj) (Jim_Interp *interp,
+        Jim_Obj *const *elements, int len);
+JIM_STATIC int JIM_API(Jim_DictKey) (Jim_Interp *interp, Jim_Obj *dictPtr,
+        Jim_Obj *keyPtr, Jim_Obj **objPtrPtr, int flags);
+JIM_STATIC int JIM_API(Jim_DictKeysVector) (Jim_Interp *interp,
+        Jim_Obj *dictPtr, Jim_Obj *const *keyv, int keyc,
+        Jim_Obj **objPtrPtr, int flags);
+JIM_STATIC int JIM_API(Jim_SetDictKeysVector) (Jim_Interp *interp,
+        Jim_Obj *varNamePtr, Jim_Obj *const *keyv, int keyc,
+        Jim_Obj *newObjPtr);
+
+/* return code object */
+JIM_STATIC int JIM_API(Jim_GetReturnCode) (Jim_Interp *interp, Jim_Obj *objPtr,
+        int *intPtr);
+
+/* expression object */
+JIM_STATIC int JIM_API(Jim_EvalExpression) (Jim_Interp *interp,
+        Jim_Obj *exprObjPtr, Jim_Obj **exprResultPtrPtr);
+JIM_STATIC int JIM_API(Jim_GetBoolFromExpr) (Jim_Interp *interp,
+        Jim_Obj *exprObjPtr, int *boolPtr);
+
+/* integer object */
+JIM_STATIC int JIM_API(Jim_GetWide) (Jim_Interp *interp, Jim_Obj *objPtr,
+        jim_wide *widePtr);
+JIM_STATIC int JIM_API(Jim_GetLong) (Jim_Interp *interp, Jim_Obj *objPtr,
+        long *longPtr);
+JIM_STATIC void JIM_API(Jim_SetWide) (Jim_Interp *interp, Jim_Obj *objPtr,
+        jim_wide wideValue);
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewIntObj) (Jim_Interp *interp,
+        jim_wide wideValue);
+
+/* double object */
+JIM_STATIC int JIM_API(Jim_GetDouble)(Jim_Interp *interp, Jim_Obj *objPtr,
+        double *doublePtr);
+JIM_STATIC void JIM_API(Jim_SetDouble)(Jim_Interp *interp, Jim_Obj *objPtr,
+        double doubleValue);
+JIM_STATIC Jim_Obj * JIM_API(Jim_NewDoubleObj)(Jim_Interp *interp, double doubleValue);
+
+/* shared strings */
+JIM_STATIC const char * JIM_API(Jim_GetSharedString) (Jim_Interp *interp, 
+        const char *str);
+JIM_STATIC void JIM_API(Jim_ReleaseSharedString) (Jim_Interp *interp,
+        const char *str);
+
+/* commands utilities */
+JIM_STATIC void JIM_API(Jim_WrongNumArgs) (Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv, const char *msg);
+JIM_STATIC int JIM_API(Jim_GetEnum) (Jim_Interp *interp, Jim_Obj *objPtr,
+        const char **tablePtr, int *indexPtr, const char *name, int flags);
+JIM_STATIC int JIM_API(Jim_ScriptIsComplete) (const char *s, int len,
+        char *stateCharPtr);
+
+/* package utilities */
+typedef void (Jim_InterpDeleteProc)(Jim_Interp *interp, void *data);
+JIM_STATIC void * JIM_API(Jim_GetAssocData)(Jim_Interp *interp, const char *key);
+JIM_STATIC int JIM_API(Jim_SetAssocData)(Jim_Interp *interp, const char *key,
+        Jim_InterpDeleteProc *delProc, void *data);
+JIM_STATIC int JIM_API(Jim_DeleteAssocData)(Jim_Interp *interp, const char *key);
+
+/* API import/export functions */
+JIM_STATIC int JIM_API(Jim_GetApi) (Jim_Interp *interp, const char *funcname,
+        void *targetPtrPtr);
+JIM_STATIC int JIM_API(Jim_RegisterApi) (Jim_Interp *interp, 
+        const char *funcname, void *funcptr);
+
+/* Packages C API */
+JIM_STATIC int JIM_API(Jim_PackageProvide) (Jim_Interp *interp,
+        const char *name, const char *ver, int flags);
+JIM_STATIC const char * JIM_API(Jim_PackageRequire) (Jim_Interp *interp,
+        const char *name, const char *ver, int flags);
+
+/* error messages */
+JIM_STATIC void JIM_API(Jim_PrintErrorMessage) (Jim_Interp *interp);
+
+/* interactive mode */
+JIM_STATIC int JIM_API(Jim_InteractivePrompt) (Jim_Interp *interp);
+
+/* Misc */
+JIM_STATIC void JIM_API(Jim_Panic) (Jim_Interp *interp, const char *fmt, ...);
+
+#undef JIM_STATIC
+#undef JIM_API
+
+#ifndef __JIM_CORE__
+
+#define JIM_GET_API(name) \
+    Jim_GetApi(interp, "Jim_" #name, ((void *)&Jim_ ## name))
+
+#if defined JIM_EXTENSION || defined JIM_EMBEDDED
+/* This must be included "inline" inside the extension */
+static void Jim_InitExtension(Jim_Interp *interp)
+{
+  Jim_GetApi = interp->getApiFuncPtr;
+
+  JIM_GET_API(Alloc);
+  JIM_GET_API(Free);
+  JIM_GET_API(Eval);
+  JIM_GET_API(EvalGlobal);
+  JIM_GET_API(EvalFile);
+  JIM_GET_API(EvalObj);
+  JIM_GET_API(EvalObjBackground);
+  JIM_GET_API(EvalObjVector);
+  JIM_GET_API(InitHashTable);
+  JIM_GET_API(ExpandHashTable);
+  JIM_GET_API(AddHashEntry);
+  JIM_GET_API(ReplaceHashEntry);
+  JIM_GET_API(DeleteHashEntry);
+  JIM_GET_API(FreeHashTable);
+  JIM_GET_API(FindHashEntry);
+  JIM_GET_API(ResizeHashTable);
+  JIM_GET_API(GetHashTableIterator);
+  JIM_GET_API(NextHashEntry);
+  JIM_GET_API(NewObj);
+  JIM_GET_API(FreeObj);
+  JIM_GET_API(InvalidateStringRep);
+  JIM_GET_API(InitStringRep);
+  JIM_GET_API(DuplicateObj);
+  JIM_GET_API(GetString);
+  JIM_GET_API(Length);
+  JIM_GET_API(InvalidateStringRep);
+  JIM_GET_API(NewStringObj);
+  JIM_GET_API(NewStringObjNoAlloc);
+  JIM_GET_API(AppendString);
+  JIM_GET_API(AppendObj);
+  JIM_GET_API(AppendStrings);
+  JIM_GET_API(StringEqObj);
+  JIM_GET_API(StringMatchObj);
+  JIM_GET_API(StringRangeObj);
+  JIM_GET_API(FormatString);
+  JIM_GET_API(ScanString);
+  JIM_GET_API(CompareStringImmediate);
+  JIM_GET_API(NewReference);
+  JIM_GET_API(GetReference);
+  JIM_GET_API(SetFinalizer);
+  JIM_GET_API(GetFinalizer);
+  JIM_GET_API(CreateInterp);
+  JIM_GET_API(FreeInterp);
+  JIM_GET_API(GetExitCode);
+  JIM_GET_API(SetStdin);
+  JIM_GET_API(SetStdout);
+  JIM_GET_API(SetStderr);
+  JIM_GET_API(CreateCommand);
+  JIM_GET_API(CreateProcedure);
+  JIM_GET_API(DeleteCommand);
+  JIM_GET_API(RenameCommand);
+  JIM_GET_API(GetCommand);
+  JIM_GET_API(SetVariable);
+  JIM_GET_API(SetVariableStr);
+  JIM_GET_API(SetGlobalVariableStr);
+  JIM_GET_API(SetVariableStrWithStr);
+  JIM_GET_API(SetVariableLink);
+  JIM_GET_API(GetVariable);
+  JIM_GET_API(GetCallFrameByLevel);
+  JIM_GET_API(Collect);
+  JIM_GET_API(CollectIfNeeded);
+  JIM_GET_API(GetIndex);
+  JIM_GET_API(NewListObj);
+  JIM_GET_API(ListInsertElements);
+  JIM_GET_API(ListAppendElement);
+  JIM_GET_API(ListAppendList);
+  JIM_GET_API(ListLength);
+  JIM_GET_API(ListIndex);
+  JIM_GET_API(SetListIndex);
+  JIM_GET_API(ConcatObj);
+  JIM_GET_API(NewDictObj);
+  JIM_GET_API(DictKey);
+  JIM_GET_API(DictKeysVector);
+  JIM_GET_API(GetIndex);
+  JIM_GET_API(GetReturnCode);
+  JIM_GET_API(EvalExpression);
+  JIM_GET_API(GetBoolFromExpr);
+  JIM_GET_API(GetWide);
+  JIM_GET_API(GetLong);
+  JIM_GET_API(SetWide);
+  JIM_GET_API(NewIntObj);
+  JIM_GET_API(GetDouble);
+  JIM_GET_API(SetDouble);
+  JIM_GET_API(NewDoubleObj);
+  JIM_GET_API(WrongNumArgs);
+  JIM_GET_API(SetDictKeysVector);
+  JIM_GET_API(SubstObj);
+  JIM_GET_API(RegisterApi);
+  JIM_GET_API(PrintErrorMessage);
+  JIM_GET_API(InteractivePrompt);
+  JIM_GET_API(RegisterCoreCommands);
+  JIM_GET_API(GetSharedString);
+  JIM_GET_API(ReleaseSharedString);
+  JIM_GET_API(Panic);
+  JIM_GET_API(StrDup);
+  JIM_GET_API(UnsetVariable);
+  JIM_GET_API(GetVariableStr);
+  JIM_GET_API(GetGlobalVariable);
+  JIM_GET_API(GetGlobalVariableStr);
+  JIM_GET_API(GetAssocData);
+  JIM_GET_API(SetAssocData);
+  JIM_GET_API(DeleteAssocData);
+  JIM_GET_API(GetEnum);
+  JIM_GET_API(ScriptIsComplete);
+  JIM_GET_API(PackageProvide);
+  JIM_GET_API(PackageRequire);
+  JIM_GET_API(InitStack);
+  JIM_GET_API(FreeStack);
+  JIM_GET_API(StackLen);
+  JIM_GET_API(StackPush);
+  JIM_GET_API(StackPop);
+  JIM_GET_API(StackPeek);
+  JIM_GET_API(FreeStackElements);
+}
+#endif /* defined JIM_EXTENSION || defined JIM_EMBEDDED */
+
+#undef JIM_GET_API
+
+#ifdef JIM_EMBEDDED
+Jim_Interp *ExportedJimCreateInterp(void);
+static void Jim_InitEmbedded(void) {
+    Jim_Interp *i = ExportedJimCreateInterp();
+    Jim_InitExtension(i);
+    Jim_FreeInterp(i);
+}
+#endif /* JIM_EMBEDDED */
+#endif /* __JIM_CORE__ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __JIM__H */
diff --git a/packages/net/athttpd/v2_0/include/md5.h b/packages/net/athttpd/v2_0/include/md5.h
new file mode 100644 (file)
index 0000000..adadc0d
--- /dev/null
@@ -0,0 +1,37 @@
+/* MD5.H - header file for MD5C.C
+ */
+
+/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+rights reserved.
+
+License to copy and use this software is granted provided that it
+is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+Algorithm" in all material mentioning or referencing this software
+or this function.
+
+License is also granted to make and use derivative works provided
+that such works are identified as "derived from the RSA Data
+Security, Inc. MD5 Message-Digest Algorithm" in all material
+mentioning or referencing the derived work.
+
+RSA Data Security, Inc. makes no representations concerning either
+the merchantability of this software or the suitability of this
+software for any particular purpose. It is provided "as is"
+without express or implied warranty of any kind.
+
+These notices must be retained in any copies of any part of this
+documentation and/or software.
+ */
+#include <cyg/athttpd/global.h>
+
+/* MD5 context. */
+typedef struct {
+  UINT4 state[4];                                   /* state (ABCD) */
+  UINT4 count[2];        /* number of bits, modulo 2^64 (lsb first) */
+  unsigned char buffer[64];                         /* input buffer */
+} MD5_CTX;
+
+void MD5Init(MD5_CTX *);
+void MD5Update(MD5_CTX *, unsigned char*, unsigned int);
+void MD5Final(unsigned char [16], MD5_CTX *);
+
diff --git a/packages/net/athttpd/v2_0/include/socket.h b/packages/net/athttpd/v2_0/include/socket.h
new file mode 100644 (file)
index 0000000..a9646a8
--- /dev/null
@@ -0,0 +1,76 @@
+/* =================================================================
+ *
+ *      socket.h
+ *
+ *      Improved HTTPD server.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#ifndef __SOCKET_H__
+#define __SOCKET_H__
+
+#include <pkgconf/system.h>
+
+#define CYG_HTTPD_SOCKET_IDLE_TIMEOUT          300 // In seconds
+
+extern cyg_thread   cyg_httpd_thread_object;
+extern cyg_handle_t cyg_httpd_thread_handle;
+extern cyg_uint8    cyg_httpd_thread_stack[];
+
+
+void cyg_httpd_daemon(cyg_addrword_t);
+void cyg_httpd_start(void);
+ssize_t cyg_httpd_write(char*, int);
+ssize_t cyg_httpd_start_chunked(char*);
+ssize_t cyg_httpd_write_chunked(char*, int);
+void cyg_httpd_end_chunked(void);
+cyg_int32 cyg_httpd_socket_setup(void);
+cyg_int32 cyg_httpd_socket_handle_request(void);
+ssize_t cyg_httpd_writev(cyg_iovec*, int );
+#endif
diff --git a/packages/net/athttpd/v2_0/src/auth.c b/packages/net/athttpd/v2_0/src/auth.c
new file mode 100644 (file)
index 0000000..2a4a9fa
--- /dev/null
@@ -0,0 +1,445 @@
+/* =================================================================
+ *
+ *      auth.c
+ *
+ *      Handles basic authentication.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#include <pkgconf/hal.h>
+#include <pkgconf/kernel.h>
+#include <cyg/kernel/kapi.h>           // Kernel API.
+#include <cyg/hal/hal_tables.h>
+
+#include <stdio.h>
+
+#include <network.h>
+#include <string.h>
+
+#include <cyg/athttpd/http.h>
+#include <cyg/athttpd/md5.h>
+
+// This is a string that contains the domain that is currently authorized.
+cyg_uint8 *cyg_httpd_current_authName;
+
+CYG_HAL_TABLE_BEGIN(cyg_httpd_auth_table, httpd_auth_table );
+CYG_HAL_TABLE_END(cyg_httpd_auth_table_end, httpd_auth_table );
+
+__externC cyg_httpd_auth_table_entry cyg_httpd_auth_table[];
+__externC cyg_httpd_auth_table_entry cyg_httpd_auth_table_end[];
+
+// Variables used for authorization. The header parsing code will only copy
+//  up to AUTH_STORAGE_BUFFER_LENGTH bytes into cyg_httpd_md5_response to
+//  avoid overflow.
+char cyg_httpd_md5_response[AUTH_STORAGE_BUFFER_LENGTH + 1];
+char cyg_httpd_md5_digest[AUTH_STORAGE_BUFFER_LENGTH + 1];
+char cyg_httpd_md5_nonce[33];
+char cyg_httpd_md5_cnonce[33];
+char cyg_httpd_md5_noncecount[9];
+char cyg_httpd_md5_ha2[HASHHEXLEN+1] = {'\0'};
+char cyg_httpd_md5_ha1[HASHHEXLEN+1];
+
+char b64string[] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+cyg_httpd_auth_table_entry*
+cyg_httpd_auth_entry_from_path(char *authPath)
+{
+    cyg_httpd_auth_table_entry *entry = cyg_httpd_auth_table;
+    if (strcmp(authPath, "/") != 0)
+        while (entry != cyg_httpd_auth_table_end)
+        {
+            if (strncmp(entry->auth_dirname,
+                        authPath,
+                        strlen(entry->auth_dirname)) == 0)
+                return entry;
+            entry++;
+        }
+    else
+        while (entry != cyg_httpd_auth_table_end)
+        {
+            if (strcmp(entry->auth_dirname, authPath) == 0)
+                return entry;
+            entry++;
+        }
+            
+    return (cyg_httpd_auth_table_entry *)0;
+}
+
+cyg_httpd_auth_table_entry*
+cyg_httpd_auth_entry_from_domain(char *authDomain)
+{
+    cyg_httpd_auth_table_entry *entry = cyg_httpd_auth_table;
+    while (entry != cyg_httpd_auth_table_end)
+    {
+        if (!strncmp((const char*)authDomain, 
+                       entry->auth_domainname,
+                       strlen(entry->auth_domainname)))
+            return entry;
+        entry++;
+    }
+            
+    return (cyg_httpd_auth_table_entry *)0;
+}
+
+static cyg_int32
+cyg_httpd_base64_decode(char* to, char* from, cyg_uint32 len )
+{
+    char     *fromp = from;
+    char     *top = to;
+    char     *p;
+    char      cbyte;
+    char      obyte;
+    cyg_int32 padding = 0;
+
+    for (; len >= 4; len -= 4)
+    {
+        if ((cbyte = *fromp++) == '=')
+            cbyte = 0;
+        else
+        {
+            if (badchar(cbyte, p ) )
+                return -1;
+            cbyte = (p - b64string);
+        }
+        obyte = cbyte << 2;
+
+        if ((cbyte = *fromp++) == '=')
+            cbyte = 0;
+        else
+        {
+            if (badchar(cbyte, p))
+                return -1;
+            cbyte = p - b64string;
+        }
+        obyte |= cbyte >> 4;
+        *top++ = obyte;
+
+        obyte = cbyte << 4;
+        if ((cbyte = *fromp++) == '=')
+        {
+            cbyte = 0; 
+            padding++;
+        }
+        else
+        {
+            padding = 0;
+            if (badchar(cbyte, p))
+                return -1;
+            cbyte = p - b64string;
+        }
+        obyte |= cbyte >> 2;
+        *top++ = obyte;
+
+        obyte = cbyte << 6;
+        if ((cbyte = *fromp++) == '=')
+        {
+            cbyte = 0;
+            padding++;
+        }
+        else
+        {
+            padding = 0;
+            if (badchar(cbyte, p))
+                return -1;
+            cbyte = p - b64string;
+        }
+        obyte |= cbyte;
+        *top++ = obyte;
+    }
+
+    *top = 0;
+    if (len)
+        return -1;
+    return (top - to) - padding;
+}
+
+// The following code is a slightly modified version of those available at the
+//  end of RFC1270.
+static void cyg_httpd_cvthex(HASH Bin, HASHHEX Hex)
+{
+    unsigned short i;
+    unsigned char j;
+
+    for (i = 0; i < HASHLEN; i++)
+    {
+        j = (Bin[i] >> 4) & 0xf;
+        if (j <= 9)
+            Hex[i*2] = (j + '0');
+         else
+            Hex[i*2] = (j + 'a' - 10);
+        j = Bin[i] & 0xf;
+        if (j <= 9)
+            Hex[i*2+1] = (j + '0');
+         else
+            Hex[i*2+1] = (j + 'a' - 10);
+    };
+    Hex[HASHHEXLEN] = '\0';
+};
+
+// Calculate H(A1) as per spec.
+static void
+cyg_httpd_digest_calc_HA1( char    *pszAlg,
+                           char    *pszUserName,
+                           char    *pszRealm,
+                           char    *pszPassword,
+                           char    *pszNonce,
+                           char    *pszCNonce,
+                           HASHHEX  SessionKey )
+{
+      MD5_CTX Md5Ctx;
+      HASH HA1;
+
+      MD5Init(&Md5Ctx);
+      MD5Update(&Md5Ctx, (unsigned char*)pszUserName, strlen(pszUserName));
+      MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+      MD5Update(&Md5Ctx, (unsigned char*)pszRealm, strlen(pszRealm));
+      MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+      MD5Update(&Md5Ctx, (unsigned char*)pszPassword, strlen(pszPassword));
+      MD5Final((unsigned char*)HA1, &Md5Ctx);
+      if (strcmp(pszAlg, "md5-sess") == 0) 
+      {
+          MD5Init(&Md5Ctx);
+          MD5Update(&Md5Ctx, (unsigned char*)HA1, HASHLEN);
+          MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+          MD5Update(&Md5Ctx, (unsigned char*)pszNonce, strlen(pszNonce));
+          MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+          MD5Update(&Md5Ctx, (unsigned char*)pszCNonce, strlen(pszCNonce));
+          MD5Final((unsigned char*)HA1, &Md5Ctx);
+      };
+      cyg_httpd_cvthex(HA1, SessionKey);
+};
+
+// Calculate request-digest/response-digest as per HTTP Digest spec.
+void
+cyg_httpd_digest_calc_response(HASHHEX  HA1,           
+                               char    *pszNonce,       
+                               char    *pszNonceCount,  
+                               char    *pszCNonce,      
+                               char    *pszQop,         
+                               char    *pszMethod,      
+                               char    *pszDigestUri,   
+                               HASHHEX  HEntity,       
+                               HASHHEX  Response)
+{
+    MD5_CTX Md5Ctx;
+    HASH HA2;
+    HASH RespHash;
+    HASHHEX HA2Hex;
+
+    // Calculate H(A2).
+    MD5Init(&Md5Ctx);
+    MD5Update(&Md5Ctx, (unsigned char*)pszMethod, strlen(pszMethod));
+    MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+    MD5Update(&Md5Ctx, (unsigned char*)pszDigestUri, strlen(pszDigestUri));
+    if (strcmp(pszQop, "auth-int") == 0) {
+        MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+        MD5Update(&Md5Ctx, (unsigned char*)HEntity, HASHHEXLEN);
+    };
+    MD5Final((unsigned char*)HA2, &Md5Ctx);
+    cyg_httpd_cvthex(HA2, HA2Hex);
+
+    // calculate response
+    MD5Init(&Md5Ctx);
+    MD5Update(&Md5Ctx, (unsigned char*)HA1, HASHHEXLEN);
+    MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+    MD5Update(&Md5Ctx, (unsigned char*)pszNonce, strlen(pszNonce));
+    MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+    if (*pszQop) 
+    {
+        MD5Update(&Md5Ctx, (unsigned char*)pszNonceCount, strlen(pszNonceCount));
+        MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+        MD5Update(&Md5Ctx, (unsigned char*)pszCNonce, strlen(pszCNonce));
+        MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+        MD5Update(&Md5Ctx, (unsigned char*)pszQop, strlen(pszQop));
+        MD5Update(&Md5Ctx, (unsigned char*)":", 1);
+    };
+    MD5Update(&Md5Ctx, (unsigned char*)HA2Hex, HASHHEXLEN);
+    MD5Final((unsigned char*)RespHash, &Md5Ctx);
+    cyg_httpd_cvthex(RespHash, Response);
+};
+
+cyg_httpd_auth_table_entry*
+cyg_httpd_is_authenticated(char* fname)
+{
+    // Let's check if the directory access needs authorization. The 
+    //  authentication is done on the directory name.
+    cyg_httpd_auth_table_entry* entry =
+                                cyg_httpd_auth_entry_from_path(fname);
+    if (entry != 0)
+    {
+        if (entry->auth_mode == CYG_HTTPD_AUTH_BASIC)
+        {
+            cyg_httpd_base64_decode(cyg_httpd_md5_digest,
+                                    cyg_httpd_md5_response,
+                                    strlen(cyg_httpd_md5_response));
+            char *colon = rindex(cyg_httpd_md5_digest, ':');
+            if (colon == NULL)
+            {
+                return (httpstate.needs_auth = entry);
+            }    
+            else
+            {    
+                *colon = '\0'; // Crypto now has the username.
+                
+                // In the case of a 'Basic" authentication, the HTTP header
+                //  did not return to us the domain name that we sent when we
+                //  challenged the request: The only things that are returned 
+                //  are the username:password duo. In this case I will just 
+                //  compare the entry's username/password to those read from 
+                //  the header.
+                if ((strcmp(entry->auth_username,cyg_httpd_md5_digest) != 0) ||
+                                 (strcmp(entry->auth_password, ++colon) != 0))
+                    return (httpstate.needs_auth = entry);
+            }    
+        }
+        else
+        {
+            char *cyg_httpd_md5_method;
+            
+            switch (httpstate.method)
+            {
+            case CYG_HTTPD_METHOD_GET:
+                cyg_httpd_md5_method = "GET";
+                break;
+            case CYG_HTTPD_METHOD_POST:
+                cyg_httpd_md5_method = "POST";
+                break;
+            default:
+                cyg_httpd_md5_method = "HEAD";
+                break;
+            }    
+            cyg_httpd_digest_calc_HA1(CYG_HTTPD_MD5_AUTH_NAME,
+                                      entry->auth_username,
+                                      entry->auth_domainname,
+                                      entry->auth_password,
+                                      cyg_httpd_md5_nonce,
+                                      cyg_httpd_md5_cnonce,
+                                      cyg_httpd_md5_ha1);
+            cyg_httpd_digest_calc_response(cyg_httpd_md5_ha1,
+                                           cyg_httpd_md5_nonce,
+                                           cyg_httpd_md5_noncecount,
+                                           cyg_httpd_md5_cnonce,
+                                           CYG_HTTPD_MD5_AUTH_QOP,
+                                           cyg_httpd_md5_method,
+                                           httpstate.url,
+                                           cyg_httpd_md5_ha2,
+                                           cyg_httpd_md5_digest);
+            if (strcmp(cyg_httpd_md5_response, cyg_httpd_md5_digest) != 0)
+                return (httpstate.needs_auth = entry);
+        }
+    }
+    // No need for authentication...
+    return (cyg_httpd_auth_table_entry*)0;
+}
+
+char*
+cyg_httpd_digest_data(char *dest, char *src)
+{
+    int exit = 0;
+    while (exit == 0)
+    {
+        switch (*src )
+        {
+        case '\r':
+        case '\n':
+            *dest = '\0';
+            exit = 1;
+            break;
+        case ',':
+            // If it is a comma there might or might not be a blank space
+            //  following it (IE7 inserts no spaces, everyone else does...)
+            //  so before exiting the loop remove any blank space that follows.
+            if (src[1] == ' ')
+                src++;             
+        case ' ':
+            src++;
+            *dest = '\0';
+            exit = 1;
+            break;
+        case '"':
+            src++;
+            break;
+        default:
+            *dest++ = *src++;
+        }    
+    }
+    return src;
+}    
+
+// Skips through fields we do not need.
+char*
+cyg_httpd_digest_skip(char *p)
+{
+    if (*p == '"')
+    {
+        p++;
+        while ((*p != '"') && (*p != '\n'))
+            p++;
+        p++;
+        if (*p == ',')
+            p++;
+        if (*p == ' ')
+            p++;
+        if (*p == '\n')
+            p++;
+    }
+    else        
+    {    
+        while ((*p != ' ') && (*p != '\n'))
+            p++;
+        if (*p == ',')
+            p++;
+        if (*p == ' ')
+            p++;
+        if (*p == '\n')
+            p++;
+    }        
+    return p;
+}
diff --git a/packages/net/athttpd/v2_0/src/cgi.c b/packages/net/athttpd/v2_0/src/cgi.c
new file mode 100644 (file)
index 0000000..5c4800b
--- /dev/null
@@ -0,0 +1,292 @@
+/* =================================================================
+ *
+ *      cgi.c
+ *
+ *      Handles the CGI requests via OBJLOADER or tcl
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: Sergei Gavrikov (w3sg@SoftHome.net)
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#include <pkgconf/hal.h>
+#include <pkgconf/kernel.h>
+#include <cyg/hal/hal_tables.h>
+#include <cyg/fileio/fileio.h>
+#include <dirent.h>
+#include <network.h>
+
+#include <string.h>
+#include <stdio.h>                     // sprintf().
+
+#define JIM_EMBEDDED
+#include <cyg/athttpd/http.h>
+#include <cyg/athttpd/socket.h>
+#include <cyg/athttpd/handler.h>
+#include <cyg/athttpd/forms.h>
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER
+#include <cyg/objloader/elf.h>
+#include <cyg/objloader/objelf.h>
+#endif
+
+// =============================================================================
+// Objloader CGI Support
+// =============================================================================
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER
+CYG_LDR_TABLE_STDIO()
+CYG_LDR_TABLE_STRING()
+
+// Chunked transfers.
+CYG_LDR_TABLE_ENTRY(cyg_httpd_start_chunked_entry,      \
+                    "cyg_httpd_start_chunked",          \
+                    cyg_httpd_start_chunked);
+CYG_LDR_TABLE_ENTRY(cyg_httpd_write_chunked_entry,      \
+                    "cyg_httpd_write_chunked",          \
+                    cyg_httpd_write_chunked);
+CYG_LDR_TABLE_ENTRY(cyg_httpd_end_chunked_entry,      \
+                    "cyg_httpd_end_chunked",          \
+                    cyg_httpd_end_chunked);
+
+// Mime strings.
+CYG_LDR_TABLE_ENTRY(cyg_httpd_write_entry, \
+                    "cyg_httpd_write",     \
+                    cyg_httpd_write);
+                     
+// Entry to find a GET/POST variable in the table.                     
+CYG_LDR_TABLE_ENTRY(cyg_httpd_find_form_variable_entry, \
+                    "cyg_httpd_find_form_variable",     \
+                    cyg_httpd_find_form_variable);
+
+// Finds an internal resource given the URL. Returns a pointer to the entry
+//  in the resource table.
+CYG_LDR_TABLE_ENTRY(cyg_httpd_find_ires_entry, \
+                    "cyg_httpd_find_ires",     \
+                    cyg_httpd_find_ires);
+// Sends an internal resource out, given the entry in the reource table.
+CYG_LDR_TABLE_ENTRY(cyg_httpd_send_ires_entry, \
+                    "cyg_httpd_send_ires",     \
+                    cyg_httpd_send_ires);
+                     
+CYG_LDR_TABLE_ENTRY(cyg_httpd_format_header_entry, \
+                    "cyg_httpd_format_header",     \
+                    cyg_httpd_format_header);
+CYG_LDR_TABLE_ENTRY(diag_printf_entry, "diag_printf", diag_printf);
+CYG_LDR_TABLE_ENTRY(cyg_httpd_find_mime_string_entry, \
+                    "cyg_httpd_find_mime_string",     \
+                    cyg_httpd_find_mime_string);
+#endif // CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER
+cyg_int32 cyg_httpd_exec_cgi_objloader(char *file_name)
+{
+    // Check if the file is in the file system.
+    struct stat sp;
+    cyg_int32 (*fn)(CYG_HTTPD_STATE*);
+    
+    cyg_int32 rc = stat(file_name, &sp);
+    if(rc < 0)
+    {
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_FOUND);
+        return 0;
+    }    
+    
+    void *lib_handle = cyg_ldr_open_library((CYG_ADDRWORD)file_name, 0);
+    CYG_ASSERT(lib_handle != 0, "Error opening the library");
+    if (lib_handle == 0)
+    {
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_SYSTEM_ERROR);
+        return 0;
+    }    
+    fn = cyg_ldr_find_symbol(lib_handle, "exec_cgi");
+    if (fn)
+    {
+        cyg_int32 rc = fn(&httpstate);
+        cyg_ldr_close_library(lib_handle);
+        return rc;
+    }    
+    else
+    {
+        cyg_ldr_close_library(lib_handle);
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_SYSTEM_ERROR);
+        return 0;
+    }    
+}
+#endif
+
+// =============================================================================
+// tcl CGI Support
+// =============================================================================
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL
+int Jim_AioInit(Jim_Interp *);
+cyg_int32
+cyg_httpd_exec_cgi_tcl(char *file_name)
+{
+    // Make sure that tcl sees the internal variables including the post_data.
+    cyg_httpd_fvars_table_entry *entry = cyg_httpd_fvars_table;
+    while (entry != cyg_httpd_fvars_table_end)
+    {
+        if (strlen(entry->buf) != 0)
+            Jim_SetVariableStrWithStr(httpstate.jim_interp, 
+                                      entry->name, 
+                                      entry->buf);
+        entry++;
+    }
+
+    if (httpstate.post_data != NULL)
+        Jim_SetVariableStrWithStr(httpstate.jim_interp, 
+                                  "post_data", 
+                                  httpstate.post_data);
+     
+    char tcl_cmd[CYG_HTTPD_MAXPATH];
+    sprintf(tcl_cmd, "source %s", file_name);
+    Jim_Eval(httpstate.jim_interp, tcl_cmd);
+    return 0;
+}
+
+int
+cyg_httpd_Jim_Command_startchunked(Jim_Interp *interp, 
+                                   int argc,
+                                   Jim_Obj *const *argv)
+{
+    char *buf = (char*)Jim_GetString(argv[1], NULL);
+    cyg_httpd_start_chunked(buf);
+    return JIM_OK;
+}
+  
+int
+cyg_httpd_Jim_Command_writechunked(Jim_Interp *interp, 
+                                   int argc,
+                                   Jim_Obj *const *argv)
+{
+    int len;
+    char *buf = (char*)Jim_GetString(argv[1], &len);
+    cyg_httpd_write_chunked(buf, len);
+    return JIM_OK;
+}
+  
+int
+cyg_httpd_Jim_Command_endchunked(Jim_Interp *interp, 
+                                 int argc,
+                                 Jim_Obj *const *argv)
+{
+    cyg_httpd_end_chunked();
+    return JIM_OK;
+}
+  
+void
+cyg_httpd_init_tcl_interpreter(void)
+{
+    // Start the TCL interpreter.
+    Jim_InitEmbedded();
+    httpstate.jim_interp = Jim_CreateInterp();
+    Jim_RegisterCoreCommands(httpstate.jim_interp);
+    Jim_AioInit(httpstate.jim_interp);
+    
+    // Add a new cyg_httpd_write_chunked command for tcl.
+    Jim_CreateCommand(httpstate.jim_interp,
+                      "start_chunked",
+                      cyg_httpd_Jim_Command_startchunked,
+                      NULL, 
+                      NULL);
+    Jim_CreateCommand(httpstate.jim_interp,
+                      "write_chunked",
+                      cyg_httpd_Jim_Command_writechunked,
+                      NULL, 
+                      NULL);
+    Jim_CreateCommand(httpstate.jim_interp,
+                      "end_chunked",
+                      cyg_httpd_Jim_Command_endchunked,
+                      NULL, 
+                      NULL);
+}                      
+#endif    
+
+// =============================================================================
+// CGI Support
+// =============================================================================
+#if defined(CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL ) || \
+    defined(CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER)
+cyg_int32 
+cyg_httpd_exec_cgi(void)
+{
+    char  file_name[CYG_HTTPD_MAXPATH];
+    
+    strcpy(file_name, CYGDAT_NET_ATHTTPD_SERVEROPT_ROOTDIR);
+    if (file_name[strlen(file_name)-1] != '/')
+        strcat(file_name, "/");
+    strcat(file_name, httpstate.url);
+    cyg_httpd_cleanup_filename(file_name);
+    
+    char *extension = rindex(httpstate.url, '.');
+    if (extension == NULL)
+    {
+        // File in CGI request _must_ have an extension.
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_SYSTEM_ERROR);
+        return 0;
+    }    
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER
+    if (strcmp(extension, CYG_HTTPD_DEFAULT_CGIBIN_OBJLOADER_EXTENSION) == 0)
+    {
+        // Load a cgibin via OBJLOADER.
+        cyg_int32 rc = cyg_httpd_exec_cgi_objloader(file_name);
+        return rc;
+    }    
+#endif
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL
+    if (strcmp(extension, CYG_HTTPD_DEFAULT_CGIBIN_TCL_EXTENSION) == 0)
+    {
+        // Load a cgibin via the TCL interpreter.
+        cyg_int32 rc = cyg_httpd_exec_cgi_tcl(file_name);
+        return rc;
+    }    
+#endif
+    cyg_httpd_send_error(CYG_HTTPD_STATUS_SYSTEM_ERROR);
+    return 0;
+}
+#endif 
+
diff --git a/packages/net/athttpd/v2_0/src/forms.c b/packages/net/athttpd/v2_0/src/forms.c
new file mode 100644 (file)
index 0000000..e530a8f
--- /dev/null
@@ -0,0 +1,309 @@
+/* =================================================================
+ *
+ *      forms.c
+ *
+ *      Handles form variables of GET and POST requests.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: Sergei Gavrikov (w3sg@SoftHome.net)
+ *                Lars Povlsen    (lpovlsen@vitesse.com)
+ *                Tad Artis       (ecos@ds3switch.com)
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#include <pkgconf/hal.h>
+#include <pkgconf/kernel.h>
+#include <pkgconf/io_fileio.h>
+#include <cyg/kernel/kapi.h>           // Kernel API.
+#include <cyg/kernel/ktypes.h>         // base kernel types.
+#include <cyg/infra/diag.h>            // For diagnostic printing.
+#include <network.h>
+#include <sys/uio.h>
+
+#include <cyg/hal/hal_tables.h>
+#include <stdlib.h>
+
+#include <cyg/athttpd/http.h>
+#include <cyg/athttpd/socket.h>
+#include <cyg/athttpd/handler.h>
+#include <cyg/athttpd/forms.h>
+
+CYG_HAL_TABLE_BEGIN(cyg_httpd_fvars_table, httpd_fvars_table);
+CYG_HAL_TABLE_END(cyg_httpd_fvars_table_end, httpd_fvars_table);
+
+cyg_int8 blank[] = "";
+
+cyg_int8
+cyg_httpd_from_hex(cyg_int8 c)
+{
+    if ((c >= '0') && (c <= '9'))
+        return (c - '0');
+    if ((c >= 'A') && (c <= 'F'))
+        return (c - 'A' + 10);
+    if ((c >= 'a') && (c <= 'f'))
+        return (c - 'a' + 10);
+    return -1;    
+}
+
+char*
+cyg_httpd_store_form_variable(char *query, cyg_httpd_fvars_table_entry *entry)
+{
+    char *p = query;
+    char *q = entry->buf;
+    int   len = 0;
+    
+    while (len < (entry->buflen - 1))
+        switch(*p)
+        {
+        case '%':
+            p++;
+            if (*p) 
+                *q = cyg_httpd_from_hex(*p++) * 16;
+            if (*p) 
+                *q = (*q + cyg_httpd_from_hex(*p++));
+            q++;
+            len++;
+            break;
+        case '+':
+            *q++ = ' ';
+            p++;
+            len++;
+            break;
+        case '&':
+        case ' ':
+        case '\0':        // Don't parse past the end of the packet.
+            *q++ = '\0';
+            return p;
+        default:    
+            *q++ = *p++;
+            len++;
+        }
+        while ((*p != ' ') && (*p != '&') && *p)
+            p++;
+        return p;
+} 
+
+// We'll try to parse the data from the form, and store it in the variables
+//  that have been defined by the user in the 'form_variable_table'.
+char*
+cyg_httpd_store_form_data(char *p)
+{
+    char      *p2;
+    cyg_int32 var_length;
+    cyg_httpd_fvars_table_entry *entry = cyg_httpd_fvars_table;
+    
+    // We'll clear all the variables first, to avoid stale data.
+    while (entry != cyg_httpd_fvars_table_end)
+    {
+        entry->buf[0] = '\0';
+        entry++;
+    }
+
+    if (!p)    // No form data? just return after clearing variables.
+        return NULL;
+
+    while (*p && *p != ' ')
+    {
+        if (!(p2 = strchr(p, '=')))
+            return NULL;        // Malformed post?
+        var_length = (cyg_int32)p2 - (cyg_int32)p;
+        entry = cyg_httpd_fvars_table;
+        while (entry != cyg_httpd_fvars_table_end)
+        {
+            // Compare both lenght and name.
+            // If we do not compare the lenght of the variables as well we
+            //  risk the the case where, for instance, the variable name 'foo'
+            //  hits a match with a variable name 'foobar' because the first
+            //  3 letters of the latter are the same as the former.
+            if ((strlen(entry->name) == var_length) &&
+                (strncmp((const char*)p, entry->name, var_length ) == 0))
+               break;
+            entry++;
+        }
+                
+        if (entry == cyg_httpd_fvars_table_end)
+        {
+            // No such variable. Run through the data.
+            while ((*p != '&') && (*p && *p != ' '))
+                p++;
+            if(*p == '&')
+                p++;
+            continue;
+        }
+            
+        // Found the variable, store the name.
+        p = cyg_httpd_store_form_variable(++p2, entry);
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+        diag_printf("Stored form variable: %s Value: %s\n",
+                    entry->name,
+                    entry->buf);
+#endif    
+        if (*p == '&')
+            p++;
+    }
+    return p;
+}
+
+char*
+cyg_httpd_find_form_variable(char *p)
+{
+    cyg_httpd_fvars_table_entry *entry = cyg_httpd_fvars_table;
+    
+    while (entry != cyg_httpd_fvars_table_end)
+    {
+        if (!strcmp((const char*)p, entry->name))
+            return entry->buf;
+        entry++;
+    }
+            
+    return (char*)0;
+}
+
+static inline void release_post_buffer(void)
+{
+    free(httpstate.post_data);
+    httpstate.post_data = NULL;
+    return;
+}
+    
+void
+cyg_httpd_handle_method_POST(void)
+{
+    CYG_ASSERT(httpstate.post_data == NULL, "Leftover content data");
+    CYG_ASSERT(httpstate.request_end != NULL, "Cannot see POST data");
+    if (httpstate.content_len == 0 || 
+        httpstate.content_len > CYGNUM_ATHTTPD_SERVER_MAX_POST) {
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_BAD_REQUEST);
+        return;
+    }
+    
+    // The content data is only valid during a POST.
+    httpstate.post_data = (char*)malloc(httpstate.content_len + 1);
+    CYG_ASSERT(httpstate.post_data != NULL, "Cannot malloc POST buffer");
+    if (httpstate.post_data == NULL)
+    {
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_SYSTEM_ERROR);
+        return;
+    }
+
+    // Grab partial/all content from data read with headers.
+    int header_len = (int)httpstate.request_end - (int)httpstate.inbuffer;
+    unsigned int post_data_available = httpstate.inbuffer_len - header_len;
+    if (httpstate.content_len < post_data_available)
+        post_data_available = httpstate.content_len;
+    
+    // Some POST data might have come along with the header frame, and the
+    //  rest is coming in on following frames. Copy the data that already
+    //  arrived into the post buffer.
+    memcpy(httpstate.post_data, httpstate.request_end, post_data_available);
+    httpstate.request_end += post_data_available;
+    unsigned int total_data_read = post_data_available;
+    
+    // Do we need additional data?
+    if (total_data_read < httpstate.content_len)
+    {
+        while (total_data_read < httpstate.content_len)
+        {
+            // Read only the data that belongs to the POST request.
+            post_data_available = read(
+                          httpstate.sockets[httpstate.client_index].descriptor,
+                          httpstate.post_data + total_data_read,
+                          httpstate.content_len - total_data_read);
+            if (post_data_available < 0)
+            {
+                release_post_buffer();
+                return;
+            }    
+            total_data_read += post_data_available;
+        }
+    }    
+    
+    // httpstate.content remains available in handler.
+    httpstate.post_data[total_data_read] = '\0';
+    
+    // The assumption here is that the data that arrived in the POST body is of
+    //  'multipart/form-data' MIME type. We need to change this if we are to
+    //  support things such as HTTP file transfer.
+    if (httpstate.mode & CYG_HTTPD_MODE_FORM_DATA)
+        cyg_httpd_store_form_data(httpstate.post_data);
+
+#if defined(CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER) || \
+                           defined(CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL)
+    // See if we are trying to execute a CGI via one of the supported methods.
+    // If we the GET request is trying to access a file in the 
+    //  CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR directory then it is assumed that
+    //  we are trying to execute a CGI script. The extension of the file will
+    //  determine the appropriate interpreter to use.
+    if (httpstate.url[0] == '/' &&
+                    !strncmp(httpstate.url + 1, 
+                              CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR, 
+                              strlen(CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR)))
+    {                              
+        // Here we'll look for extension to the file. We'll call the cgi
+        //  handler only if the extension is '.o'.
+        cyg_httpd_exec_cgi();
+        release_post_buffer();
+        return;
+    }
+#endif    
+    
+    handler h = cyg_httpd_find_handler();
+    if (h != 0)
+    {
+        // A handler was found. We'll call the function associated to it.
+        h(&httpstate);
+        release_post_buffer();
+        return;
+    }
+
+
+    // No handler of any kind for a post request. Must send 404.
+    cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_FOUND);
+    release_post_buffer();
+    return;
+}
+
+
diff --git a/packages/net/athttpd/v2_0/src/handler.c b/packages/net/athttpd/v2_0/src/handler.c
new file mode 100644 (file)
index 0000000..26e9590
--- /dev/null
@@ -0,0 +1,596 @@
+/* =================================================================
+ *
+ *      handler.c
+ *
+ *      C callbacks as well as directory listings.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: 
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#include <pkgconf/hal.h>
+#include <pkgconf/kernel.h>
+#include <cyg/hal/hal_tables.h>
+#include <cyg/fileio/fileio.h>
+#include <dirent.h>
+#include <network.h>
+
+#include <string.h>
+#include <stdio.h>                     // sprintf().
+
+#include <cyg/athttpd/http.h>
+#include <cyg/athttpd/socket.h>
+#include <cyg/athttpd/handler.h>
+#include <cyg/athttpd/forms.h>
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_DIRLIST
+static char folder_gif[] = {
+    0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x12, 0x00,
+    0x12, 0x00, 0xd5, 0x00, 0x00, 0xfb, 0xfb, 0xfb,
+    0xef, 0xef, 0xef, 0xdb, 0xb7, 0x52, 0xcc, 0x99,
+    0x34, 0xe4, 0xe4, 0xe4, 0xc1, 0xc1, 0xc1, 0xa3,
+    0x71, 0x0b, 0xc2, 0x8f, 0x2a, 0xb7, 0xb7, 0xb7,
+    0x9e, 0x6c, 0x06, 0xba, 0x87, 0x22, 0x9c, 0x6a,
+    0x04, 0xc9, 0x96, 0x31, 0xbd, 0x8a, 0x25, 0xb3,
+    0x81, 0x1b, 0x99, 0x67, 0x01, 0xdb, 0xb7, 0x71,
+    0xb5, 0x82, 0x1d, 0xa0, 0x6e, 0x08, 0xcb, 0x98,
+    0x33, 0xff, 0xff, 0xba, 0xb0, 0x7e, 0x18, 0xc5,
+    0x92, 0x2d, 0xa7, 0x75, 0x0f, 0xc7, 0x94, 0x2f,
+    0xa6, 0xa6, 0xa6, 0xa5, 0x73, 0x0d, 0xb7, 0x84,
+    0x1f, 0xab, 0x79, 0x13, 0xc8, 0x95, 0x30, 0xc0,
+    0x8d, 0x28, 0xc6, 0xc6, 0xc6, 0xae, 0x7c, 0x16,
+    0x9a, 0x68, 0x02, 0xa8, 0x76, 0x10, 0xac, 0x7a,
+    0x14, 0xff, 0xd4, 0x6f, 0xff, 0xf8, 0x93, 0xeb,
+    0xeb, 0xeb, 0xff, 0xff, 0x9c, 0xff, 0xdb, 0x75,
+    0xff, 0xe4, 0x7f, 0xff, 0xef, 0x89, 0xb6, 0xb6,
+    0xb6, 0xff, 0xff, 0xff, 0xff, 0xff, 0x99, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04,
+    0x01, 0x00, 0x00, 0x2e, 0x00, 0x2c, 0x00, 0x00,
+    0x00, 0x00, 0x12, 0x00, 0x12, 0x00, 0x00, 0x06,
+    0x91, 0x40, 0x97, 0x70, 0x48, 0x2c, 0x1a, 0x8f,
+    0xc8, 0xa4, 0xd2, 0x35, 0x18, 0x4c, 0x18, 0x9d,
+    0x00, 0x40, 0x39, 0x60, 0x59, 0x29, 0x94, 0x03,
+    0x61, 0x7a, 0x1c, 0x40, 0x04, 0x60, 0x30, 0xa4,
+    0xa1, 0xd8, 0x44, 0x1c, 0x95, 0xc0, 0x70, 0x62,
+    0x6d, 0xbb, 0xdb, 0xa3, 0xcf, 0x90, 0xd1, 0x3a,
+    0xd9, 0xef, 0xf8, 0xd6, 0x05, 0x31, 0xc4, 0xb4,
+    0xfe, 0x80, 0x81, 0x7f, 0x06, 0x2b, 0x43, 0x16,
+    0x2d, 0x25, 0x89, 0x8a, 0x8b, 0x2d, 0x12, 0x85,
+    0x42, 0x07, 0x2d, 0x2a, 0x93, 0x94, 0x95, 0x2d,
+    0x09, 0x8f, 0x2e, 0x1e, 0x2d, 0x29, 0x9d, 0x9e,
+    0x9f, 0x2d, 0x0b, 0x99, 0x0d, 0x2d, 0x28, 0xa6,
+    0xa7, 0xa8, 0x2d, 0x21, 0x99, 0x0a, 0x2d, 0x24,
+    0xaf, 0xb0, 0xb1, 0x2d, 0x0f, 0x7c, 0x42, 0x01,
+    0x67, 0x15, 0x20, 0x1c, 0x22, 0x1a, 0x06, 0x12,
+    0x09, 0x0b, 0x0f, 0x19, 0x05, 0x43, 0x00, 0x04,
+    0x05, 0x2b, 0xc9, 0xca, 0xcb, 0x05, 0x04, 0x44,
+    0x00, 0x01, 0x26, 0xd2, 0xd3, 0xd4, 0x52, 0x4b,
+    0x4a, 0x41, 0x00, 0x3b
+};
+
+static char doc_gif[] = {
+    0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x12, 0x00,
+    0x12, 0x00, 0xe6, 0x00, 0x00, 0xfb, 0xfb, 0xfb,
+    0xef, 0xef, 0xef, 0xf8, 0xfb, 0xff, 0xed, 0xf6,
+    0xff, 0xc1, 0xc1, 0xc1, 0xe4, 0xe4, 0xe4, 0xfd,
+    0xfd, 0xfd, 0xd8, 0xeb, 0xff, 0xc0, 0xdf, 0xff,
+    0xfe, 0xff, 0xff, 0xf3, 0xf9, 0xff, 0xc3, 0xe1,
+    0xff, 0xf4, 0xf4, 0xf5, 0xf9, 0xf9, 0xf9, 0x81,
+    0x95, 0xc3, 0x6b, 0x74, 0xa5, 0xce, 0xe7, 0xff,
+    0x5e, 0x61, 0x90, 0x55, 0xa7, 0xed, 0x93, 0xaa,
+    0xd2, 0x7a, 0x83, 0xb0, 0xc0, 0xc0, 0xff, 0xd9,
+    0xe1, 0xed, 0x84, 0x9b, 0xca, 0x8a, 0xa8, 0xd9,
+    0xe4, 0xf1, 0xff, 0x91, 0xb8, 0xea, 0x92, 0xbc,
+    0xef, 0x73, 0x7e, 0xb0, 0xf5, 0xfa, 0xff, 0xf7,
+    0xf7, 0xf7, 0x90, 0xa3, 0xcb, 0xcd, 0xe6, 0xff,
+    0xba, 0xdd, 0xff, 0xd8, 0xe5, 0xf6, 0x6d, 0x77,
+    0xa8, 0x65, 0x6a, 0x9a, 0x87, 0xa1, 0xd2, 0x7f,
+    0x8e, 0xbc, 0x8f, 0xb3, 0xe5, 0x8c, 0xae, 0xdf,
+    0xce, 0xd3, 0xff, 0xf6, 0xfa, 0xff, 0x67, 0x6d,
+    0x9e, 0xfc, 0xfd, 0xff, 0x7d, 0x89, 0xb6, 0x94,
+    0xbf, 0xf2, 0xc6, 0xc6, 0xc6, 0xfe, 0xfe, 0xfe,
+    0xdb, 0xe7, 0xf7, 0x69, 0x70, 0xa2, 0x6f, 0x7a,
+    0xac, 0x72, 0x7c, 0xae, 0x74, 0x80, 0xb2, 0x87,
+    0xa9, 0xdc, 0xd1, 0xe9, 0xff, 0xc9, 0xe4, 0xff,
+    0xb7, 0xb7, 0xb7, 0xeb, 0xeb, 0xeb, 0xb6, 0xb6,
+    0xb6, 0xe9, 0xf5, 0xff, 0x75, 0x78, 0xa3, 0xe1,
+    0xf0, 0xff, 0xdb, 0xed, 0xff, 0xff, 0xff, 0xff,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04,
+    0x01, 0x00, 0x00, 0x41, 0x00, 0x2c, 0x00, 0x00,
+    0x00, 0x00, 0x12, 0x00, 0x12, 0x00, 0x00, 0x07,
+    0xa3, 0x80, 0x41, 0x82, 0x83, 0x84, 0x85, 0x86,
+    0x87, 0x88, 0x2e, 0x36, 0x8b, 0x8c, 0x36, 0x35,
+    0x01, 0x00, 0x87, 0x1b, 0x40, 0x06, 0x00, 0x0d,
+    0x1e, 0x0c, 0x16, 0x35, 0x13, 0x90, 0x86, 0x1a,
+    0x30, 0x40, 0xa1, 0x09, 0x02, 0x31, 0x35, 0x12,
+    0x1f, 0x01, 0x86, 0x27, 0x06, 0xa2, 0x02, 0x1d,
+    0x22, 0x35, 0xb1, 0x2f, 0x86, 0x28, 0xa1, 0x02,
+    0x02, 0x03, 0x3c, 0x3c, 0x29, 0x15, 0x1c, 0x39,
+    0x86, 0x18, 0x2c, 0xb8, 0xb9, 0x3c, 0x3f, 0x3f,
+    0x07, 0x34, 0xbf, 0x85, 0x25, 0x2a, 0x0a, 0xb9,
+    0x3e, 0x3e, 0xc7, 0x37, 0x33, 0xca, 0x84, 0x17,
+    0xce, 0x3c, 0xd0, 0xc6, 0x37, 0x20, 0x23, 0xd5,
+    0x83, 0x0e, 0xba, 0xda, 0x3f, 0x37, 0x38, 0x38,
+    0x0f, 0xdf, 0x82, 0x26, 0xd9, 0xd1, 0xe4, 0xe6,
+    0x0b, 0x32, 0xe9, 0x41, 0x2d, 0x19, 0xed, 0x37,
+    0xe5, 0x0b, 0x08, 0x2b, 0xf2, 0x14, 0xf6, 0x10,
+    0xe6, 0x08, 0x42, 0x90, 0x90, 0xd7, 0xa3, 0xa0,
+    0xc1, 0x83, 0x11, 0x08, 0x18, 0x2a, 0x40, 0x60,
+    0x87, 0xc3, 0x87, 0x0e, 0x09, 0x14, 0x30, 0x04,
+    0x20, 0x80, 0x8e, 0x8b, 0x18, 0x2f, 0x76, 0x42,
+    0xc4, 0xd1, 0x50, 0x20, 0x00, 0x3b
+};
+
+static char back_gif[] = {
+    0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x0a, 0x00,
+    0x09, 0x00, 0xf7, 0x00, 0x00, 0xf8, 0xfa, 0xfb,
+    0x3a, 0x6b, 0x9d, 0xe5, 0xeb, 0xf2, 0x87, 0xa5,
+    0xc3, 0x9d, 0xb5, 0xce, 0xd0, 0xdc, 0xe7, 0xa9,
+    0xbe, 0xd4, 0x74, 0x97, 0xb9, 0x65, 0x8c, 0xb2,
+    0xd9, 0xe2, 0xec, 0xf1, 0xf4, 0xf8, 0xe7, 0xed,
+    0xf3, 0x55, 0x7f, 0xaa, 0xc8, 0xd6, 0xe3, 0xcc,
+    0xcc, 0xcc, 0x91, 0xac, 0xc8, 0x3f, 0x6f, 0x9f,
+    0xfd, 0xfd, 0xfe, 0x4d, 0x7a, 0xa6, 0xac, 0xc1,
+    0xd5, 0x4b, 0x78, 0xa5, 0x33, 0x66, 0x99, 0xff,
+    0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00,
+    0x00, 0x00, 0x0a, 0x00, 0x09, 0x00, 0x00, 0x08,
+    0x3b, 0x00, 0x2d, 0x08, 0x1c, 0x68, 0x61, 0xc1,
+    0x83, 0x02, 0x04, 0x2d, 0x00, 0x20, 0x10, 0x80,
+    0xc2, 0x04, 0x82, 0x13, 0x28, 0x54, 0xa8, 0xe0,
+    0x50, 0x60, 0x02, 0x04, 0x13, 0x27, 0x56, 0x04,
+    0x70, 0x20, 0xa3, 0xc6, 0x87, 0x02, 0x1b, 0x30,
+    0xc8, 0x58, 0x71, 0x60, 0x04, 0x03, 0x10, 0x28,
+    0x82, 0x24, 0xa8, 0x60, 0x80, 0x84, 0x95, 0x09,
+    0x05, 0x38, 0x08, 0x08, 0x00, 0x3b
+};
+#endif
+
+// =============================================================================
+// Internal resources
+// =============================================================================
+CYG_HAL_TABLE_BEGIN(cyg_httpd_ires_table, httpd_ires_table);
+CYG_HAL_TABLE_END(cyg_httpd_ires_table_end, httpd_ires_table);
+__externC cyg_httpd_ires_table_entry cyg_httpd_ires_table[];
+__externC cyg_httpd_ires_table_entry cyg_httpd_ires_table_end[];
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_DIRLIST
+// These threes internal resources are used for the directory listing.
+CYG_HTTPD_IRES_TABLE_ENTRY(cyg_httpd_ires_folder, \
+                           "/___folder__gif.gif", \
+                           folder_gif,            \
+                           sizeof(folder_gif));
+CYG_HTTPD_IRES_TABLE_ENTRY(cyg_httpd_ires_doc,    \
+                           "/___doc__gif.gif",    \
+                           doc_gif,               \
+                           sizeof(doc_gif));
+CYG_HTTPD_IRES_TABLE_ENTRY(cyg_httpd_ires_back,   \
+                           "/___back__gif.gif",   \
+                           back_gif,              \
+                           sizeof(back_gif));
+#endif                           
+
+cyg_httpd_ires_table_entry *
+cyg_httpd_find_ires(char *path_name)
+{
+    cyg_httpd_ires_table_entry *entry = cyg_httpd_ires_table;
+    
+    while (entry != cyg_httpd_ires_table_end)
+    {
+        if (!strcasecmp((char*)path_name, entry->f_pname))
+            return entry;
+        entry++;
+    }
+            
+    return (cyg_httpd_ires_table_entry*)NULL;
+}
+
+void 
+cyg_httpd_send_ires(cyg_httpd_ires_table_entry *entry)
+{
+    httpstate.status_code  = CYG_HTTPD_STATUS_OK;
+
+    // Here we'll look for extension to the file. Consider the case where
+    //  there might be more than one dot in the file name. We'll look for
+    //  the last dot, then we'll check the extension.
+    char *extension = rindex(entry->f_pname, '.');
+    if (extension == NULL)
+        // No extension in the file name.
+        httpstate.mime_type = 0;
+    else
+        httpstate.mime_type = cyg_httpd_find_mime_string(++extension);
+
+    httpstate.payload_len  = entry->f_size;
+    cyg_int32 header_length = cyg_httpd_format_header();
+    
+    // As always, the header is always sent out.
+    send(httpstate.sockets[httpstate.client_index].descriptor, 
+         httpstate.outbuffer, 
+         header_length,
+         0);
+    if (httpstate.mode & CYG_HTTPD_MODE_SEND_HEADER_ONLY) 
+        return;
+    cyg_httpd_write(entry->f_ptr, entry->f_size);
+}
+
+// =============================================================================
+// C callbacks
+// =============================================================================
+CYG_HAL_TABLE_BEGIN(cyg_httpd_handler_table, httpd_handler_table);
+CYG_HAL_TABLE_END(cyg_httpd_handler_table_end, httpd_handler_table);
+
+__externC cyg_httpd_handler_table_entry cyg_httpd_handler_table[];
+__externC cyg_httpd_handler_table_entry cyg_httpd_handler_table_end[];
+
+handler
+cyg_httpd_find_handler(void)
+{
+    cyg_httpd_handler_table_entry *entry = cyg_httpd_handler_table;
+    while (entry != cyg_httpd_handler_table_end)
+    {
+        if (strcmp((const char*)httpstate.url, entry->path) == 0)
+            return entry->h;
+        entry++;
+    }
+            
+    return (handler)NULL;
+}
+
+// =============================================================================
+// Directory listing
+// =============================================================================
+#ifdef CYGOPT_NET_ATHTTPD_USE_DIRLIST
+void
+cyg_httpd_print_directory_entry(char *path_name, 
+                                struct stat *s, 
+                                struct dirent *de)
+{
+    char fname[CYG_HTTPD_MAXPATH];
+    char time_str[32];
+    time_t last_mod = s->st_mtime;
+
+    struct tm *mod_time = gmtime(&last_mod);
+    sprintf(time_str,
+            "%02d-%s-%04d %02d:%02d",
+            mod_time->tm_mday,
+            month_of_year[mod_time->tm_mon],
+            mod_time->tm_year + 1900,
+            mod_time->tm_hour,
+            mod_time->tm_min);
+
+    if (S_ISREG(s->st_mode))
+    {
+        strcpy(fname, path_name);
+        if (fname[strlen(fname)-1] != '/')
+            strcat(fname, "/");
+        strcat(fname, de->d_name);
+        cyg_httpd_cleanup_filename(fname);
+        sprintf(httpstate.outbuffer,
+                "<tr><td><img src='/___doc__gif.gif'></td>"
+                "<td><a href='%s'>%s</a></td>"
+                "<td>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</td>"
+                "<td>%s&nbsp;&nbsp;</td>"
+                "<td style='color:black'>%d</td></tr>",
+                fname,
+                de->d_name,
+                time_str,
+                (int)s->st_size);
+    }
+    else
+    {
+        strcpy(fname, "/");
+        strcat(fname, path_name);
+        if (fname[strlen(fname)-1] != '/')
+            strcat(fname, "/");
+        strcat(fname, de->d_name);
+        cyg_httpd_cleanup_filename(fname);
+        sprintf(httpstate.outbuffer,
+                "<tr><td><img src='/___folder__gif.gif'></td>"
+                "<td><a href='%s/'>%s</a></td>"
+                "<td>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</td>"
+                "<td>%s&nbsp;&nbsp;</td>"
+                "<td style='color:black'></td></tr>",
+                fname,
+                de->d_name,
+                time_str);
+    }
+    cyg_httpd_write_chunked(httpstate.outbuffer, strlen(httpstate.outbuffer));
+}
+
+void
+cyg_httpd_send_directory_listing(char *path_name)
+{
+    struct dirent next_file;
+    struct dirent last_printed;
+    struct stat s;
+    char fname[CYG_HTTPD_MAXPATH];
+
+    cyg_httpd_start_chunked("html");
+    sprintf(httpstate.outbuffer,
+            "<html><body><h3>Index of %s</h3><p></p>"
+            "<table style='font-family:courier'>",
+            path_name);
+    cyg_httpd_write_chunked(httpstate.outbuffer, strlen(httpstate.outbuffer));
+
+    sprintf(httpstate.outbuffer,
+            "<tr><td></td><td align='center' style='border-style:none none"
+            " solid none;border-width:thin'>Name</td>"
+            "<td style='border-style:none none solid none; border-width:thin'>"
+            "&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</td>"
+             "<td  align='center' style='border-style:none none solid none;"
+             " border-width:thin'>Last Modified</td>"
+             "<td style='border-style:none none solid none; border-width:thin'>"
+            "Size</td></tr>");
+    cyg_httpd_write_chunked(httpstate.outbuffer, strlen(httpstate.outbuffer));
+
+    // Provide a pointer to the parent directory.
+    strcpy(fname, path_name);
+    if (fname[strlen(fname)-1] == '/')
+        fname[strlen(fname)-1] = '\0';
+    char *slash = rindex(fname, '/');
+    slash[1] = '\0';
+    sprintf(httpstate.outbuffer,
+            "<tr><td><img src='/___back__gif.gif'></td></td>"
+            "<td><a href='%s' style='color:red'>Parent "
+            "Directory</a></td>"
+            "<td>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</td>"
+            "<td>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</td>"
+            "<td style='color:black'>-</td></tr>",
+            fname);
+    cyg_httpd_write_chunked(httpstate.outbuffer, strlen(httpstate.outbuffer));
+
+    strcpy(fname, CYGDAT_NET_ATHTTPD_SERVEROPT_ROOTDIR);
+    if (fname[strlen(fname)-1] != '/')
+        strcat(fname, "/");
+    strcat(fname, path_name);
+    if (fname[strlen(fname)-1] != '/')
+        strcat(fname, "/");
+    cyg_httpd_cleanup_filename(fname);
+    int abs_path_len = strlen(fname);
+
+    DIR* pdir = opendir(fname);
+    struct dirent *dirent = readdir(pdir);
+
+    // First time for the directories.
+    rewinddir(pdir);
+    memset((void*)&last_printed, 0, sizeof(struct dirent));
+    dirent = readdir(pdir);
+    int new_entry = 1;
+    while (1)
+    {
+        memset((void*)&next_file, 0, sizeof(struct dirent));
+        new_entry = 0;
+        while(dirent)
+        {
+            if (strcmp(dirent->d_name, "..") &&
+                                     strcmp(dirent->d_name, "."))
+                if ((next_file.d_name[0] == '\0') ||
+                      (strcmp(next_file.d_name, dirent->d_name) > 0))
+                    if ((last_printed.d_name[0] == '\0') ||
+                      (strcmp(last_printed.d_name, dirent->d_name) < 0))
+                    {
+                        fname[abs_path_len] = '\0';
+                        strcat(fname, dirent->d_name);
+                        struct stat sp;
+                        stat(fname, &sp);
+                        if (S_ISDIR(sp.st_mode))
+                        {
+                            memcpy(&next_file, dirent, sizeof(struct dirent));
+                            memcpy(&s, &sp, sizeof(struct stat));
+                            new_entry = 1;
+                        }
+                    }
+            dirent = readdir(pdir);
+        }
+        if (new_entry == 0)
+            break;
+        cyg_httpd_print_directory_entry(path_name, &s, &next_file);
+        memcpy(&last_printed, &next_file, sizeof(struct dirent));
+        rewinddir(pdir);
+        dirent = readdir(pdir);
+    }
+
+    // A second time for the files.
+    rewinddir(pdir);
+    memset((void*)&last_printed, 0, sizeof(struct dirent));
+    dirent = readdir(pdir);
+    new_entry = 1;
+    while (1)
+    {
+        memset((void*)&next_file, 0, sizeof(struct dirent));
+        new_entry = 0;
+        while(dirent)
+        {
+            if (strcmp(dirent->d_name, "..") &&
+                                     strcmp(dirent->d_name, "."))
+                if ((next_file.d_name[0] == '\0') ||
+                      (strcmp(next_file.d_name, dirent->d_name) > 0))
+                    if ((last_printed.d_name[0] == '\0') ||
+                      (strcmp(last_printed.d_name, dirent->d_name) < 0))
+                    {
+                        fname[abs_path_len] = '\0';
+                        strcat(fname, dirent->d_name);
+                        struct stat sp;
+                        stat(fname, &sp);
+                        if (S_ISREG(sp.st_mode))
+                        {
+                            memcpy(&next_file, dirent, sizeof(struct dirent));
+                            memcpy(&s, &sp, sizeof(struct stat));
+                            new_entry = 1;
+                        }
+                    }
+            dirent = readdir(pdir);
+        }
+        if (new_entry == 0)
+            break;
+        cyg_httpd_print_directory_entry(path_name, &s, &next_file);
+        memcpy(&last_printed, &next_file, sizeof(struct dirent));
+        rewinddir(pdir);
+        dirent = readdir(pdir);
+    }
+
+    strcpy(httpstate.outbuffer, "</table><html><body>");
+    cyg_httpd_write_chunked(httpstate.outbuffer, strlen(httpstate.outbuffer));
+    cyg_httpd_end_chunked();
+    closedir(pdir);
+}
+#endif
diff --git a/packages/net/athttpd/v2_0/src/http.c b/packages/net/athttpd/v2_0/src/http.c
new file mode 100644 (file)
index 0000000..bb7fc28
--- /dev/null
@@ -0,0 +1,1048 @@
+/* =================================================================
+ *
+ *      http.c
+ *
+ *      Handles the client requests.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005, 2007 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: Sergei Gavrikov (w3sg@SoftHome.net)
+ *                Lars Povlsen    (lpovlsen@vitesse.com)
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+
+#include <pkgconf/hal.h>
+#include <pkgconf/kernel.h>
+#include <cyg/kernel/kapi.h>           // Kernel API.
+#include <cyg/infra/diag.h>            // For diagnostic printing.
+#include <network.h>
+#include <time.h>
+
+#include <cyg/hal/hal_tables.h>
+#include <cyg/fileio/fileio.h>
+#include <stdio.h>                     // sprintf().
+#include <stdlib.h>
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER
+#include <cyg/objloader/elf.h>
+#include <cyg/objloader/objelf.h>
+#endif
+
+#include <cyg/athttpd/http.h>
+#include <cyg/athttpd/socket.h>
+#include <cyg/athttpd/handler.h>
+#include <cyg/athttpd/forms.h>
+
+cyg_int32 debug_print = 0;
+
+const char *day_of_week[7] = {"Sun", "Mon", "Tue", "Wed", 
+                                 "Thu", "Fri", "Sat"};
+const char *month_of_year[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", 
+                                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
+const char *home_pages[] = {"index.html",   "index.htm",
+                            "default.html", "home.html"};
+CYG_HAL_TABLE_BEGIN(cyg_httpd_mime_table, httpd_mime_table);
+CYG_HAL_TABLE_END(cyg_httpd_mime_table_end, httpd_mime_table);
+
+__externC cyg_httpd_mime_table_entry cyg_httpd_mime_table[];
+__externC cyg_httpd_mime_table_entry cyg_httpd_mime_table_end[];
+
+// Standard handlers added by default. Correspond to the most used extensions.
+// The user can add his/her own later.
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_htm_entry, "htm",
+                                       "text/html; charset=iso-8859-1");
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_html_entry, "html", 
+                                       "text/html; charset=iso-8859-1");
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_gif_entry, "gif", "image/gif");
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_jpg_entry, "jpg", "image/jpg");
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_png_entry, "png", "image/png");
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_css_entry, "css", "text/css");
+CYG_HTTPD_MIME_TABLE_ENTRY(hal_js_entry, "js", "application/x-javascript");
+
+void 
+cyg_httpd_send_error(cyg_int32 err_type)
+{
+    httpstate.status_code = err_type;
+    
+    // Errors pages close the socket and are never cached.
+    httpstate.mode |= CYG_HTTPD_MODE_NO_CACHE;
+
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+    diag_printf("Sending error: %d\n", err_type);
+#endif    
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_FS
+    // Check if the user has defines his own error pages.
+    struct stat sp;
+    char file_name[CYG_HTTPD_MAXPATH];
+    strcpy(file_name, CYGDAT_NET_ATHTTPD_SERVEROPT_ROOTDIR);
+    if (file_name[strlen(file_name)-1] != '/')
+        strcat(file_name, "/");
+    strcat(file_name, CYGDAT_NET_ATHTTPD_SERVEROPT_ERRORDIR);
+    if (file_name[strlen(file_name)-1] != '/')
+        strcat(file_name, "/");
+    sprintf(file_name + strlen(file_name), "error_%d.html", err_type);
+    cyg_httpd_cleanup_filename(file_name);
+    cyg_int32 rc = stat(file_name, &sp);
+    if (rc == 0)
+    {
+        char *extension = rindex(file_name, '.');
+        if (extension == NULL)
+            // No extension in the file name.
+            httpstate.mime_type = 0;
+        else
+            httpstate.mime_type = cyg_httpd_find_mime_string(++extension);
+
+        httpstate.payload_len  = sp.st_size;
+        cyg_int32 header_length = cyg_httpd_format_header();
+        cyg_httpd_write(httpstate.outbuffer, header_length);
+    
+        // File found.
+        FILE *fp = fopen(file_name, "r");
+        if(fp == NULL)
+            return;
+
+        ssize_t payload_size = fread(httpstate.outbuffer, 
+                                     1, 
+                                     CYG_HTTPD_MAXOUTBUFFER, 
+                                     fp);
+        while (payload_size > 0)
+        {
+            ssize_t bytes_written = cyg_httpd_write_chunked(httpstate.outbuffer, 
+                                                            payload_size);
+            if (bytes_written != payload_size)
+                break;
+
+            payload_size = fread(httpstate.outbuffer, 
+                                 1, 
+                                 CYG_HTTPD_MAXOUTBUFFER, 
+                                 fp);
+        }
+
+        fclose(fp);
+        return;
+    }
+#endif    
+
+    // Because the size of the frame is not known upfront (every error message
+    //  is different and thus has different length) we use chunked frames to
+    //  send the message out.
+#if defined(CYGOPT_NET_ATHTTPD_CLOSE_CHUNKED_CONNECTIONS)
+    httpstate.mode |= CYG_HTTPD_MODE_CLOSE_CONN;
+#endif
+    
+    httpstate.mode |= CYG_HTTPD_MODE_TRANSFER_CHUNKED;
+    httpstate.status_code = err_type;
+    httpstate.last_modified = -1;
+    httpstate.mime_type = "text/html";
+    cyg_int32 header_length = cyg_httpd_format_header();
+    cyg_httpd_write(httpstate.outbuffer, header_length);
+    
+    // If no file has been defined, send a simple notification. We must use
+    //  chunked frames, because we do not know upfron the length of the
+    //  packet we have to send.
+    strcpy(httpstate.outbuffer,
+           "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n");
+    switch (err_type)
+    {
+    case CYG_HTTPD_STATUS_MOVED_PERMANENTLY:
+        strcat(httpstate.outbuffer,
+               "<html><head><title>301 Moved Permanently</title></head>\r\n"
+               "<body><h1>Moved Permanently</h1>\r\n"
+               "<p>The document has moved <a href=\"");
+        strcat(httpstate.outbuffer, httpstate.url);
+        strcat(httpstate.outbuffer, "\">here</a>.\r\n");
+        break;
+    case CYG_HTTPD_STATUS_MOVED_TEMPORARILY:
+        strcat(httpstate.outbuffer, 
+               "<html><head><title>302 Found</title></head>\r\n"
+               "<body><h1>Redirect</h1>\r\n"
+               "<p>Please continue <a href=\"");
+        strcat(httpstate.outbuffer, httpstate.url);
+        strcat(httpstate.outbuffer, "\">here</a>.\r\n");
+        break;
+    case CYG_HTTPD_STATUS_NOT_AUTHORIZED:
+        strcat(httpstate.outbuffer, 
+               "<html><head><title>401 Not Authorized</title></head>\r\n");
+        strcat(httpstate.outbuffer, 
+               "<body><p>Authorization required to access this URL.</p>\r\n");
+        break;    
+    case CYG_HTTPD_STATUS_NOT_MODIFIED:
+        cyg_httpd_end_chunked();
+        return;
+    case CYG_HTTPD_STATUS_NOT_FOUND:
+        strcat(httpstate.outbuffer, 
+               "<html><head><title>404 Not Found</title></head>\r\n");
+        sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                "<p>The requested URL: %s was not found on this server</p>\r\n",
+                httpstate.url);
+        break;
+    case CYG_HTTPD_STATUS_SYSTEM_ERROR:
+        strcat(httpstate.outbuffer, 
+               "<html><head><title>500 Server Error</title></head>\r\n");
+        strcat(httpstate.outbuffer, 
+               "<p>The server encountered an unexpected condition that "
+               "prevented it from fulfilling the request"
+               " by the client</p>\r\n");
+        break;
+    case CYG_HTTPD_STATUS_NOT_IMPLEMENTED:
+        strcat(httpstate.outbuffer, 
+               "<html><head><title>501 Not Implemented</title></head>\r\n");
+        strcat(httpstate.outbuffer, 
+               "<p>The method requested is not implemented</p>\r\n");
+        break;
+    default:
+        strcat(httpstate.outbuffer, 
+               "<html><head><title>400 Bad Request</title></head>\r\n");
+        strcat(httpstate.outbuffer, 
+               "<p>Bad request</p>\r\n");
+        break;
+    }
+    
+    sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+            "<hr>%s at %d.%d.%d.%d Port %d\r\n</body></html>\r\n",
+            CYGDAT_NET_ATHTTPD_SERVEROPT_SERVERID,
+            httpstate.host[0],
+            httpstate.host[1],
+            httpstate.host[2],
+            httpstate.host[3],
+            CYGNUM_NET_ATHTTPD_SERVEROPT_PORT);
+    
+    cyg_httpd_write_chunked(httpstate.outbuffer, strlen(httpstate.outbuffer));
+    cyg_httpd_end_chunked();
+}
+
+// Return a time_t that is always UTC (aka GMT).
+time_t
+cyg_httpd_parse_date(char *time)
+{
+    int    i;
+    char   month[4];
+    struct tm tm_mod;
+
+    // We are going to get rid of the day of the week. This is always the first
+    //  part of the string, separated by a blank.
+    time = strchr( time, ' ');
+    if ( time == NULL)
+        return 0;
+    time++;
+
+    /// RFC1123. The date is in the format: Sun, 06 Nov 1994 08:49:37 GMT.
+    cyg_int32 rc = sscanf(time,
+                          "%2d %3s %4d %2d:%2d:%2d GMT",
+                          &tm_mod.tm_mday,
+                          month,
+                          &tm_mod.tm_year,
+                          &tm_mod.tm_hour,
+                          &tm_mod.tm_min,
+                          &tm_mod.tm_sec);
+    if (rc != 6)
+    {
+        // RFC1036. The date is in the format: Sunday, 06-Nov-94 08:49:37 GMT.
+        rc = sscanf(time,
+                    "%2d-%3s-%2d %2d:%2d:%2d GMT",
+                    &tm_mod.tm_mday,
+                    month,
+                    &tm_mod.tm_year,
+                    &tm_mod.tm_hour,
+                    &tm_mod.tm_min,
+                    &tm_mod.tm_sec);
+        if (rc != 6)
+        {
+            // asctime().
+            rc = sscanf(time,"%3s %2d %2d:%2d:%2d %4d",
+                        month,
+                        &tm_mod.tm_mday,
+                        &tm_mod.tm_hour,
+                        &tm_mod.tm_min,
+                        &tm_mod.tm_sec,
+                        &tm_mod.tm_year);
+            if (rc != 6)
+                return 0;
+        }
+    }
+
+    for (i = 0; i < sizeof(month_of_year); i++)
+        if (strcmp(month, month_of_year[i]) == 0)
+        {
+            tm_mod.tm_mon = i;
+            if (tm_mod.tm_year > 1900)
+                tm_mod.tm_year -= 1900;
+            return mktime(&tm_mod);
+        }
+
+    return 0;
+}
+
+// Finds the mime string into the mime_table associated with a specific 
+//  extension. Returns the MIME type to send in the header, or NULL if the
+//  extension is not in the table.
+char*
+cyg_httpd_find_mime_string(char *ext)
+{
+    cyg_httpd_mime_table_entry *entry = cyg_httpd_mime_table;
+
+    while (entry != cyg_httpd_mime_table_end)
+    {
+        if (!strcmp((const char*)ext, entry->extension))
+            return entry->mime_string;
+        entry++;
+    }
+            
+    return (char*)0;
+}
+
+void
+cyg_httpd_cleanup_filename(char *filename)
+{
+    char *src = strstr(filename, "//");
+    while (src != 0)
+    {
+        strcpy(src + 1, src + 2);
+        src = strstr(filename, "//");
+    }
+
+    src = strstr(filename, "/./");
+    while (src != 0)
+    {
+        strcpy(src + 1, src + 3);
+        src = strstr(filename, "/./");
+    }
+
+    src = strstr(filename, "/../");
+    while (src != 0)
+    {
+        char *comp1 = filename, *comp2 = filename;
+
+        // Search the path component before this redirection.
+        while ((comp1 = strchr(comp1, '/')) != src)
+            comp2 = ++comp1;
+
+        strcpy(comp2, src + 4);
+        src = strstr(filename, "/../");
+    }
+}
+
+cyg_int32
+cyg_httpd_initialize(void)
+{
+    httpstate.post_data = NULL;
+    httpstate.needs_auth = (cyg_httpd_auth_table_entry *)0;
+    return 0;
+}
+
+void
+cyg_httpd_append_homepage(char *root)
+{
+#ifdef CYGOPT_NET_ATHTTPD_USE_FS
+    struct stat sp;
+    cyg_int32 i;
+
+    cyg_int32 root_len = strlen(root);
+    for (i = 0; i < sizeof(home_pages)/sizeof(char*); i++)
+    {
+        root[root_len] = '\0';
+        sprintf(root + root_len, "%s", home_pages[i]);
+        cyg_int32 rc = stat(root, &sp);
+        if (rc == 0)
+            return;
+    }
+    root[root_len] = 0;
+#endif    
+    
+#ifdef CYGDAT_NET_ATHTTPD_ALTERNATE_HOME    
+    if (strcmp(root, "/") == 0)
+        // The client is trying to open the main index file.
+        strcat(root, CYGDAT_NET_ATHTTPD_ALTERNATE_HOME);
+#endif    
+}
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_FS
+void
+cyg_httpd_send_file(char *name)
+{
+    cyg_int32  err;
+    FILE      *fp;
+    struct stat sp;
+    char       file_name[CYG_HTTPD_MAXPATH];
+
+    strcpy(file_name, CYGDAT_NET_ATHTTPD_SERVEROPT_ROOTDIR);
+    if (file_name[strlen(file_name)-1] != '/')
+        strcat(file_name, "/");
+    strcat(file_name, name);
+    cyg_httpd_cleanup_filename(file_name);
+        
+    // Check if the file is in the file system. This will also give us the
+    //  size of the file, to be used in the HTTP header.
+    cyg_int32 rc = stat(file_name, &sp);
+    if (rc < 0)
+    {
+        // Before giving up, we make a last ditch attempt at finding a file
+        //  within the internal resources of the server. The user can add
+        //  his/her own files to the table.
+        cyg_httpd_ires_table_entry *p = cyg_httpd_find_ires(name);
+        if (p != NULL)
+        {
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+            diag_printf("Sending Internal Resource: %s\n", name);
+#endif    
+            cyg_httpd_send_ires(p);
+        }    
+        else    
+            cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_FOUND);
+        return;
+    }
+    
+    if (S_ISDIR(sp.st_mode))
+    {
+        char tmp_url[CYG_HTTPD_MAXURL];
+        strcpy(tmp_url, httpstate.url);
+        // Directories need a trialing slash, and if missing, we'll redirect
+        //  the client to the right URL. This is called (appropriately
+        //  enough) "Trailing-Slash Redirection". 
+        if (name[strlen(name)-1] != '/')
+        {
+            sprintf(httpstate.url,
+                    "http://%d.%d.%d.%d:%d%s/",
+                    httpstate.host[0],
+                    httpstate.host[1],
+                    httpstate.host[2],
+                    httpstate.host[3],
+                    CYGNUM_NET_ATHTTPD_SERVEROPT_PORT,
+                    tmp_url);
+            cyg_httpd_send_error(CYG_HTTPD_STATUS_MOVED_PERMANENTLY);
+            return;
+        }
+
+        // We are going to try to locate an index page in the directory we got
+        //  in the URL. 
+        cyg_httpd_append_homepage(file_name);
+        if (file_name[strlen(file_name)-1] == '/')
+        {
+#ifdef CYGOPT_NET_ATHTTPD_USE_DIRLIST
+            // No home page found, we are sending a directory listing.
+            cyg_httpd_send_directory_listing(name);
+#else
+            cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_FOUND);
+#endif
+            return;
+        }
+        stat(file_name, &sp);
+    }
+    
+    httpstate.last_modified = sp.st_mtime;
+
+    // Let's see if we luck out and can send a 304.
+    if ((httpstate.modified_since != -1) && 
+                   (httpstate.modified_since >= httpstate.last_modified))
+    {                   
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_MODIFIED);
+        return;
+    }    
+    else    
+        httpstate.status_code = CYG_HTTPD_STATUS_OK;
+
+    // Here we'll look for an extension to the file. Consider the case where
+    //  there might be more than one dot in the file name. We'll look for just
+    //  the last one, then we'll check the extension.
+    char *extension = rindex(file_name, '.');
+    if (extension == NULL)
+        httpstate.mime_type = 0;
+    else    
+        httpstate.mime_type = cyg_httpd_find_mime_string(++extension);
+
+    httpstate.payload_len  = sp.st_size;
+    httpstate.mode &= ~CYG_HTTPD_MODE_NO_CACHE;
+    cyg_int32 payload_size = cyg_httpd_format_header();
+    if ((httpstate.mode & CYG_HTTPD_MODE_SEND_HEADER_ONLY) != 0)
+    {                 
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+        diag_printf("Sending header only for URL: %s\n", file_name);
+#endif    
+        send(httpstate.sockets[httpstate.client_index].descriptor, 
+             httpstate.outbuffer, 
+             payload_size,
+             0);
+        return;
+    }
+
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+    diag_printf("Sending file: %s\n", file_name);
+#endif    
+    fp = fopen(file_name, "r");
+    if (fp == NULL)
+    {
+        // We should really read errno and send messages accordingly...
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_SYSTEM_ERROR);
+        return;
+    }
+    
+    // Fill up the rest of the buffer and send it out.
+    cyg_int32 bread = fread(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                            1, 
+                            CYG_HTTPD_MAXOUTBUFFER - payload_size,
+                            fp);
+    cyg_httpd_write(httpstate.outbuffer, payload_size + bread);
+
+    ssize_t bytes_written = 0;
+    sp.st_size -= bread;
+    while (bytes_written < sp.st_size)
+    {
+        bread = fread(httpstate.outbuffer, 1, CYG_HTTPD_MAXOUTBUFFER, fp);
+        bytes_written += cyg_httpd_write(httpstate.outbuffer, bread);
+    }    
+    
+    err = fclose(fp);
+    if (err < 0)
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_SYSTEM_ERROR);
+}
+#endif
+
+cyg_int32
+cyg_httpd_format_header(void)
+{
+    sprintf(httpstate.outbuffer, "HTTP/1.1 %d", httpstate.status_code);
+    time_t time_val = time(NULL);
+    
+    // Error messages (i.e. with status other than OK, automatically add
+    //  the no-cache header.
+    switch (httpstate.status_code)
+    {
+    case CYG_HTTPD_STATUS_MOVED_PERMANENTLY:
+        strcat(httpstate.outbuffer, " Moved Permanently\r\n");
+        strcat(httpstate.outbuffer, "Location: ");
+        strcat(httpstate.outbuffer, httpstate.url);
+        strcat(httpstate.outbuffer, "\r\n");
+        sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                "Content-Length: %d\r\n",
+                httpstate.payload_len);
+        break;
+    case CYG_HTTPD_STATUS_MOVED_TEMPORARILY:
+        strcat(httpstate.outbuffer, " Found\r\n");
+        strcat(httpstate.outbuffer, "Location: ");
+        strcat(httpstate.outbuffer, httpstate.url);
+        strcat(httpstate.outbuffer, "\r\n");
+        sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                "Content-Length: %d\r\n",
+                httpstate.payload_len);
+        break;
+#ifdef CYGOPT_NET_ATHTTPD_USE_AUTH
+    case CYG_HTTPD_STATUS_NOT_AUTHORIZED:
+        // A 401 error closes the connection right away.
+        httpstate.mode |= CYG_HTTPD_MODE_CLOSE_CONN;
+        strcat(httpstate.outbuffer, " Not Authorized\r\n");
+        
+        // Here we should set the proper header based on the authentication
+        //  required (httpstate.needs_authMode) but for now, with only
+        //  Basic Authentication supported, there is no need to do so.
+        if (httpstate.needs_auth->auth_mode == CYG_HTTPD_AUTH_BASIC)
+        {
+            sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                    "WWW-Authenticate: Basic realm=\"%s\"\r\n",
+                    httpstate.needs_auth->auth_domainname);
+        }
+        else             
+        {
+            sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                     "WWW-Authenticate: Digest realm=\"%s\", ",
+                     httpstate.needs_auth->auth_domainname);
+            strftime(cyg_httpd_md5_nonce, 
+                     33,
+                     TIME_FORMAT_RFC1123,
+                     gmtime(&time_val));
+            sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                    "nonce=\"%s\", ", cyg_httpd_md5_nonce);
+            sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                    "opaque=\"%s\", ", 
+                    CYG_HTTPD_MD5_AUTH_OPAQUE);
+            sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                    "stale=false, algorithm=%s, qop=\"%s\"\r\n",
+                    CYG_HTTPD_MD5_AUTH_NAME,
+                    CYG_HTTPD_MD5_AUTH_QOP);
+        }
+        break;
+#endif
+    case CYG_HTTPD_STATUS_NOT_MODIFIED:
+        strcat(httpstate.outbuffer, " Not Modified\r\n");
+        break;
+    case CYG_HTTPD_STATUS_NOT_FOUND:
+        strcat(httpstate.outbuffer, " Not Found\r\n");
+        sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                "Content-Length: %d\r\n", 
+                httpstate.payload_len);
+        break;
+    case CYG_HTTPD_STATUS_METHOD_NOT_ALLOWED:
+        strcat(httpstate.outbuffer, " Method Not Allowed\r\n");
+        break;
+    default:
+        strcat(httpstate.outbuffer, " OK\r\n");
+        if ((httpstate.mode & CYG_HTTPD_MODE_TRANSFER_CHUNKED) == 0)
+            sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+                    "Content-Length: %d\r\n", 
+                    httpstate.payload_len);
+        break;
+    }
+
+    strcat(httpstate.outbuffer, "Date: ");
+    strftime(httpstate.outbuffer + strlen(httpstate.outbuffer), 
+             CYG_HTTPD_MAXOUTBUFFER - strlen(httpstate.outbuffer),
+             TIME_FORMAT_RFC1123,
+             gmtime(&time_val));
+    strcat(httpstate.outbuffer, "\r\n");
+    
+    sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer), 
+            "Server: %s\r\n", 
+            CYGDAT_NET_ATHTTPD_SERVEROPT_SERVERID);
+    
+    if (httpstate.mode & CYG_HTTPD_MODE_CLOSE_CONN)
+        strcat(httpstate.outbuffer, "Connection: close\r\n");
+    else
+        strcat(httpstate.outbuffer, "Connection: keep-alive\r\n");
+
+    // When we cannot find the appropriate MIME type, we'll send a default type.
+    if (httpstate.mime_type == 0)
+        httpstate.mime_type = CYGDAT_NET_ATHTTPD_DEFAULT_MIME_TYPE;
+    sprintf(httpstate.outbuffer + strlen(httpstate.outbuffer),
+            "Content-Type: %s\r\n", 
+            httpstate.mime_type);
+
+    if (httpstate.mode & CYG_HTTPD_MODE_TRANSFER_CHUNKED)
+        strcat(httpstate.outbuffer, "Transfer-Encoding: chunked\r\n");
+
+    if (httpstate.mode & CYG_HTTPD_MODE_NO_CACHE)
+        strcat(httpstate.outbuffer, "Cache-Control: no-cache\r\n");
+        
+    if (httpstate.last_modified != -1)
+    {
+        time_val = httpstate.last_modified;
+        strcat(httpstate.outbuffer, "Last-Modified: "); 
+        strftime(httpstate.outbuffer + strlen(httpstate.outbuffer), 
+                 CYG_HTTPD_MAXOUTBUFFER - strlen(httpstate.outbuffer),
+                 TIME_FORMAT_RFC1123,
+                 gmtime(&time_val));
+        strcat(httpstate.outbuffer, "\r\n");
+
+#if (CYGOPT_NET_ATHTTPD_DOCUMENT_EXPIRATION_TIME != 0)                 
+        time_val += CYGOPT_NET_ATHTTPD_DOCUMENT_EXPIRATION_TIME;
+        strcat(httpstate.outbuffer, "Expires: "); 
+        strftime(httpstate.outbuffer + strlen(httpstate.outbuffer), 
+                 CYG_HTTPD_MAXOUTBUFFER - strlen(httpstate.outbuffer),
+                 TIME_FORMAT_RFC1123,
+                 gmtime(&time_val));
+        strcat(httpstate.outbuffer, "\r\n");
+#endif
+    }        
+                 
+    // There must be 2 carriage returns between the header and the body, 
+    //  so if you modify this function make sure that there is another 
+    //  CRLF already terminating the buffer thus far.
+    strcat(httpstate.outbuffer, "\r\n");
+    return strlen(httpstate.outbuffer);
+}
+
+void
+cyg_httpd_handle_method_GET(void)
+{
+#if defined(CYGOPT_NET_ATHTTPD_USE_CGIBIN_OBJLOADER) ||\
+                             defined(CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL)
+    // If the URL is a CGI script, there is a different directory...
+    if (httpstate.url[0] == '/' &&
+                    !strncmp(httpstate.url + 1, 
+                              CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR, 
+                              strlen(CYGDAT_NET_ATHTTPD_SERVEROPT_CGIDIR)))
+    {                              
+        cyg_httpd_exec_cgi();
+        return;
+    }
+    // If the OBJLOADER package is not loaded, then the request for a library
+    //  will likely generate a 404.
+#endif    
+
+    // User defined handlers take precedence over other forms of response.
+    handler h = cyg_httpd_find_handler();
+    if (h != 0)
+    {
+        h(&httpstate);
+        return;
+    }
+    
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_FS
+    // No handler, we'll redirect to the file system.
+    cyg_httpd_send_file(httpstate.url);
+#else
+    // If we do not have a file system, we look for the file within the 
+    //  internal resources of the server. The user can add his/her own files
+    //  to the table.
+    if (strcmp(httpstate.url, "/") == 0)
+    {
+        int i;
+        cyg_httpd_ires_table_entry *p;
+        for (i = 0; i < sizeof(home_pages)/sizeof(char*); i++)
+        {
+            httpstate.url[1] = '\0';
+            strcat(httpstate.url, home_pages[i]);
+            p = cyg_httpd_find_ires(httpstate.url);
+            if (p != NULL)
+            {
+                cyg_httpd_send_ires(p);
+                return;
+            }    
+        }        
+    }
+    else
+    {
+        cyg_httpd_ires_table_entry *p = cyg_httpd_find_ires(httpstate.url);
+        if (p != NULL)
+        {
+            cyg_httpd_send_ires(p);
+            return;
+        }    
+    }        
+    cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_FOUND);
+#endif    
+}
+
+char*
+cyg_httpd_get_URL(char* p)
+{
+    char* dest = httpstate.url;
+
+    // First get rid of multiple leading slashes.
+    while ((p[0] == '/') && (p[1] == '/'))
+       p++;
+
+    // Store the url, and check if there is a form result in it.
+    while ((*p != ' ') && (*p != '?') &&
+            ((dest - httpstate.url) <= CYG_HTTPD_MAXURL))
+    {
+        // Look for encoded characters in the URL.
+        if (*p == '%') 
+        {
+            p++;
+            cyg_int8 ch = cyg_httpd_from_hex(*p++);
+            if (ch == -1)
+            {
+                cyg_httpd_send_error(CYG_HTTPD_STATUS_BAD_REQUEST);
+                return (char*)0;
+            }
+            *dest = ch << 4;
+            ch = cyg_httpd_from_hex(*p++);
+            if (ch == -1)
+            {
+                cyg_httpd_send_error(CYG_HTTPD_STATUS_BAD_REQUEST);
+                return (char*)0;
+            }
+            *dest += ch;
+            dest++;
+        }
+        else 
+            *dest++ = *p++;
+    }
+
+    // Terminate the file name...
+    *dest = '\0';
+
+    // The URL must start with a leading slash.
+    if (httpstate.url[0] != '/') 
+    {
+        cyg_httpd_send_error(CYG_HTTPD_STATUS_BAD_REQUEST);
+        return (char*)0;
+    }
+    return p;
+}
+
+char*
+cyg_httpd_parse_POST(char* p)
+{
+    httpstate.method = CYG_HTTPD_METHOD_POST;
+    char *cp = cyg_httpd_get_URL(p);
+    if (cp == 0)
+        return (char*)0;
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+    diag_printf("POST Request URL: %s\n", httpstate.url);
+#endif    
+
+    while (*cp++ != '\n');
+    return cp;
+}
+
+char*
+cyg_httpd_parse_GET(char* p)
+{
+    char *cp = cyg_httpd_get_URL(p);
+    if (cp == 0)
+        return 0;
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+    if ( httpstate.method == CYG_HTTPD_METHOD_GET)
+        diag_printf("GET Request URL: %s\n", httpstate.url);
+    else    
+        diag_printf("HEAD Request URL: %s\n", httpstate.url);
+#endif    
+
+    if (*cp == '?')
+        // If we have a GET header with form variables we'll get the
+        //  variables out of it and store them in the variable table.
+        // Can we assume that HEAD request can have form variables?
+        // That will be a yes until I learn otherwise.
+        cp = cyg_httpd_store_form_data(++cp);
+
+    // Run to end of line.
+    while (*cp++ != '\n');
+    return cp;
+}
+
+char*
+cyg_httpd_process_header(char *p)
+{
+#ifdef CYGOPT_NET_ATHTTPD_USE_AUTH
+    // Clear the previous request's response. The client properly authenticated
+    //  will always reinitialize this variable during the header parsing
+    //  process. This variable is also commandeered to hold the hashed
+    //  username:password duo in the basic authentication.
+    cyg_httpd_md5_response[0] = '\0';
+#endif
+
+    // The deafult for HTTP 1.1 is keep-alive connections, unless specifically
+    //  closed by the far end.
+    httpstate.mode &= ~(CYG_HTTPD_MODE_CLOSE_CONN | CYG_HTTPD_MODE_FORM_DATA |\
+                                        CYG_HTTPD_MODE_SEND_HEADER_ONLY);
+    httpstate.modified_since = -1;
+    httpstate.content_len = 0;
+    while (p < httpstate.request_end)
+    {
+        if (strncasecmp("GET ", p, 4) == 0)
+        {
+            // We need separate flags for HEAD and SEND_HEADERS_ONLY since
+            //  we can send a header only even in the case of a GET request
+            //  (as a 304 response.)
+            httpstate.method = CYG_HTTPD_METHOD_GET;
+            httpstate.mode &= ~CYG_HTTPD_MODE_SEND_HEADER_ONLY;
+            p = cyg_httpd_parse_GET(p + 4);
+            if (p ==0)
+                return (char*)0;
+        }
+        else if (strncasecmp("POST ", p, 5) == 0)
+        {
+            p = cyg_httpd_parse_POST(p + 5);
+            if (p ==0)
+                return (char*)0;
+        }
+        else if (strncasecmp("HEAD ", p, 5) == 0)
+        {
+            httpstate.method = CYG_HTTPD_METHOD_HEAD;
+            httpstate.mode |= CYG_HTTPD_MODE_SEND_HEADER_ONLY;
+            p = cyg_httpd_parse_GET(p + 5);
+            if (p ==0)
+                return (char*)0;
+        }
+        else if (strncasecmp(p, "Content-Length: ", 16) == 0)
+        {
+            p = strchr(p, ':') + 2;
+            if (p)
+                // In the case of a POST request, this is the total length of
+                //  the payload, which might be spread across several frames.
+                httpstate.content_len = atoi(p);
+            while (*p++ != '\n');
+        }
+        else if (strncasecmp(p, "Content-Type: ", 14) == 0)
+        {
+            p = strchr(p, ':') + 2;
+            if (p)
+                // In the case of a POST request, this is the total length of
+                //  the payload, which might be spread across several frames.
+                if (strncasecmp(p,
+                                "application/x-www-form-urlencoded",
+                                33) == 0)
+                    httpstate.mode |= CYG_HTTPD_MODE_FORM_DATA;
+            while (*p++ != '\n');
+        }
+        else if (strncasecmp("Host:", p, 5) == 0)
+        {
+            p += 5;
+            if (*p == ' ')
+                p++;
+            sscanf(p,
+                   "%d.%d.%d.%d",
+                   &httpstate.host[0],
+                   &httpstate.host[1],
+                   &httpstate.host[2],
+                   &httpstate.host[3]);
+            while (*p++ != '\n');
+        }
+        else if (strncasecmp("If-Modified-Since:", p, 18) == 0)
+        {
+            p += 18;
+            if ( *p == ' ')
+                p++;
+            httpstate.modified_since = cyg_httpd_parse_date(p);
+            while (*p++ != '\n');
+        }
+#ifdef CYGOPT_NET_ATHTTPD_USE_AUTH
+        else if (strncasecmp("Authorization:", p, 14) == 0)
+        {
+            p += 14;
+            while (*p == ' ')
+                p++;
+            if (strncasecmp("Basic", p, 5) == 0)
+            {
+                p += 5;
+                while (*p == ' ')
+                    p++;
+                cyg_int32 auth_data_length = 0;    
+                while (*p != '\n') 
+                {
+                    // We are going to copy only up to 
+                    //  AUTH_STORAGE_BUFFER_LENGTH characters to prevent
+                    //  overflow of the cyg_httpd_md5_response variable.
+                    if (auth_data_length < AUTH_STORAGE_BUFFER_LENGTH)
+                        if ((*p != '\r') && (*p != ' '))
+                            cyg_httpd_md5_response[auth_data_length++] = *p;
+                    p++;
+                }    
+                p++;        
+                cyg_httpd_md5_response[auth_data_length] = '\0';
+            }
+            else if (strncasecmp(p, "Digest", 6) == 0)
+            {
+                p += 6;
+                while (*p == ' ')
+                   p++;
+                while (*p != '\n')
+                {
+                    if (strncasecmp(p, "realm=", 6) == 0)
+                        p = cyg_httpd_digest_skip(p + 6);
+                    else if (strncasecmp(p, "username=", 9) == 0)
+                        p = cyg_httpd_digest_skip(p + 9);
+                    else if (strncasecmp(p, "nonce=", 6) == 0)
+                        p = cyg_httpd_digest_skip(p + 6);
+                    else if (strncasecmp(p, "response=", 9) == 0)
+                        p = cyg_httpd_digest_data(cyg_httpd_md5_response, 
+                                                  p + 9);
+                    else if (strncasecmp(p, "cnonce=", 7) == 0)
+                        p = cyg_httpd_digest_data(cyg_httpd_md5_cnonce, p + 7);
+                    else if (strncasecmp(p, "qop=", 4) == 0)
+                        p = cyg_httpd_digest_skip(p + 4);
+                    else if (strncasecmp(p, "nc=", 3) == 0)
+                        p = cyg_httpd_digest_data(cyg_httpd_md5_noncecount, 
+                                                  p + 3);
+                    else if (strncasecmp(p, "algorithm=", 10) == 0)
+                        p = cyg_httpd_digest_skip(p + 10);
+                    else if (strncasecmp(p, "opaque=", 7) == 0)
+                        p = cyg_httpd_digest_skip(p + 7);
+                    else if (strncasecmp(p, "uri=", 4) == 0)
+                        p = cyg_httpd_digest_skip(p + 4);
+                    else
+                        p++;    
+                }
+                p++;
+            }    
+            else
+                while (*p++ != '\n');
+        }   
+#endif // CYGOPT_NET_ATHTTPD_USE_AUTH
+        else if (strncasecmp(p, "Connection:", 11) == 0)
+        {
+            p += 11;
+            while (*p == ' ')
+               p++;
+            if (strncasecmp(p, "close", 5) == 0)
+                httpstate.mode |= CYG_HTTPD_MODE_CLOSE_CONN;
+            while (*p++ != '\n');
+        }
+        else
+            // We'll just dump the rest of the line and move on to the next.
+            while (*p++ != '\n');
+    }
+    return p;
+}
+
+void
+cyg_httpd_process_method(void)
+{
+    char* p = httpstate.inbuffer;
+    
+    // Some browsers send an extra '\r\n' after the POST data that is not
+    //  accounted in the "Content-Length:" field. We are going to junk all
+    //  the leading returns and line carriages we find.
+    while ((*p == '\r') || (*p =='\n'))
+        p++;
+
+    while (*p != '\0')
+    {
+        p = cyg_httpd_process_header(p);
+        if (p == 0)
+            return;
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_AUTH
+        // Let's check that the requested URL is not inside some directory that 
+        //  needs authentication.
+        cyg_httpd_auth_table_entry* auth = 
+                                  cyg_httpd_is_authenticated(httpstate.url);
+        if (auth != 0)
+        {
+            cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_AUTHORIZED);
+            return;
+        }
+#endif
+        switch (httpstate.method)
+        {
+            case CYG_HTTPD_METHOD_GET:
+            case CYG_HTTPD_METHOD_HEAD:
+                cyg_httpd_handle_method_GET();
+                break;
+            case CYG_HTTPD_METHOD_POST:
+                cyg_httpd_handle_method_POST();
+                return;
+                break;
+            default:
+                cyg_httpd_send_error(CYG_HTTPD_STATUS_NOT_IMPLEMENTED);
+                return;
+            break;
+        }
+    }    
+}
+
diff --git a/packages/net/athttpd/v2_0/src/jim-aio.c b/packages/net/athttpd/v2_0/src/jim-aio.c
new file mode 100644 (file)
index 0000000..cd0d04d
--- /dev/null
@@ -0,0 +1,357 @@
+/* Jim - ANSI I/O extension
+ * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
+ *
+ * $Id$
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * A copy of the license is also included in the source distribution
+ * of Jim, as a TXT file name called LICENSE.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <pkgconf/athttpd.h>
+#ifndef JIM_STATICEXT
+#define JIM_EXTENSION
+#endif
+#include <cyg/athttpd/jim.h>
+
+#define AIO_CMD_LEN 128
+#define AIO_BUF_LEN 1024
+
+typedef struct AioFile {
+    FILE *fp;
+    int keepOpen; /* If set, the file is not fclosed on cleanup (stdin, ...) */
+} AioFile;
+
+static void JimAioSetError(Jim_Interp *interp)
+{
+    Jim_SetResultString(interp, strerror(errno), -1);
+}
+
+static void JimAioDelProc(Jim_Interp *interp, void *privData)
+{
+    AioFile *af = privData;
+    JIM_NOTUSED(interp);
+
+    if (!af->keepOpen)
+        fclose(af->fp);
+    Jim_Free(af);
+}
+
+/* Calls to [aio.file] create commands that are implemented by this
+ * C command. */
+static int JimAioHandlerCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    AioFile *af = Jim_CmdPrivData(interp);
+    int option;
+    const char *options[] = {
+        "close", "seek", "tell", "gets", "read", "puts", "flush", "eof", NULL
+    };
+    enum {OPT_CLOSE, OPT_SEEK, OPT_TELL, OPT_GETS, OPT_READ, OPT_PUTS,
+          OPT_FLUSH, OPT_EOF};
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "method ?args ...?");
+        return JIM_ERR;
+    }
+    if (Jim_GetEnum(interp, argv[1], options, &option, "AIO method",
+                JIM_ERRMSG) != JIM_OK)
+        return JIM_ERR;
+    /* CLOSE */
+    if (option == OPT_CLOSE) {
+        if (argc != 2) {
+            Jim_WrongNumArgs(interp, 2, argv, "");
+            return JIM_ERR;
+        }
+        Jim_DeleteCommand(interp, Jim_GetString(argv[0], NULL));
+        return JIM_OK;
+    } else if (option == OPT_SEEK) {
+    /* SEEK */
+        int orig = SEEK_SET;
+        long offset;
+
+        if (argc != 3 && argc != 4) {
+            Jim_WrongNumArgs(interp, 2, argv, "offset ?origin?");
+            return JIM_ERR;
+        }
+        if (argc == 4) {
+            if (Jim_CompareStringImmediate(interp, argv[3], "start"))
+                orig = SEEK_SET;
+            else if (Jim_CompareStringImmediate(interp, argv[3], "current"))
+                orig = SEEK_CUR;
+            else if (Jim_CompareStringImmediate(interp, argv[3], "end"))
+                orig = SEEK_END;
+            else {
+                Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+                Jim_AppendStrings(interp, Jim_GetResult(interp),
+                        "bad origin \"", Jim_GetString(argv[3], NULL),
+                        "\" must be: start, current, or end", NULL);
+                return JIM_ERR;
+            }
+        }
+        if (Jim_GetLong(interp, argv[2], &offset) != JIM_OK)
+            return JIM_ERR;
+        if (fseek(af->fp, offset, orig) == -1) {
+            JimAioSetError(interp);
+            return JIM_ERR;
+        }
+        return JIM_OK;
+    } else if (option == OPT_TELL) {
+    /* TELL */
+        long position;
+
+        if (argc != 2) {
+            Jim_WrongNumArgs(interp, 2, argv, "");
+            return JIM_ERR;
+        }
+        position = ftell(af->fp);
+        Jim_SetResult(interp, Jim_NewIntObj(interp, position));
+        return JIM_OK;
+    } else if (option == OPT_GETS) {
+    /* GETS */
+        char buf[AIO_BUF_LEN];
+        Jim_Obj *objPtr;
+
+        if (argc != 2 && argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "?varName?");
+            return JIM_ERR;
+        }
+        objPtr = Jim_NewStringObj(interp, NULL, 0);
+        while (1) {
+            int more = 0;
+            buf[AIO_BUF_LEN-1] = '_';
+            if (fgets(buf, AIO_BUF_LEN, af->fp) == NULL)
+                break;
+            if (buf[AIO_BUF_LEN-1] == '\0' && buf[AIO_BUF_LEN-2] == '\n')
+                more = 1;
+            if (more) {
+                Jim_AppendString(interp, objPtr, buf, AIO_BUF_LEN-1);
+            } else {
+                /* strip "\n" */
+                Jim_AppendString(interp, objPtr, buf, strlen(buf)-1);
+            }
+            if (!more)
+                break;
+        }
+        if (ferror(af->fp)) {
+            /* I/O error */
+            Jim_IncrRefCount(objPtr);
+            Jim_DecrRefCount(interp, objPtr);
+            JimAioSetError(interp);
+            return JIM_ERR;
+        }
+        /* On EOF returns -1 if varName was specified, or the empty string. */
+        if (feof(af->fp) && Jim_Length(objPtr) == 0) {
+            Jim_IncrRefCount(objPtr);
+            Jim_DecrRefCount(interp, objPtr);
+            if (argc == 3)
+                Jim_SetResult(interp, Jim_NewIntObj(interp, -1));
+            return JIM_OK;
+        }
+        if (argc == 3) {
+            int totLen;
+
+            Jim_GetString(objPtr, &totLen);
+            if (Jim_SetVariable(interp, argv[2], objPtr) != JIM_OK) {
+                Jim_IncrRefCount(objPtr);
+                Jim_DecrRefCount(interp, objPtr);
+                return JIM_ERR;
+            }
+            Jim_SetResult(interp, Jim_NewIntObj(interp, totLen));
+        } else {
+            Jim_SetResult(interp, objPtr);
+        }
+        return JIM_OK;
+    } else if (option == OPT_READ) {
+    /* READ */
+        char buf[AIO_BUF_LEN];
+        Jim_Obj *objPtr;
+        int nonewline = 0;
+        int neededLen = -1; /* -1 is "read as much as possible" */
+
+        if (argc != 2 && argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "?-nonewline? ?len?");
+            return JIM_ERR;
+        }
+        if (argc == 3 &&
+            Jim_CompareStringImmediate(interp, argv[2], "-nonewline"))
+        {
+            nonewline = 1;
+            argv++;
+            argc--;
+        }
+        if (argc == 3) {
+            jim_wide wideValue;
+            if (Jim_GetWide(interp, argv[2], &wideValue) != JIM_OK)
+                return JIM_ERR;
+            if (wideValue < 0) {
+                Jim_SetResultString(interp, "invalid parameter: negative len",
+                        -1);
+                return JIM_ERR;
+            }
+            neededLen = (int) wideValue;
+        }
+        objPtr = Jim_NewStringObj(interp, NULL, 0);
+        while (neededLen != 0) {
+            int retval;
+            int readlen;
+           
+            if (neededLen == -1) {
+                readlen = AIO_BUF_LEN;
+            } else {
+                readlen = (neededLen > AIO_BUF_LEN ? AIO_BUF_LEN : neededLen);
+            }
+            retval = fread(buf, 1, readlen, af->fp);
+            if (retval > 0) {
+                Jim_AppendString(interp, objPtr, buf, retval);
+                if (neededLen != -1) {
+                    neededLen -= retval;
+                }
+            }
+            if (retval != readlen) break;
+        }
+        /* Check for error conditions */
+        if (ferror(af->fp)) {
+            /* I/O error */
+            Jim_FreeNewObj(interp, objPtr);
+            JimAioSetError(interp);
+            return JIM_ERR;
+        }
+        if (nonewline) {
+            int len;
+            const char *s = Jim_GetString(objPtr, &len);
+
+            if (len > 0 && s[len-1] == '\n') {
+                objPtr->length--;
+                objPtr->bytes[objPtr->length] = '\0';
+            }
+        }
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    } else if (option == OPT_PUTS) {
+    /* PUTS */
+        int wlen;
+        const char *wdata;
+
+        if (argc != 3 && (argc != 4 || !Jim_CompareStringImmediate(
+                        interp, argv[2], "-nonewline"))) {
+            Jim_WrongNumArgs(interp, 2, argv, "?-nonewline? string");
+            return JIM_ERR;
+        }
+        wdata = Jim_GetString(argv[2+(argc==4)], &wlen);
+        if (fwrite(wdata, 1, wlen, af->fp) != (unsigned)wlen ||
+            (argc == 3 && fwrite("\n", 1, 1, af->fp) != 1)) {
+            JimAioSetError(interp);
+            return JIM_ERR;
+        }
+        return JIM_OK;
+    } else if (option  == OPT_FLUSH) {
+    /* FLUSH */
+        if (argc != 2) {
+            Jim_WrongNumArgs(interp, 2, argv, "");
+            return JIM_ERR;
+        }
+        if (fflush(af->fp) == EOF) {
+            JimAioSetError(interp);
+            return JIM_ERR;
+        }
+        return JIM_OK;
+    } else if (option  == OPT_EOF) {
+    /* EOF */
+        if (argc != 2) {
+            Jim_WrongNumArgs(interp, 2, argv, "");
+            return JIM_ERR;
+        }
+        Jim_SetResult(interp, Jim_NewIntObj(interp, feof(af->fp)));
+        return JIM_OK;
+    }
+    return JIM_OK;
+}
+
+static int JimAioOpenCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    FILE *fp;
+    AioFile *af;
+    char buf[AIO_CMD_LEN];
+    const char *mode = "r";
+    Jim_Obj *objPtr;
+    long fileId;
+    const char *options[] = {"input", "output", "error"};
+    enum {OPT_INPUT, OPT_OUTPUT, OPT_ERROR};
+    int keepOpen = 0, modeLen;
+
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "filename ?mode?");
+        return JIM_ERR;
+    }
+    if (argc == 3)
+        mode = Jim_GetString(argv[2], &modeLen);
+    if (argc == 3 && Jim_CompareStringImmediate(interp, argv[1], "standard") &&
+            modeLen >= 3) {
+            int option;
+        if (Jim_GetEnum(interp, argv[2], options, &option, "standard channel",
+                    JIM_ERRMSG) != JIM_OK)
+            return JIM_ERR;
+        keepOpen = 1;
+        switch (option) {
+        case OPT_INPUT: fp = stdin; break;
+        case OPT_OUTPUT: fp = stdout; break;
+        case OPT_ERROR: fp = stderr; break;
+        default: fp = NULL; Jim_Panic(interp,"default reached in JimAioOpenCommand()");
+                 break;
+        }
+    } else {
+        fp = fopen(Jim_GetString(argv[1], NULL), mode);
+        if (fp == NULL) {
+            JimAioSetError(interp);
+            return JIM_ERR;
+        }
+    }
+    /* Get the next file id */
+    if (Jim_EvalGlobal(interp,
+                "if {[catch {incr aio.fileId}]} {set aio.fileId 0}") != JIM_OK)
+        return JIM_ERR;
+    objPtr = Jim_GetGlobalVariableStr(interp, "aio.fileId", JIM_ERRMSG);
+    if (objPtr == NULL) return JIM_ERR;
+    if (Jim_GetLong(interp, objPtr, &fileId) != JIM_OK) return JIM_ERR;
+
+    /* Create the file command */
+    af = Jim_Alloc(sizeof(*af));
+    af->fp = fp;
+    af->keepOpen = keepOpen;
+    sprintf(buf, "aio.handle%ld", fileId);
+    Jim_CreateCommand(interp, buf, JimAioHandlerCommand, af, JimAioDelProc);
+    Jim_SetResultString(interp, buf, -1);
+    return JIM_OK;
+}
+
+#ifndef JIM_STATICEXT
+int Jim_OnLoad(Jim_Interp *interp)
+#else
+int Jim_AioInit(Jim_Interp *interp)
+#endif
+{
+    #ifndef JIM_STATICEXT
+    Jim_InitExtension(interp);
+    #endif
+    if (Jim_PackageProvide(interp, "aio", "1.0", JIM_ERRMSG) != JIM_OK)
+        return JIM_ERR;
+    Jim_CreateCommand(interp, "aio.open", JimAioOpenCommand, NULL, NULL);
+    return JIM_OK;
+}
diff --git a/packages/net/athttpd/v2_0/src/jim.c b/packages/net/athttpd/v2_0/src/jim.c
new file mode 100644 (file)
index 0000000..989a1da
--- /dev/null
@@ -0,0 +1,11806 @@
+/* Jim - A small embeddable Tcl interpreter
+ * Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
+ * Copyright 2005 Clemens Hintze <c.hintze@gmx.net>
+ *
+ * $Id$
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * A copy of the license is also included in the source distribution
+ * of Jim, as a TXT file name called LICENSE.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define __JIM_CORE__
+#define JIM_OPTIMIZATION /* comment to avoid optimizations and reduce size */
+
+#include <pkgconf/athttpd.h>
+
+#ifndef JIM_ANSIC
+#define JIM_DYNLIB      /* Dynamic library support for UNIX and WIN32 */
+#endif /* JIM_ANSIC */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <limits.h>
+#include <assert.h>
+#include <errno.h>
+#include <time.h>
+
+/* Include the platform dependent libraries for
+ * dynamic loading of libraries. */
+#ifdef JIM_DYNLIB
+#if defined(_WIN32) || defined(WIN32)
+#ifndef WIN32
+#define WIN32 1
+#endif
+#define STRICT
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#if _MSC_VER >= 1000
+#pragma warning(disable:4146)
+#endif /* _MSC_VER */
+#else
+#include <dlfcn.h>
+#endif /* WIN32 */
+#endif /* JIM_DYNLIB */
+
+#include <cyg/athttpd/jim.h>
+
+#ifdef HAVE_BACKTRACE
+#include <execinfo.h>
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Global variables
+ * ---------------------------------------------------------------------------*/
+
+/* A shared empty string for the objects string representation.
+ * Jim_InvalidateStringRep knows about it and don't try to free. */
+static char *JimEmptyStringRep = (char*) "";
+
+/* -----------------------------------------------------------------------------
+ * Required prototypes of not exported functions
+ * ---------------------------------------------------------------------------*/
+static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf);
+static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf, int flags);
+static void JimRegisterCoreApi(Jim_Interp *interp);
+
+static Jim_HashTableType JimVariablesHashTableType;
+
+/* -----------------------------------------------------------------------------
+ * Utility functions
+ * ---------------------------------------------------------------------------*/
+
+/*
+ * Convert a string to a jim_wide INTEGER.
+ * This function originates from BSD.
+ *
+ * Ignores `locale' stuff.  Assumes that the upper and lower case
+ * alphabets and digits are each contiguous.
+ */
+#ifdef HAVE_LONG_LONG
+#define JimIsAscii(c) (((c) & ~0x7f) == 0)
+static jim_wide JimStrtoll(const char *nptr, char **endptr, register int base)
+{
+    register const char *s;
+    register unsigned jim_wide acc;
+    register unsigned char c;
+    register unsigned jim_wide qbase, cutoff;
+    register int neg, any, cutlim;
+
+    /*
+     * Skip white space and pick up leading +/- sign if any.
+     * If base is 0, allow 0x for hex and 0 for octal, else
+     * assume decimal; if base is already 16, allow 0x.
+     */
+    s = nptr;
+    do {
+        c = *s++;
+    } while (isspace(c));
+    if (c == '-') {
+        neg = 1;
+        c = *s++;
+    } else {
+        neg = 0;
+        if (c == '+')
+            c = *s++;
+    }
+    if ((base == 0 || base == 16) &&
+        c == '0' && (*s == 'x' || *s == 'X')) {
+        c = s[1];
+        s += 2;
+        base = 16;
+    }
+    if (base == 0)
+        base = c == '0' ? 8 : 10;
+
+    /*
+     * Compute the cutoff value between legal numbers and illegal
+     * numbers.  That is the largest legal value, divided by the
+     * base.  An input number that is greater than this value, if
+     * followed by a legal input character, is too big.  One that
+     * is equal to this value may be valid or not; the limit
+     * between valid and invalid numbers is then based on the last
+     * digit.  For instance, if the range for quads is
+     * [-9223372036854775808..9223372036854775807] and the input base
+     * is 10, cutoff will be set to 922337203685477580 and cutlim to
+     * either 7 (neg==0) or 8 (neg==1), meaning that if we have
+     * accumulated a value > 922337203685477580, or equal but the
+     * next digit is > 7 (or 8), the number is too big, and we will
+     * return a range error.
+     *
+     * Set any if any `digits' consumed; make it negative to indicate
+     * overflow.
+     */
+    qbase = (unsigned)base;
+    cutoff = neg ? (unsigned jim_wide)-(LLONG_MIN + LLONG_MAX) + LLONG_MAX
+        : LLONG_MAX;
+    cutlim = (int)(cutoff % qbase);
+    cutoff /= qbase;
+    for (acc = 0, any = 0;; c = *s++) {
+        if (!JimIsAscii(c))
+            break;
+        if (isdigit(c))
+            c -= '0';
+        else if (isalpha(c))
+            c -= isupper(c) ? 'A' - 10 : 'a' - 10;
+        else
+            break;
+        if (c >= base)
+            break;
+        if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
+            any = -1;
+        else {
+            any = 1;
+            acc *= qbase;
+            acc += c;
+        }
+    }
+    if (any < 0) {
+        acc = neg ? LLONG_MIN : LLONG_MAX;
+        errno = ERANGE;
+    } else if (neg)
+        acc = -acc;
+    if (endptr != 0)
+        *endptr = (char *)(any ? s - 1 : nptr);
+    return (acc);
+}
+#endif
+
+/* Glob-style pattern matching. */
+static int JimStringMatch(const char *pattern, int patternLen,
+        const char *string, int stringLen, int nocase)
+{
+    while(patternLen) {
+        switch(pattern[0]) {
+        case '*':
+            while (pattern[1] == '*') {
+                pattern++;
+                patternLen--;
+            }
+            if (patternLen == 1)
+                return 1; /* match */
+            while(stringLen) {
+                if (JimStringMatch(pattern+1, patternLen-1,
+                            string, stringLen, nocase))
+                    return 1; /* match */
+                string++;
+                stringLen--;
+            }
+            return 0; /* no match */
+            break;
+        case '?':
+            if (stringLen == 0)
+                return 0; /* no match */
+            string++;
+            stringLen--;
+            break;
+        case '[':
+        {
+            int not, match;
+
+            pattern++;
+            patternLen--;
+            not = pattern[0] == '^';
+            if (not) {
+                pattern++;
+                patternLen--;
+            }
+            match = 0;
+            while(1) {
+                if (pattern[0] == '\\') {
+                    pattern++;
+                    patternLen--;
+                    if (pattern[0] == string[0])
+                        match = 1;
+                } else if (pattern[0] == ']') {
+                    break;
+                } else if (patternLen == 0) {
+                    pattern--;
+                    patternLen++;
+                    break;
+                } else if (pattern[1] == '-' && patternLen >= 3) {
+                    int start = pattern[0];
+                    int end = pattern[2];
+                    int c = string[0];
+                    if (start > end) {
+                        int t = start;
+                        start = end;
+                        end = t;
+                    }
+                    if (nocase) {
+                        start = tolower(start);
+                        end = tolower(end);
+                        c = tolower(c);
+                    }
+                    pattern += 2;
+                    patternLen -= 2;
+                    if (c >= start && c <= end)
+                        match = 1;
+                } else {
+                    if (!nocase) {
+                        if (pattern[0] == string[0])
+                            match = 1;
+                    } else {
+                        if (tolower((int)pattern[0]) == tolower((int)string[0]))
+                            match = 1;
+                    }
+                }
+                pattern++;
+                patternLen--;
+            }
+            if (not)
+                match = !match;
+            if (!match)
+                return 0; /* no match */
+            string++;
+            stringLen--;
+            break;
+        }
+        case '\\':
+            if (patternLen >= 2) {
+                pattern++;
+                patternLen--;
+            }
+            /* fall through */
+        default:
+            if (!nocase) {
+                if (pattern[0] != string[0])
+                    return 0; /* no match */
+            } else {
+                if (tolower((int)pattern[0]) != tolower((int)string[0]))
+                    return 0; /* no match */
+            }
+            string++;
+            stringLen--;
+            break;
+        }
+        pattern++;
+        patternLen--;
+        if (stringLen == 0) {
+            while(*pattern == '*') {
+                pattern++;
+                patternLen--;
+            }
+            break;
+        }
+    }
+    if (patternLen == 0 && stringLen == 0)
+        return 1;
+    return 0;
+}
+
+int JimStringCompare(const char *s1, int l1, const char *s2, int l2,
+        int nocase)
+{
+    unsigned char *u1 = (unsigned char*) s1, *u2 = (unsigned char*) s2;
+
+    if (nocase == 0) {
+        while(l1 && l2) {
+            if (*u1 != *u2)
+                return (int)*u1-*u2;
+            u1++; u2++; l1--; l2--;
+        }
+        if (!l1 && !l2) return 0;
+        return l1-l2;
+    } else {
+        while(l1 && l2) {
+            if (tolower((int)*u1) != tolower((int)*u2))
+                return tolower((int)*u1)-tolower((int)*u2);
+            u1++; u2++; l1--; l2--;
+        }
+        if (!l1 && !l2) return 0;
+        return l1-l2;
+    }
+}
+
+/* Search 's1' inside 's2', starting to search from char 'index' of 's2'.
+ * The index of the first occurrence of s1 in s2 is returned. 
+ * If s1 is not found inside s2, -1 is returned. */
+int JimStringFirst(const char *s1, int l1, const char *s2, int l2, int index)
+{
+    int i;
+
+    if (!l1 || !l2 || l1 > l2) return -1;
+    if (index < 0) index = 0;
+    s2 += index;
+    for (i = index; i <= l2-l1; i++) {
+        if (memcmp(s2, s1, l1) == 0)
+            return i;
+        s2++;
+    }
+    return -1;
+}
+
+int Jim_WideToString(char *buf, jim_wide wideValue)
+{
+    const char *fmt = "%" JIM_WIDE_MODIFIER;
+    return sprintf(buf, fmt, wideValue);
+}
+
+int Jim_StringToWide(const char *str, jim_wide *widePtr, int base)
+{
+    char *endptr;
+
+#ifdef HAVE_LONG_LONG
+    *widePtr = JimStrtoll(str, &endptr, base);
+#else
+    *widePtr = strtol(str, &endptr, base);
+#endif
+    if (str[0] == '\0')
+        return JIM_ERR;
+    if (endptr[0] != '\0') {
+        while(*endptr) {
+            if (!isspace((int)*endptr))
+                return JIM_ERR;
+            endptr++;
+        }
+    }
+    return JIM_OK;
+}
+
+int Jim_StringToIndex(const char *str, int *intPtr)
+{
+    char *endptr;
+
+    *intPtr = strtol(str, &endptr, 10);
+    if (str[0] == '\0')
+        return JIM_ERR;
+    if (endptr[0] != '\0') {
+        while(*endptr) {
+            if (!isspace((int)*endptr))
+                return JIM_ERR;
+            endptr++;
+        }
+    }
+    return JIM_OK;
+}
+
+/* The string representation of references has two features in order
+ * to make the GC faster. The first is that every reference starts
+ * with a non common character '~', in order to make the string matching
+ * fater. The second is that the reference string rep his 32 characters
+ * in length, this allows to avoid to check every object with a string
+ * repr < 32, and usually there are many of this objects. */
+
+#define JIM_REFERENCE_SPACE (35+JIM_REFERENCE_TAGLEN)
+
+static int JimFormatReference(char *buf, Jim_Reference *refPtr, jim_wide id)
+{
+    const char *fmt = "<reference.<%s>.%020" JIM_WIDE_MODIFIER ">";
+    sprintf(buf, fmt, refPtr->tag, id);
+    return JIM_REFERENCE_SPACE;
+}
+
+int Jim_DoubleToString(char *buf, double doubleValue)
+{
+    char *s;
+    int len;
+
+    len = sprintf(buf, "%.17g", doubleValue);
+    s = buf;
+    while(*s) {
+        if (*s == '.') return len;
+        s++;
+    }
+    /* Add a final ".0" if it's a number. But not
+     * for NaN or InF */
+    if (isdigit((int)buf[0])
+        || ((buf[0] == '-' || buf[0] == '+')
+            && isdigit((int)buf[1]))) {
+        s[0] = '.';
+        s[1] = '0';
+        s[2] = '\0';
+        return len+2;
+    }
+    return len;
+}
+
+int Jim_StringToDouble(const char *str, double *doublePtr)
+{
+    char *endptr;
+
+    *doublePtr = strtod(str, &endptr);
+    if (str[0] == '\0' || endptr[0] != '\0')
+        return JIM_ERR;
+    return JIM_OK;
+}
+
+static jim_wide JimPowWide(jim_wide b, jim_wide e)
+{
+    jim_wide i, res = 1;
+    if ((b==0 && e!=0) || (e<0)) return 0;
+    for(i=0; i<e; i++) {res *= b;}
+    return res;
+}
+
+/* -----------------------------------------------------------------------------
+ * Special functions
+ * ---------------------------------------------------------------------------*/
+
+/* Note that 'interp' may be NULL if not available in the
+ * context of the panic. It's only useful to get the error
+ * file descriptor, it will default to stderr otherwise. */
+void Jim_Panic(Jim_Interp *interp, const char *fmt, ...)
+{
+    va_list ap;
+    FILE *fp = interp ? interp->stderr : stderr;
+
+    va_start(ap, fmt);
+    fprintf(fp, JIM_NL "JIM INTERPRETER PANIC: ");
+    vfprintf(fp, fmt, ap);
+    fprintf(fp, JIM_NL JIM_NL);
+    va_end(ap);
+#ifdef HAVE_BACKTRACE
+    {
+        void *array[40];
+        int size, i;
+        char **strings;
+
+        size = backtrace(array, 40);
+        strings = backtrace_symbols(array, size);
+        for (i = 0; i < size; i++)
+            fprintf(fp,"[backtrace] %s" JIM_NL, strings[i]);
+        fprintf(fp,"[backtrace] Include the above lines and the output" JIM_NL);
+        fprintf(fp,"[backtrace] of 'nm <executable>' in the bug report." JIM_NL);
+    }
+#endif
+    abort();
+}
+
+/* -----------------------------------------------------------------------------
+ * Memory allocation
+ * ---------------------------------------------------------------------------*/
+
+/* Macro used for memory debugging.
+ * In order for they to work you have to rename Jim_Alloc into _Jim_Alloc
+ * and similary for Jim_Realloc and Jim_Free */
+#if 0
+#define Jim_Alloc(s) (printf("%s %d: Jim_Alloc(%d)\n",__FILE__,__LINE__,s),_Jim_Alloc(s))
+#define Jim_Free(p) (printf("%s %d: Jim_Free(%p)\n",__FILE__,__LINE__,p),_Jim_Free(p))
+#define Jim_Realloc(p,s) (printf("%s %d: Jim_Realloc(%p,%d)\n",__FILE__,__LINE__,p,s),_Jim_Realloc(p,s))
+#endif
+
+void *Jim_Alloc(int size)
+{
+    void *p = malloc(size);
+    if (p == NULL)
+        Jim_Panic(NULL,"Out of memory");
+    return p;
+}
+
+void Jim_Free(void *ptr) {
+    free(ptr);
+}
+
+void *Jim_Realloc(void *ptr, int size)
+{
+    void *p = realloc(ptr, size);
+    if (p == NULL)
+        Jim_Panic(NULL,"Out of memory");
+    return p;
+}
+
+char *Jim_StrDup(const char *s)
+{
+    int l = strlen(s);
+    char *copy = Jim_Alloc(l+1);
+
+    memcpy(copy, s, l+1);
+    return copy;
+}
+
+char *Jim_StrDupLen(const char *s, int l)
+{
+    char *copy = Jim_Alloc(l+1);
+    
+    memcpy(copy, s, l+1);
+    copy[l] = 0;    /* Just to be sure, original could be substring */
+    return copy;
+}
+
+/* -----------------------------------------------------------------------------
+ * Time related functions
+ * ---------------------------------------------------------------------------*/
+/* Returns microseconds of CPU used since start. */
+static jim_wide JimClock(void)
+{
+#if (defined WIN32) && !(defined JIM_ANSIC)
+    LARGE_INTEGER t, f;
+    QueryPerformanceFrequency(&f);
+    QueryPerformanceCounter(&t);
+    return (long)((t.QuadPart * 1000000) / f.QuadPart);
+#else /* !WIN32 */
+    clock_t clocks = clock();
+
+    return (long)(clocks*(1000000/CLOCKS_PER_SEC));
+#endif /* WIN32 */
+}
+
+/* -----------------------------------------------------------------------------
+ * Hash Tables
+ * ---------------------------------------------------------------------------*/
+
+/* -------------------------- private prototypes ---------------------------- */
+static int JimExpandHashTableIfNeeded(Jim_HashTable *ht);
+static unsigned int JimHashTableNextPower(unsigned int size);
+static int JimInsertHashEntry(Jim_HashTable *ht, const void *key);
+
+/* -------------------------- hash functions -------------------------------- */
+
+/* Thomas Wang's 32 bit Mix Function */
+unsigned int Jim_IntHashFunction(unsigned int key)
+{
+    key += ~(key << 15);
+    key ^=  (key >> 10);
+    key +=  (key << 3);
+    key ^=  (key >> 6);
+    key += ~(key << 11);
+    key ^=  (key >> 16);
+    return key;
+}
+
+/* Identity hash function for integer keys */
+unsigned int Jim_IdentityHashFunction(unsigned int key)
+{
+    return key;
+}
+
+/* Generic hash function (we are using to multiply by 9 and add the byte
+ * as Tcl) */
+unsigned int Jim_GenHashFunction(const unsigned char *buf, int len)
+{
+    unsigned int h = 0;
+    while(len--)
+        h += (h<<3)+*buf++;
+    return h;
+}
+
+/* ----------------------------- API implementation ------------------------- */
+/* reset an hashtable already initialized with ht_init().
+ * NOTE: This function should only called by ht_destroy(). */
+static void JimResetHashTable(Jim_HashTable *ht)
+{
+    ht->table = NULL;
+    ht->size = 0;
+    ht->sizemask = 0;
+    ht->used = 0;
+    ht->collisions = 0;
+}
+
+/* Initialize the hash table */
+int Jim_InitHashTable(Jim_HashTable *ht, Jim_HashTableType *type,
+        void *privDataPtr)
+{
+    JimResetHashTable(ht);
+    ht->type = type;
+    ht->privdata = privDataPtr;
+    return JIM_OK;
+}
+
+/* Resize the table to the minimal size that contains all the elements,
+ * but with the invariant of a USER/BUCKETS ration near to <= 1 */
+int Jim_ResizeHashTable(Jim_HashTable *ht)
+{
+    int minimal = ht->used;
+
+    if (minimal < JIM_HT_INITIAL_SIZE)
+        minimal = JIM_HT_INITIAL_SIZE;
+    return Jim_ExpandHashTable(ht, minimal);
+}
+
+/* Expand or create the hashtable */
+int Jim_ExpandHashTable(Jim_HashTable *ht, unsigned int size)
+{
+    Jim_HashTable n; /* the new hashtable */
+    unsigned int realsize = JimHashTableNextPower(size), i;
+
+    /* the size is invalid if it is smaller than the number of
+     * elements already inside the hashtable */
+    if (ht->used >= size)
+        return JIM_ERR;
+
+    Jim_InitHashTable(&n, ht->type, ht->privdata);
+    n.size = realsize;
+    n.sizemask = realsize-1;
+    n.table = Jim_Alloc(realsize*sizeof(Jim_HashEntry*));
+
+    /* Initialize all the pointers to NULL */
+    memset(n.table, 0, realsize*sizeof(Jim_HashEntry*));
+
+    /* Copy all the elements from the old to the new table:
+     * note that if the old hash table is empty ht->size is zero,
+     * so Jim_ExpandHashTable just creates an hash table. */
+    n.used = ht->used;
+    for (i = 0; i < ht->size && ht->used > 0; i++) {
+        Jim_HashEntry *he, *nextHe;
+
+        if (ht->table[i] == NULL) continue;
+        
+        /* For each hash entry on this slot... */
+        he = ht->table[i];
+        while(he) {
+            unsigned int h;
+
+            nextHe = he->next;
+            /* Get the new element index */
+            h = Jim_HashKey(ht, he->key) & n.sizemask;
+            he->next = n.table[h];
+            n.table[h] = he;
+            ht->used--;
+            /* Pass to the next element */
+            he = nextHe;
+        }
+    }
+    assert(ht->used == 0);
+    Jim_Free(ht->table);
+
+    /* Remap the new hashtable in the old */
+    *ht = n;
+    return JIM_OK;
+}
+
+/* Add an element to the target hash table */
+int Jim_AddHashEntry(Jim_HashTable *ht, const void *key, void *val)
+{
+    int index;
+    Jim_HashEntry *entry;
+
+    /* Get the index of the new element, or -1 if
+     * the element already exists. */
+    if ((index = JimInsertHashEntry(ht, key)) == -1)
+        return JIM_ERR;
+
+    /* Allocates the memory and stores key */
+    entry = Jim_Alloc(sizeof(*entry));
+    entry->next = ht->table[index];
+    ht->table[index] = entry;
+
+    /* Set the hash entry fields. */
+    Jim_SetHashKey(ht, entry, key);
+    Jim_SetHashVal(ht, entry, val);
+    ht->used++;
+    return JIM_OK;
+}
+
+/* Add an element, discarding the old if the key already exists */
+int Jim_ReplaceHashEntry(Jim_HashTable *ht, const void *key, void *val)
+{
+    Jim_HashEntry *entry;
+
+    /* Try to add the element. If the key
+     * does not exists Jim_AddHashEntry will suceed. */
+    if (Jim_AddHashEntry(ht, key, val) == JIM_OK)
+        return JIM_OK;
+    /* It already exists, get the entry */
+    entry = Jim_FindHashEntry(ht, key);
+    /* Free the old value and set the new one */
+    Jim_FreeEntryVal(ht, entry);
+    Jim_SetHashVal(ht, entry, val);
+    return JIM_OK;
+}
+
+/* Search and remove an element */
+int Jim_DeleteHashEntry(Jim_HashTable *ht, const void *key)
+{
+    unsigned int h;
+    Jim_HashEntry *he, *prevHe;
+
+    if (ht->size == 0)
+        return JIM_ERR;
+    h = Jim_HashKey(ht, key) & ht->sizemask;
+    he = ht->table[h];
+
+    prevHe = NULL;
+    while(he) {
+        if (Jim_CompareHashKeys(ht, key, he->key)) {
+            /* Unlink the element from the list */
+            if (prevHe)
+                prevHe->next = he->next;
+            else
+                ht->table[h] = he->next;
+            Jim_FreeEntryKey(ht, he);
+            Jim_FreeEntryVal(ht, he);
+            Jim_Free(he);
+            ht->used--;
+            return JIM_OK;
+        }
+        prevHe = he;
+        he = he->next;
+    }
+    return JIM_ERR; /* not found */
+}
+
+/* Destroy an entire hash table */
+int Jim_FreeHashTable(Jim_HashTable *ht)
+{
+    unsigned int i;
+
+    /* Free all the elements */
+    for (i = 0; i < ht->size && ht->used > 0; i++) {
+        Jim_HashEntry *he, *nextHe;
+
+        if ((he = ht->table[i]) == NULL) continue;
+        while(he) {
+            nextHe = he->next;
+            Jim_FreeEntryKey(ht, he);
+            Jim_FreeEntryVal(ht, he);
+            Jim_Free(he);
+            ht->used--;
+            he = nextHe;
+        }
+    }
+    /* Free the table and the allocated cache structure */
+    Jim_Free(ht->table);
+    /* Re-initialize the table */
+    JimResetHashTable(ht);
+    return JIM_OK; /* never fails */
+}
+
+Jim_HashEntry *Jim_FindHashEntry(Jim_HashTable *ht, const void *key)
+{
+    Jim_HashEntry *he;
+    unsigned int h;
+
+    if (ht->size == 0) return NULL;
+    h = Jim_HashKey(ht, key) & ht->sizemask;
+    he = ht->table[h];
+    while(he) {
+        if (Jim_CompareHashKeys(ht, key, he->key))
+            return he;
+        he = he->next;
+    }
+    return NULL;
+}
+
+Jim_HashTableIterator *Jim_GetHashTableIterator(Jim_HashTable *ht)
+{
+    Jim_HashTableIterator *iter = Jim_Alloc(sizeof(*iter));
+
+    iter->ht = ht;
+    iter->index = -1;
+    iter->entry = NULL;
+    iter->nextEntry = NULL;
+    return iter;
+}
+
+Jim_HashEntry *Jim_NextHashEntry(Jim_HashTableIterator *iter)
+{
+    while (1) {
+        if (iter->entry == NULL) {
+            iter->index++;
+            if (iter->index >=
+                    (signed)iter->ht->size) break;
+            iter->entry = iter->ht->table[iter->index];
+        } else {
+            iter->entry = iter->nextEntry;
+        }
+        if (iter->entry) {
+            /* We need to save the 'next' here, the iterator user
+             * may delete the entry we are returning. */
+            iter->nextEntry = iter->entry->next;
+            return iter->entry;
+        }
+    }
+    return NULL;
+}
+
+/* ------------------------- private functions ------------------------------ */
+
+/* Expand the hash table if needed */
+static int JimExpandHashTableIfNeeded(Jim_HashTable *ht)
+{
+    /* If the hash table is empty expand it to the intial size,
+     * if the table is "full" dobule its size. */
+    if (ht->size == 0)
+        return Jim_ExpandHashTable(ht, JIM_HT_INITIAL_SIZE);
+    if (ht->size == ht->used)
+        return Jim_ExpandHashTable(ht, ht->size*2);
+    return JIM_OK;
+}
+
+/* Our hash table capability is a power of two */
+static unsigned int JimHashTableNextPower(unsigned int size)
+{
+    unsigned int i = JIM_HT_INITIAL_SIZE;
+
+    if (size >= 2147483648U)
+        return 2147483648U;
+    while(1) {
+        if (i >= size)
+            return i;
+        i *= 2;
+    }
+}
+
+/* Returns the index of a free slot that can be populated with
+ * an hash entry for the given 'key'.
+ * If the key already exists, -1 is returned. */
+static int JimInsertHashEntry(Jim_HashTable *ht, const void *key)
+{
+    unsigned int h;
+    Jim_HashEntry *he;
+
+    /* Expand the hashtable if needed */
+    if (JimExpandHashTableIfNeeded(ht) == JIM_ERR)
+        return -1;
+    /* Compute the key hash value */
+    h = Jim_HashKey(ht, key) & ht->sizemask;
+    /* Search if this slot does not already contain the given key */
+    he = ht->table[h];
+    while(he) {
+        if (Jim_CompareHashKeys(ht, key, he->key))
+            return -1;
+        he = he->next;
+    }
+    return h;
+}
+
+/* ----------------------- StringCopy Hash Table Type ------------------------*/
+
+static unsigned int JimStringCopyHTHashFunction(const void *key)
+{
+    return Jim_GenHashFunction(key, strlen(key));
+}
+
+static const void *JimStringCopyHTKeyDup(void *privdata, const void *key)
+{
+    int len = strlen(key);
+    char *copy = Jim_Alloc(len+1);
+    JIM_NOTUSED(privdata);
+
+    memcpy(copy, key, len);
+    copy[len] = '\0';
+    return copy;
+}
+
+static void *JimStringKeyValCopyHTValDup(void *privdata, const void *val)
+{
+    int len = strlen(val);
+    char *copy = Jim_Alloc(len+1);
+    JIM_NOTUSED(privdata);
+
+    memcpy(copy, val, len);
+    copy[len] = '\0';
+    return copy;
+}
+
+static int JimStringCopyHTKeyCompare(void *privdata, const void *key1,
+        const void *key2)
+{
+    JIM_NOTUSED(privdata);
+
+    return strcmp(key1, key2) == 0;
+}
+
+static void JimStringCopyHTKeyDestructor(void *privdata, const void *key)
+{
+    JIM_NOTUSED(privdata);
+
+    Jim_Free((void*)key); /* ATTENTION: const cast */
+}
+
+static void JimStringKeyValCopyHTValDestructor(void *privdata, void *val)
+{
+    JIM_NOTUSED(privdata);
+
+    Jim_Free((void*)val); /* ATTENTION: const cast */
+}
+
+static Jim_HashTableType JimStringCopyHashTableType = {
+    JimStringCopyHTHashFunction,        /* hash function */
+    JimStringCopyHTKeyDup,              /* key dup */
+    NULL,                               /* val dup */
+    JimStringCopyHTKeyCompare,          /* key compare */
+    JimStringCopyHTKeyDestructor,       /* key destructor */
+    NULL                                /* val destructor */
+};
+
+/* This is like StringCopy but does not auto-duplicate the key.
+ * It's used for intepreter's shared strings. */
+static Jim_HashTableType JimSharedStringsHashTableType = {
+    JimStringCopyHTHashFunction,        /* hash function */
+    NULL,                               /* key dup */
+    NULL,                               /* val dup */
+    JimStringCopyHTKeyCompare,          /* key compare */
+    JimStringCopyHTKeyDestructor,       /* key destructor */
+    NULL                                /* val destructor */
+};
+
+/* This is like StringCopy but also automatically handle dynamic
+ * allocated C strings as values. */
+static Jim_HashTableType JimStringKeyValCopyHashTableType = {
+    JimStringCopyHTHashFunction,        /* hash function */
+    JimStringCopyHTKeyDup,              /* key dup */
+    JimStringKeyValCopyHTValDup,        /* val dup */
+    JimStringCopyHTKeyCompare,          /* key compare */
+    JimStringCopyHTKeyDestructor,       /* key destructor */
+    JimStringKeyValCopyHTValDestructor, /* val destructor */
+};
+
+typedef struct AssocDataValue {
+    Jim_InterpDeleteProc *delProc;
+    void *data;
+} AssocDataValue;
+
+static void JimAssocDataHashTableValueDestructor(void *privdata, void *data)
+{
+    AssocDataValue *assocPtr = (AssocDataValue *)data;
+    if (assocPtr->delProc != NULL)
+        assocPtr->delProc((Jim_Interp *)privdata, assocPtr->data);
+    Jim_Free(data);
+}
+
+static Jim_HashTableType JimAssocDataHashTableType = {
+    JimStringCopyHTHashFunction,         /* hash function */
+    JimStringCopyHTKeyDup,               /* key dup */
+    NULL,                                /* val dup */
+    JimStringCopyHTKeyCompare,           /* key compare */
+    JimStringCopyHTKeyDestructor,        /* key destructor */
+    JimAssocDataHashTableValueDestructor /* val destructor */
+};
+
+/* -----------------------------------------------------------------------------
+ * Stack - This is a simple generic stack implementation. It is used for
+ * example in the 'expr' expression compiler.
+ * ---------------------------------------------------------------------------*/
+void Jim_InitStack(Jim_Stack *stack)
+{
+    stack->len = 0;
+    stack->maxlen = 0;
+    stack->vector = NULL;
+}
+
+void Jim_FreeStack(Jim_Stack *stack)
+{
+    Jim_Free(stack->vector);
+}
+
+int Jim_StackLen(Jim_Stack *stack)
+{
+    return stack->len;
+}
+
+void Jim_StackPush(Jim_Stack *stack, void *element) {
+    int neededLen = stack->len+1;
+    if (neededLen > stack->maxlen) {
+        stack->maxlen = neededLen*2;
+        stack->vector = Jim_Realloc(stack->vector, sizeof(void*)*stack->maxlen);
+    }
+    stack->vector[stack->len] = element;
+    stack->len++;
+}
+
+void *Jim_StackPop(Jim_Stack *stack)
+{
+    if (stack->len == 0) return NULL;
+    stack->len--;
+    return stack->vector[stack->len];
+}
+
+void *Jim_StackPeek(Jim_Stack *stack)
+{
+    if (stack->len == 0) return NULL;
+    return stack->vector[stack->len-1];
+}
+
+void Jim_FreeStackElements(Jim_Stack *stack, void (*freeFunc)(void *ptr))
+{
+    int i;
+
+    for (i = 0; i < stack->len; i++)
+        freeFunc(stack->vector[i]);
+}
+
+/* -----------------------------------------------------------------------------
+ * Parser
+ * ---------------------------------------------------------------------------*/
+
+/* Token types */
+#define JIM_TT_NONE -1        /* No token returned */
+#define JIM_TT_STR 0        /* simple string */
+#define JIM_TT_ESC 1        /* string that needs escape chars conversion */
+#define JIM_TT_VAR 2        /* var substitution */
+#define JIM_TT_DICTSUGAR 3    /* Syntax sugar for [dict get], $foo(bar) */
+#define JIM_TT_CMD 4        /* command substitution */
+#define JIM_TT_SEP 5        /* word separator */
+#define JIM_TT_EOL 6        /* line separator */
+
+/* Additional token types needed for expressions */
+#define JIM_TT_SUBEXPR_START 7
+#define JIM_TT_SUBEXPR_END 8
+#define JIM_TT_EXPR_NUMBER 9
+#define JIM_TT_EXPR_OPERATOR 10
+
+/* Parser states */
+#define JIM_PS_DEF 0        /* Default state */
+#define JIM_PS_QUOTE 1        /* Inside "" */
+
+/* Parser context structure. The same context is used both to parse
+ * Tcl scripts and lists. */
+struct JimParserCtx {
+    const char *prg;     /* Program text */
+    const char *p;       /* Pointer to the point of the program we are parsing */
+    int len;             /* Left length of 'prg' */
+    int linenr;          /* Current line number */
+    const char *tstart;
+    const char *tend;    /* Returned token is at tstart-tend in 'prg'. */
+    int tline;           /* Line number of the returned token */
+    int tt;              /* Token type */
+    int eof;             /* Non zero if EOF condition is true. */
+    int state;           /* Parser state */
+    int comment;         /* Non zero if the next chars may be a comment. */
+};
+
+#define JimParserEof(c) ((c)->eof)
+#define JimParserTstart(c) ((c)->tstart)
+#define JimParserTend(c) ((c)->tend)
+#define JimParserTtype(c) ((c)->tt)
+#define JimParserTline(c) ((c)->tline)
+
+static int JimParseScript(struct JimParserCtx *pc);
+static int JimParseSep(struct JimParserCtx *pc);
+static int JimParseEol(struct JimParserCtx *pc);
+static int JimParseCmd(struct JimParserCtx *pc);
+static int JimParseVar(struct JimParserCtx *pc);
+static int JimParseBrace(struct JimParserCtx *pc);
+static int JimParseStr(struct JimParserCtx *pc);
+static int JimParseComment(struct JimParserCtx *pc);
+static char *JimParserGetToken(struct JimParserCtx *pc,
+        int *lenPtr, int *typePtr, int *linePtr);
+
+/* Initialize a parser context.
+ * 'prg' is a pointer to the program text, linenr is the line
+ * number of the first line contained in the program. */
+void JimParserInit(struct JimParserCtx *pc, const char *prg, 
+        int len, int linenr)
+{
+    pc->prg = prg;
+    pc->p = prg;
+    pc->len = len;
+    pc->tstart = NULL;
+    pc->tend = NULL;
+    pc->tline = 0;
+    pc->tt = JIM_TT_NONE;
+    pc->eof = 0;
+    pc->state = JIM_PS_DEF;
+    pc->linenr = linenr;
+    pc->comment = 1;
+}
+
+int JimParseScript(struct JimParserCtx *pc)
+{
+    while(1) { /* the while is used to reiterate with continue if needed */
+        if (!pc->len) {
+            pc->tstart = pc->p;
+            pc->tend = pc->p-1;
+            pc->tline = pc->linenr;
+            pc->tt = JIM_TT_EOL;
+            pc->eof = 1;
+            return JIM_OK;
+        }
+        switch(*(pc->p)) {
+        case '\\':
+            if (*(pc->p+1) == '\n')
+                return JimParseSep(pc);
+            else {
+                pc->comment = 0;
+                return JimParseStr(pc);
+            }
+            break;
+        case ' ':
+        case '\t':
+        case '\r':
+            if (pc->state == JIM_PS_DEF)
+                return JimParseSep(pc);
+            else {
+                pc->comment = 0;
+                return JimParseStr(pc);
+            }
+            break;
+        case '\n':
+        case ';':
+            pc->comment = 1;
+            if (pc->state == JIM_PS_DEF)
+                return JimParseEol(pc);
+            else
+                return JimParseStr(pc);
+            break;
+        case '[':
+            pc->comment = 0;
+            return JimParseCmd(pc);
+            break;
+        case '$':
+            pc->comment = 0;
+            if (JimParseVar(pc) == JIM_ERR) {
+                pc->tstart = pc->tend = pc->p++; pc->len--;
+                pc->tline = pc->linenr;
+                pc->tt = JIM_TT_STR;
+                return JIM_OK;
+            } else
+                return JIM_OK;
+            break;
+        case '#':
+            if (pc->comment) {
+                JimParseComment(pc);
+                continue;
+            } else {
+                return JimParseStr(pc);
+            }
+        default:
+            pc->comment = 0;
+            return JimParseStr(pc);
+            break;
+        }
+        return JIM_OK;
+    }
+}
+
+int JimParseSep(struct JimParserCtx *pc)
+{
+    pc->tstart = pc->p;
+    pc->tline = pc->linenr;
+    while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' ||
+           (*pc->p == '\\' && *(pc->p+1) == '\n')) {
+        if (*pc->p == '\\') {
+            pc->p++; pc->len--;
+            pc->linenr++;
+        }
+        pc->p++; pc->len--;
+    }
+    pc->tend = pc->p-1;
+    pc->tt = JIM_TT_SEP;
+    return JIM_OK;
+}
+
+int JimParseEol(struct JimParserCtx *pc)
+{
+    pc->tstart = pc->p;
+    pc->tline = pc->linenr;
+    while (*pc->p == ' ' || *pc->p == '\n' ||
+           *pc->p == '\t' || *pc->p == '\r' || *pc->p == ';') {
+        if (*pc->p == '\n')
+            pc->linenr++;
+        pc->p++; pc->len--;
+    }
+    pc->tend = pc->p-1;
+    pc->tt = JIM_TT_EOL;
+    return JIM_OK;
+}
+
+/* Todo. Don't stop if ']' appears inside {} or quoted.
+ * Also should handle the case of puts [string length "]"] */
+int JimParseCmd(struct JimParserCtx *pc)
+{
+    int level = 1;
+    int blevel = 0;
+
+    pc->tstart = ++pc->p; pc->len--;
+    pc->tline = pc->linenr;
+    while (1) {
+        if (pc->len == 0) {
+            break;
+        } else if (*pc->p == '[' && blevel == 0) {
+            level++;
+        } else if (*pc->p == ']' && blevel == 0) {
+            level--;
+            if (!level) break;
+        } else if (*pc->p == '\\') {
+            pc->p++; pc->len--;
+        } else if (*pc->p == '{') {
+            blevel++;
+        } else if (*pc->p == '}') {
+            if (blevel != 0)
+                blevel--;
+        } else if (*pc->p == '\n')
+            pc->linenr++;
+        pc->p++; pc->len--;
+    }
+    pc->tend = pc->p-1;
+    pc->tt = JIM_TT_CMD;
+    if (*pc->p == ']') {
+        pc->p++; pc->len--;
+    }
+    return JIM_OK;
+}
+
+int JimParseVar(struct JimParserCtx *pc)
+{
+    int brace = 0, stop = 0, ttype = JIM_TT_VAR;
+
+    pc->tstart = ++pc->p; pc->len--; /* skip the $ */
+    pc->tline = pc->linenr;
+    if (*pc->p == '{') {
+        pc->tstart = ++pc->p; pc->len--;
+        brace = 1;
+    }
+    if (brace) {
+        while (!stop) {
+            if (*pc->p == '}' || pc->len == 0) {
+                stop = 1;
+                if (pc->len == 0)
+                    continue;
+            }
+            else if (*pc->p == '\n')
+                pc->linenr++;
+            pc->p++; pc->len--;
+        }
+        if (pc->len == 0)
+            pc->tend = pc->p-1;
+        else
+            pc->tend = pc->p-2;
+    } else {
+        while (!stop) {
+            if (!((*pc->p >= 'a' && *pc->p <= 'z') ||
+                (*pc->p >= 'A' && *pc->p <= 'Z') ||
+                (*pc->p >= '0' && *pc->p <= '9') || *pc->p == '_'))
+                stop = 1;
+            else {
+                pc->p++; pc->len--;
+            }
+        }
+        /* Parse [dict get] syntax sugar. */
+        if (*pc->p == '(') {
+            while (*pc->p != ')' && pc->len) {
+                pc->p++; pc->len--;
+                if (*pc->p == '\\' && pc->len >= 2) {
+                    pc->p += 2; pc->len -= 2;
+                }
+            }
+            if (*pc->p != '\0') {
+                pc->p++; pc->len--;
+            }
+            ttype = JIM_TT_DICTSUGAR;
+        }
+        pc->tend = pc->p-1;
+    }
+    /* Check if we parsed just the '$' character.
+     * That's not a variable so an error is returned
+     * to tell the state machine to consider this '$' just
+     * a string. */
+    if (pc->tstart == pc->p) {
+        pc->p--; pc->len++;
+        return JIM_ERR;
+    }
+    pc->tt = ttype;
+    return JIM_OK;
+}
+
+int JimParseBrace(struct JimParserCtx *pc)
+{
+    int level = 1;
+
+    pc->tstart = ++pc->p; pc->len--;
+    pc->tline = pc->linenr;
+    while (1) {
+        if (*pc->p == '\\' && pc->len >= 2) {
+            pc->p++; pc->len--;
+            if (*pc->p == '\n')
+                pc->linenr++;
+        } else if (*pc->p == '{') {
+            level++;
+        } else if (pc->len == 0 || *pc->p == '}') {
+            level--;
+            if (pc->len == 0 || level == 0) {
+                pc->tend = pc->p-1;
+                if (pc->len != 0) {
+                    pc->p++; pc->len--;
+                }
+                pc->tt = JIM_TT_STR;
+                return JIM_OK;
+            }
+        } else if (*pc->p == '\n') {
+            pc->linenr++;
+        }
+        pc->p++; pc->len--;
+    }
+    return JIM_OK; /* unreached */
+}
+
+int JimParseStr(struct JimParserCtx *pc)
+{
+    int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
+            pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_STR);
+    if (newword && *pc->p == '{') {
+        return JimParseBrace(pc);
+    } else if (newword && *pc->p == '"') {
+        pc->state = JIM_PS_QUOTE;
+        pc->p++; pc->len--;
+    }
+    pc->tstart = pc->p;
+    pc->tline = pc->linenr;
+    while (1) {
+        if (pc->len == 0) {
+            pc->tend = pc->p-1;
+            pc->tt = JIM_TT_ESC;
+            return JIM_OK;
+        }
+        switch(*pc->p) {
+        case '\\':
+            if (pc->state == JIM_PS_DEF &&
+                *(pc->p+1) == '\n') {
+                pc->tend = pc->p-1;
+                pc->tt = JIM_TT_ESC;
+                return JIM_OK;
+            }
+            if (pc->len >= 2) {
+                pc->p++; pc->len--;
+            }
+            break;
+        case '$':
+        case '[':
+            pc->tend = pc->p-1;
+            pc->tt = JIM_TT_ESC;
+            return JIM_OK;
+        case ' ':
+        case '\t':
+        case '\n':
+        case '\r':
+        case ';':
+            if (pc->state == JIM_PS_DEF) {
+                pc->tend = pc->p-1;
+                pc->tt = JIM_TT_ESC;
+                return JIM_OK;
+            } else if (*pc->p == '\n') {
+                pc->linenr++;
+            }
+            break;
+        case '"':
+            if (pc->state == JIM_PS_QUOTE) {
+                pc->tend = pc->p-1;
+                pc->tt = JIM_TT_ESC;
+                pc->p++; pc->len--;
+                pc->state = JIM_PS_DEF;
+                return JIM_OK;
+            }
+            break;
+        }
+        pc->p++; pc->len--;
+    }
+    return JIM_OK; /* unreached */
+}
+
+int JimParseComment(struct JimParserCtx *pc)
+{
+    while (*pc->p) {
+        if (*pc->p == '\n') {
+            pc->linenr++;
+            if (*(pc->p-1) != '\\') {
+                pc->p++; pc->len--;
+                return JIM_OK;
+            }
+        }
+        pc->p++; pc->len--;
+    }
+    return JIM_OK;
+}
+
+/* xdigitval and odigitval are helper functions for JimParserGetToken() */
+static int xdigitval(int c)
+{
+    if (c >= '0' && c <= '9') return c-'0';
+    if (c >= 'a' && c <= 'f') return c-'a'+10;
+    if (c >= 'A' && c <= 'F') return c-'A'+10;
+    return -1;
+}
+
+static int odigitval(int c)
+{
+    if (c >= '0' && c <= '7') return c-'0';
+    return -1;
+}
+
+/* Perform Tcl escape substitution of 's', storing the result
+ * string into 'dest'. The escaped string is guaranteed to
+ * be the same length or shorted than the source string.
+ * Slen is the length of the string at 's', if it's -1 the string
+ * length will be calculated by the function.
+ *
+ * The function returns the length of the resulting string. */
+static int JimEscape(char *dest, const char *s, int slen)
+{
+    char *p = dest;
+    int i, len;
+    
+    if (slen == -1)
+        slen = strlen(s);
+
+    for (i = 0; i < slen; i++) {
+        switch(s[i]) {
+        case '\\':
+            switch(s[i+1]) {
+            case 'a': *p++ = 0x7; i++; break;
+            case 'b': *p++ = 0x8; i++; break;
+            case 'f': *p++ = 0xc; i++; break;
+            case 'n': *p++ = 0xa; i++; break;
+            case 'r': *p++ = 0xd; i++; break;
+            case 't': *p++ = 0x9; i++; break;
+            case 'v': *p++ = 0xb; i++; break;
+            case '\0': *p++ = '\\'; i++; break;
+            case '\n': *p++ = ' '; i++; break;
+            default:
+                  if (s[i+1] == 'x') {
+                    int val = 0;
+                    int c = xdigitval(s[i+2]);
+                    if (c == -1) {
+                        *p++ = 'x';
+                        i++;
+                        break;
+                    }
+                    val = c;
+                    c = xdigitval(s[i+3]);
+                    if (c == -1) {
+                        *p++ = val;
+                        i += 2;
+                        break;
+                    }
+                    val = (val*16)+c;
+                    *p++ = val;
+                    i += 3;
+                    break;
+                  } else if (s[i+1] >= '0' && s[i+1] <= '7')
+                  {
+                    int val = 0;
+                    int c = odigitval(s[i+1]);
+                    val = c;
+                    c = odigitval(s[i+2]);
+                    if (c == -1) {
+                        *p++ = val;
+                        i ++;
+                        break;
+                    }
+                    val = (val*8)+c;
+                    c = odigitval(s[i+3]);
+                    if (c == -1) {
+                        *p++ = val;
+                        i += 2;
+                        break;
+                    }
+                    val = (val*8)+c;
+                    *p++ = val;
+                    i += 3;
+                  } else {
+                    *p++ = s[i+1];
+                    i++;
+                  }
+                  break;
+            }
+            break;
+        default:
+            *p++ = s[i];
+            break;
+        }
+    }
+    len = p-dest;
+    *p++ = '\0';
+    return len;
+}
+
+/* Returns a dynamically allocated copy of the current token in the
+ * parser context. The function perform conversion of escapes if
+ * the token is of type JIM_TT_ESC.
+ *
+ * Note that after the conversion, tokens that are grouped with
+ * braces in the source code, are always recognizable from the
+ * identical string obtained in a different way from the type.
+ *
+ * For exmple the string:
+ *
+ * {expand}$a
+ * 
+ * will return as first token "expand", of type JIM_TT_STR
+ *
+ * While the string:
+ *
+ * expand$a
+ *
+ * will return as first token "expand", of type JIM_TT_ESC
+ */
+char *JimParserGetToken(struct JimParserCtx *pc,
+        int *lenPtr, int *typePtr, int *linePtr)
+{
+    const char *start, *end;
+    char *token;
+    int len;
+
+    start = JimParserTstart(pc);
+    end = JimParserTend(pc);
+    if (start > end) {
+        if (lenPtr) *lenPtr = 0;
+        if (typePtr) *typePtr = JimParserTtype(pc);
+        if (linePtr) *linePtr = JimParserTline(pc);
+        token = Jim_Alloc(1);
+        token[0] = '\0';
+        return token;
+    }
+    len = (end-start)+1;
+    token = Jim_Alloc(len+1);
+    if (JimParserTtype(pc) != JIM_TT_ESC) {
+        /* No escape conversion needed? Just copy it. */
+        memcpy(token, start, len);
+        token[len] = '\0';
+    } else {
+        /* Else convert the escape chars. */
+        len = JimEscape(token, start, len);
+    }
+    if (lenPtr) *lenPtr = len;
+    if (typePtr) *typePtr = JimParserTtype(pc);
+    if (linePtr) *linePtr = JimParserTline(pc);
+    return token;
+}
+
+/* The following functin is not really part of the parsing engine of Jim,
+ * but it somewhat related. Given an string and its length, it tries
+ * to guess if the script is complete or there are instead " " or { }
+ * open and not completed. This is useful for interactive shells
+ * implementation and for [info complete].
+ *
+ * If 'stateCharPtr' != NULL, the function stores ' ' on complete script,
+ * '{' on scripts incomplete missing one or more '}' to be balanced.
+ * '"' on scripts incomplete missing a '"' char.
+ *
+ * If the script is complete, 1 is returned, otherwise 0. */
+int Jim_ScriptIsComplete(const char *s, int len, char *stateCharPtr)
+{
+    int level = 0;
+    int state = ' ';
+
+    while(len) {
+        switch (*s) {
+            case '\\':
+                if (len > 1)
+                    s++;
+                break;
+            case '"':
+                if (state == ' ') {
+                    state = '"';
+                } else if (state == '"') {
+                    state = ' ';
+                }
+                break;
+            case '{':
+                if (state == '{') {
+                    level++;
+                } else if (state == ' ') {
+                    state = '{';
+                    level++;
+                }
+                break;
+            case '}':
+                if (state == '{') {
+                    level--;
+                    if (level == 0)
+                        state = ' ';
+                }
+                break;
+        }
+        s++;
+        len--;
+    }
+    if (stateCharPtr)
+        *stateCharPtr = state;
+    return state == ' ';
+}
+
+/* -----------------------------------------------------------------------------
+ * Tcl Lists parsing
+ * ---------------------------------------------------------------------------*/
+static int JimParseListSep(struct JimParserCtx *pc);
+static int JimParseListStr(struct JimParserCtx *pc);
+
+int JimParseList(struct JimParserCtx *pc)
+{
+    if (pc->len == 0) {
+        pc->tstart = pc->tend = pc->p;
+        pc->tline = pc->linenr;
+        pc->tt = JIM_TT_EOL;
+        pc->eof = 1;
+        return JIM_OK;
+    }
+    switch(*pc->p) {
+    case ' ':
+    case '\n':
+    case '\t':
+    case '\r':
+        if (pc->state == JIM_PS_DEF)
+            return JimParseListSep(pc);
+        else
+            return JimParseListStr(pc);
+        break;
+    default:
+        return JimParseListStr(pc);
+        break;
+    }
+    return JIM_OK;
+}
+
+int JimParseListSep(struct JimParserCtx *pc)
+{
+    pc->tstart = pc->p;
+    pc->tline = pc->linenr;
+    while (*pc->p == ' ' || *pc->p == '\t' || *pc->p == '\r' || *pc->p == '\n')
+    {
+        pc->p++; pc->len--;
+    }
+    pc->tend = pc->p-1;
+    pc->tt = JIM_TT_SEP;
+    return JIM_OK;
+}
+
+int JimParseListStr(struct JimParserCtx *pc)
+{
+    int newword = (pc->tt == JIM_TT_SEP || pc->tt == JIM_TT_EOL ||
+            pc->tt == JIM_TT_NONE);
+    if (newword && *pc->p == '{') {
+        return JimParseBrace(pc);
+    } else if (newword && *pc->p == '"') {
+        pc->state = JIM_PS_QUOTE;
+        pc->p++; pc->len--;
+    }
+    pc->tstart = pc->p;
+    pc->tline = pc->linenr;
+    while (1) {
+        if (pc->len == 0) {
+            pc->tend = pc->p-1;
+            pc->tt = JIM_TT_ESC;
+            return JIM_OK;
+        }
+        switch(*pc->p) {
+        case '\\':
+            pc->p++; pc->len--;
+            break;
+        case ' ':
+        case '\t':
+        case '\n':
+        case '\r':
+            if (pc->state == JIM_PS_DEF) {
+                pc->tend = pc->p-1;
+                pc->tt = JIM_TT_ESC;
+                return JIM_OK;
+            } else if (*pc->p == '\n') {
+                pc->linenr++;
+            }
+            break;
+        case '"':
+            if (pc->state == JIM_PS_QUOTE) {
+                pc->tend = pc->p-1;
+                pc->tt = JIM_TT_ESC;
+                pc->p++; pc->len--;
+                pc->state = JIM_PS_DEF;
+                return JIM_OK;
+            }
+            break;
+        }
+        pc->p++; pc->len--;
+    }
+    return JIM_OK; /* unreached */
+}
+
+/* -----------------------------------------------------------------------------
+ * Jim_Obj related functions
+ * ---------------------------------------------------------------------------*/
+
+/* Return a new initialized object. */
+Jim_Obj *Jim_NewObj(Jim_Interp *interp)
+{
+    Jim_Obj *objPtr;
+
+    /* -- Check if there are objects in the free list -- */
+    if (interp->freeList != NULL) {
+        /* -- Unlink the object from the free list -- */
+        objPtr = interp->freeList;
+        interp->freeList = objPtr->nextObjPtr;
+    } else {
+        /* -- No ready to use objects: allocate a new one -- */
+        objPtr = Jim_Alloc(sizeof(*objPtr));
+    }
+
+    /* Object is returned with refCount of 0. Every
+     * kind of GC implemented should take care to don't try
+     * to scan objects with refCount == 0. */
+    objPtr->refCount = 0;
+    /* All the other fields are left not initialized to save time.
+     * The caller will probably want set they to the right
+     * value anyway. */
+
+    /* -- Put the object into the live list -- */
+    objPtr->prevObjPtr = NULL;
+    objPtr->nextObjPtr = interp->liveList;
+    if (interp->liveList)
+        interp->liveList->prevObjPtr = objPtr;
+    interp->liveList = objPtr;
+
+    return objPtr;
+}
+
+/* Free an object. Actually objects are never freed, but
+ * just moved to the free objects list, where they will be
+ * reused by Jim_NewObj(). */
+void Jim_FreeObj(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    /* Check if the object was already freed, panic. */
+    if (objPtr->refCount != 0)  {
+        Jim_Panic(interp,"!!!Object %p freed with bad refcount %d", objPtr,
+                objPtr->refCount);
+    }
+    /* Free the internal representation */
+    Jim_FreeIntRep(interp, objPtr);
+    /* Free the string representation */
+    if (objPtr->bytes != NULL) {
+        if (objPtr->bytes != JimEmptyStringRep)
+            Jim_Free(objPtr->bytes);
+    }
+    /* Unlink the object from the live objects list */
+    if (objPtr->prevObjPtr)
+        objPtr->prevObjPtr->nextObjPtr = objPtr->nextObjPtr;
+    if (objPtr->nextObjPtr)
+        objPtr->nextObjPtr->prevObjPtr = objPtr->prevObjPtr;
+    if (interp->liveList == objPtr)
+        interp->liveList = objPtr->nextObjPtr;
+    /* Link the object into the free objects list */
+    objPtr->prevObjPtr = NULL;
+    objPtr->nextObjPtr = interp->freeList;
+    if (interp->freeList)
+        interp->freeList->prevObjPtr = objPtr;
+    interp->freeList = objPtr;
+    objPtr->refCount = -1;
+}
+
+/* Invalidate the string representation of an object. */
+void Jim_InvalidateStringRep(Jim_Obj *objPtr)
+{
+    if (objPtr->bytes != NULL) {
+        if (objPtr->bytes != JimEmptyStringRep)
+            Jim_Free(objPtr->bytes);
+    }
+    objPtr->bytes = NULL;
+}
+
+#define Jim_SetStringRep(o, b, l) \
+    do { (o)->bytes = b; (o)->length = l; } while (0)
+
+/* Set the initial string representation for an object.
+ * Does not try to free an old one. */
+void Jim_InitStringRep(Jim_Obj *objPtr, const char *bytes, int length)
+{
+    if (length == 0) {
+        objPtr->bytes = JimEmptyStringRep;
+        objPtr->length = 0;
+    } else {
+        objPtr->bytes = Jim_Alloc(length+1);
+        objPtr->length = length;
+        memcpy(objPtr->bytes, bytes, length);
+        objPtr->bytes[length] = '\0';
+    }
+}
+
+/* Duplicate an object. The returned object has refcount = 0. */
+Jim_Obj *Jim_DuplicateObj(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    Jim_Obj *dupPtr;
+
+    dupPtr = Jim_NewObj(interp);
+    if (objPtr->bytes == NULL) {
+        /* Object does not have a valid string representation. */
+        dupPtr->bytes = NULL;
+    } else {
+        Jim_InitStringRep(dupPtr, objPtr->bytes, objPtr->length);
+    }
+    if (objPtr->typePtr != NULL) {
+        if (objPtr->typePtr->dupIntRepProc == NULL) {
+            dupPtr->internalRep = objPtr->internalRep;
+        } else {
+            objPtr->typePtr->dupIntRepProc(interp, objPtr, dupPtr);
+        }
+        dupPtr->typePtr = objPtr->typePtr;
+    } else {
+        dupPtr->typePtr = NULL;
+    }
+    return dupPtr;
+}
+
+/* Return the string representation for objPtr. If the object
+ * string representation is invalid, calls the method to create
+ * a new one starting from the internal representation of the object. */
+const char *Jim_GetString(Jim_Obj *objPtr, int *lenPtr)
+{
+    if (objPtr->bytes == NULL) {
+        /* Invalid string repr. Generate it. */
+        if (objPtr->typePtr->updateStringProc == NULL) {
+            Jim_Panic(NULL,"UpdataStringProc called against '%s' type.",
+                objPtr->typePtr->name);
+        }
+        objPtr->typePtr->updateStringProc(objPtr);
+    }
+    if (lenPtr)
+        *lenPtr = objPtr->length;
+    return objPtr->bytes;
+}
+
+/* Just returns the length of the object's string rep */
+int Jim_Length(Jim_Obj *objPtr)
+{
+    int len;
+
+    Jim_GetString(objPtr, &len);
+    return len;
+}
+
+/* -----------------------------------------------------------------------------
+ * String Object
+ * ---------------------------------------------------------------------------*/
+static void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static int SetStringFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static Jim_ObjType stringObjType = {
+    "string",
+    NULL,
+    DupStringInternalRep,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+void DupStringInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+    JIM_NOTUSED(interp);
+
+    /* This is a bit subtle: the only caller of this function
+     * should be Jim_DuplicateObj(), that will copy the
+     * string representaion. After the copy, the duplicated
+     * object will not have more room in teh buffer than
+     * srcPtr->length bytes. So we just set it to length. */
+    dupPtr->internalRep.strValue.maxLength = srcPtr->length;
+}
+
+int SetStringFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    /* Get a fresh string representation. */
+    (void) Jim_GetString(objPtr, NULL);
+    /* Free any other internal representation. */
+    Jim_FreeIntRep(interp, objPtr);
+    /* Set it as string, i.e. just set the maxLength field. */
+    objPtr->typePtr = &stringObjType;
+    objPtr->internalRep.strValue.maxLength = objPtr->length;
+    return JIM_OK;
+}
+
+Jim_Obj *Jim_NewStringObj(Jim_Interp *interp, const char *s, int len)
+{
+    Jim_Obj *objPtr = Jim_NewObj(interp);
+
+    if (len == -1)
+        len = strlen(s);
+    /* Alloc/Set the string rep. */
+    if (len == 0) {
+        objPtr->bytes = JimEmptyStringRep;
+        objPtr->length = 0;
+    } else {
+        objPtr->bytes = Jim_Alloc(len+1);
+        objPtr->length = len;
+        memcpy(objPtr->bytes, s, len);
+        objPtr->bytes[len] = '\0';
+    }
+
+    /* No typePtr field for the vanilla string object. */
+    objPtr->typePtr = NULL;
+    return objPtr;
+}
+
+/* This version does not try to duplicate the 's' pointer, but
+ * use it directly. */
+Jim_Obj *Jim_NewStringObjNoAlloc(Jim_Interp *interp, char *s, int len)
+{
+    Jim_Obj *objPtr = Jim_NewObj(interp);
+
+    if (len == -1)
+        len = strlen(s);
+    Jim_SetStringRep(objPtr, s, len);
+    objPtr->typePtr = NULL;
+    return objPtr;
+}
+
+/* Low-level string append. Use it only against objects
+ * of type "string". */
+void StringAppendString(Jim_Obj *objPtr, const char *str, int len)
+{
+    int needlen;
+
+    if (len == -1)
+        len = strlen(str);
+    needlen = objPtr->length + len;
+    if (objPtr->internalRep.strValue.maxLength < needlen ||
+        objPtr->internalRep.strValue.maxLength == 0) {
+        if (objPtr->bytes == JimEmptyStringRep) {
+            objPtr->bytes = Jim_Alloc((needlen*2)+1);
+        } else {
+            objPtr->bytes = Jim_Realloc(objPtr->bytes, (needlen*2)+1);
+        }
+        objPtr->internalRep.strValue.maxLength = needlen*2;
+    }
+    memcpy(objPtr->bytes + objPtr->length, str, len);
+    objPtr->bytes[objPtr->length+len] = '\0';
+    objPtr->length += len;
+}
+
+/* Low-level wrapper to append an object. */
+void StringAppendObj(Jim_Obj *objPtr, Jim_Obj *appendObjPtr)
+{
+    int len;
+    const char *str;
+
+    str = Jim_GetString(appendObjPtr, &len);
+    StringAppendString(objPtr, str, len);
+}
+
+/* Higher level API to append strings to objects. */
+void Jim_AppendString(Jim_Interp *interp, Jim_Obj *objPtr, const char *str,
+        int len)
+{
+    if (Jim_IsShared(objPtr))
+        Jim_Panic(interp,"Jim_AppendString called with shared object");
+    if (objPtr->typePtr != &stringObjType)
+        SetStringFromAny(interp, objPtr);
+    StringAppendString(objPtr, str, len);
+}
+
+void Jim_AppendObj(Jim_Interp *interp, Jim_Obj *objPtr,
+        Jim_Obj *appendObjPtr)
+{
+    int len;
+    const char *str;
+
+    str = Jim_GetString(appendObjPtr, &len);
+    Jim_AppendString(interp, objPtr, str, len);
+}
+
+void Jim_AppendStrings(Jim_Interp *interp, Jim_Obj *objPtr, ...)
+{
+    va_list ap;
+
+    if (objPtr->typePtr != &stringObjType)
+        SetStringFromAny(interp, objPtr);
+    va_start(ap, objPtr);
+    while (1) {
+        char *s = va_arg(ap, char*);
+
+        if (s == NULL) break;
+        Jim_AppendString(interp, objPtr, s, -1);
+    }
+    va_end(ap);
+}
+
+int Jim_StringEqObj(Jim_Obj *aObjPtr, Jim_Obj *bObjPtr, int nocase)
+{
+    const char *aStr, *bStr;
+    int aLen, bLen, i;
+
+    if (aObjPtr == bObjPtr) return 1;
+    aStr = Jim_GetString(aObjPtr, &aLen);
+    bStr = Jim_GetString(bObjPtr, &bLen);
+    if (aLen != bLen) return 0;
+    if (nocase == 0)
+        return memcmp(aStr, bStr, aLen) == 0;
+    for (i = 0; i < aLen; i++) {
+        if (tolower((int)aStr[i]) != tolower((int)bStr[i]))
+            return 0;
+    }
+    return 1;
+}
+
+int Jim_StringMatchObj(Jim_Obj *patternObjPtr, Jim_Obj *objPtr,
+        int nocase)
+{
+    const char *pattern, *string;
+    int patternLen, stringLen;
+
+    pattern = Jim_GetString(patternObjPtr, &patternLen);
+    string = Jim_GetString(objPtr, &stringLen);
+    return JimStringMatch(pattern, patternLen, string, stringLen, nocase);
+}
+
+int Jim_StringCompareObj(Jim_Obj *firstObjPtr,
+        Jim_Obj *secondObjPtr, int nocase)
+{
+    const char *s1, *s2;
+    int l1, l2;
+
+    s1 = Jim_GetString(firstObjPtr, &l1);
+    s2 = Jim_GetString(secondObjPtr, &l2);
+    return JimStringCompare(s1, l1, s2, l2, nocase);
+}
+
+/* Convert a range, as returned by Jim_GetRange(), into
+ * an absolute index into an object of the specified length.
+ * This function may return negative values, or values
+ * bigger or equal to the length of the list if the index
+ * is out of range. */
+static int JimRelToAbsIndex(int len, int index)
+{
+    if (index < 0)
+        return len + index;
+    return index;
+}
+
+/* Convert a pair of index as normalize by JimRelToAbsIndex(),
+ * into a range stored in *firstPtr, *lastPtr, *rangeLenPtr, suitable
+ * for implementation of commands like [string range] and [lrange].
+ *
+ * The resulting range is guaranteed to address valid elements of
+ * the structure. */
+static void JimRelToAbsRange(int len, int first, int last,
+        int *firstPtr, int *lastPtr, int *rangeLenPtr)
+{
+    int rangeLen;
+
+    if (first > last) {
+        rangeLen = 0;
+    } else {
+        rangeLen = last-first+1;
+        if (rangeLen) {
+            if (first < 0) {
+                rangeLen += first;
+                first = 0;
+            }
+            if (last >= len) {
+                rangeLen -= (last-(len-1));
+                last = len-1;
+            }
+        }
+    }
+    if (rangeLen < 0) rangeLen = 0;
+
+    *firstPtr = first;
+    *lastPtr = last;
+    *rangeLenPtr = rangeLen;
+}
+
+Jim_Obj *Jim_StringRangeObj(Jim_Interp *interp,
+        Jim_Obj *strObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
+{
+    int first, last;
+    const char *str;
+    int len, rangeLen;
+
+    if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
+        Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
+        return NULL;
+    str = Jim_GetString(strObjPtr, &len);
+    first = JimRelToAbsIndex(len, first);
+    last = JimRelToAbsIndex(len, last);
+    JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
+    return Jim_NewStringObj(interp, str+first, rangeLen);
+}
+
+static Jim_Obj *JimStringToLower(Jim_Interp *interp, Jim_Obj *strObjPtr)
+{
+    char *buf = Jim_Alloc(strObjPtr->length+1);
+    int i;
+
+    memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);
+    for (i = 0; i < strObjPtr->length; i++)
+        buf[i] = tolower(buf[i]);
+    return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);
+}
+
+static Jim_Obj *JimStringToUpper(Jim_Interp *interp, Jim_Obj *strObjPtr)
+{
+    char *buf = Jim_Alloc(strObjPtr->length+1);
+    int i;
+
+    memcpy(buf, strObjPtr->bytes, strObjPtr->length+1);
+    for (i = 0; i < strObjPtr->length; i++)
+        buf[i] = toupper(buf[i]);
+    return Jim_NewStringObjNoAlloc(interp, buf, strObjPtr->length);
+}
+
+/* This is the core of the [format] command.
+ * TODO: Export it, make it real... for now only %s and %%
+ * specifiers supported. */
+Jim_Obj *Jim_FormatString(Jim_Interp *interp, Jim_Obj *fmtObjPtr,
+        int objc, Jim_Obj *const *objv)
+{
+    const char *fmt;
+    int fmtLen;
+    Jim_Obj *resObjPtr;
+
+    fmt = Jim_GetString(fmtObjPtr, &fmtLen);
+    resObjPtr = Jim_NewStringObj(interp, "", 0);
+    while (fmtLen) {
+        const char *p = fmt;
+        char spec[2], c;
+        jim_wide wideValue;
+
+        while (*fmt != '%' && fmtLen) {
+            fmt++; fmtLen--;
+        }
+        Jim_AppendString(interp, resObjPtr, p, fmt-p);
+        if (fmtLen == 0)
+            break;
+        fmt++; fmtLen--; /* skip '%' */
+        if (*fmt != '%') {
+            if (objc == 0) {
+                Jim_FreeNewObj(interp, resObjPtr);
+                Jim_SetResultString(interp,
+                        "not enough arguments for all format specifiers", -1);
+                return NULL;
+            } else {
+                objc--;
+            }
+        }
+        switch(*fmt) {
+        case 's':
+            Jim_AppendObj(interp, resObjPtr, objv[0]);
+            objv++;
+            break;
+        case 'c':
+            if (Jim_GetWide(interp, objv[0], &wideValue) == JIM_ERR) {
+                Jim_FreeNewObj(interp, resObjPtr);
+                return NULL;
+            }
+            c = (char) wideValue;
+            Jim_AppendString(interp, resObjPtr, &c, 1);
+            break;
+        case '%':
+            Jim_AppendString(interp, resObjPtr, "%" , 1);
+            break;
+        default:
+            spec[0] = *fmt; spec[1] = '\0';
+            Jim_FreeNewObj(interp, resObjPtr);
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                    "bad field specifier \"",  spec, "\"", NULL);
+            return NULL;
+        }
+        fmt++;
+        fmtLen--;
+    }
+    return resObjPtr;
+}
+
+/* -----------------------------------------------------------------------------
+ * Compared String Object
+ * ---------------------------------------------------------------------------*/
+
+/* This is strange object that allows to compare a C literal string
+ * with a Jim object in very short time if the same comparison is done
+ * multiple times. For example every time the [if] command is executed,
+ * Jim has to check if a given argument is "else". This comparions if
+ * the code has no errors are true most of the times, so we can cache
+ * inside the object the pointer of the string of the last matching
+ * comparison. Because most C compilers perform literal sharing,
+ * so that: char *x = "foo", char *y = "foo", will lead to x == y,
+ * this works pretty well even if comparisons are at different places
+ * inside the C code. */
+
+static Jim_ObjType comparedStringObjType = {
+    "compared-string",
+    NULL,
+    NULL,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+/* The only way this object is exposed to the API is via the following
+ * function. Returns true if the string and the object string repr.
+ * are the same, otherwise zero is returned.
+ *
+ * Note: this isn't binary safe, but it hardly needs to be.*/
+int Jim_CompareStringImmediate(Jim_Interp *interp, Jim_Obj *objPtr,
+        const char *str)
+{
+    if (objPtr->typePtr == &comparedStringObjType &&
+        objPtr->internalRep.ptr == str)
+        return 1;
+    else {
+        const char *objStr = Jim_GetString(objPtr, NULL);
+        if (strcmp(str, objStr) != 0) return 0;
+        if (objPtr->typePtr != &comparedStringObjType) {
+            Jim_FreeIntRep(interp, objPtr);
+            objPtr->typePtr = &comparedStringObjType;
+        }
+        objPtr->internalRep.ptr = (char*)str; /*ATTENTION: const cast */
+        return 1;
+    }
+}
+
+int qsortCompareStringPointers(const void *a, const void *b)
+{
+    char * const *sa = (char * const *)a;
+    char * const *sb = (char * const *)b;
+    return strcmp(*sa, *sb);
+}
+
+int Jim_GetEnum(Jim_Interp *interp, Jim_Obj *objPtr,
+        const char **tablePtr, int *indexPtr, const char *name, int flags)
+{
+    const char **entryPtr = NULL;
+    char **tablePtrSorted;
+    int i, count = 0;
+
+    *indexPtr = -1;
+    for (entryPtr = tablePtr, i = 0; *entryPtr != NULL; entryPtr++, i++) {
+        if (Jim_CompareStringImmediate(interp, objPtr, *entryPtr)) {
+            *indexPtr = i;
+            return JIM_OK;
+        }
+        count++; /* If nothing matches, this will reach the len of tablePtr */
+    }
+    if (flags & JIM_ERRMSG) {
+        if (name == NULL)
+            name = "option";
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "bad ", name, " \"", Jim_GetString(objPtr, NULL), "\": must be one of ",
+            NULL);
+        tablePtrSorted = Jim_Alloc(sizeof(char*)*count);
+        memcpy(tablePtrSorted, tablePtr, sizeof(char*)*count);
+        qsort(tablePtrSorted, count, sizeof(char*), qsortCompareStringPointers);
+        for (i = 0; i < count; i++) {
+            if (i+1 == count && count > 1)
+                Jim_AppendString(interp, Jim_GetResult(interp), "or ", -1);
+            Jim_AppendString(interp, Jim_GetResult(interp),
+                    tablePtrSorted[i], -1);
+            if (i+1 != count)
+                Jim_AppendString(interp, Jim_GetResult(interp), ", ", -1);
+        }
+        Jim_Free(tablePtrSorted);
+    }
+    return JIM_ERR;
+}
+
+/* -----------------------------------------------------------------------------
+ * Source Object
+ *
+ * This object is just a string from the language point of view, but
+ * in the internal representation it contains the filename and line number
+ * where this given token was read. This information is used by
+ * Jim_EvalObj() if the object passed happens to be of type "source".
+ *
+ * This allows to propagate the information about line numbers and file
+ * names and give error messages with absolute line numbers.
+ *
+ * Note that this object uses shared strings for filenames, and the
+ * pointer to the filename together with the line number is taken into
+ * the space for the "inline" internal represenation of the Jim_Object,
+ * so there is almost memory zero-overhead.
+ *
+ * Also the object will be converted to something else if the given
+ * token it represents in the source file is not something to be
+ * evaluated (not a script), and will be specialized in some other way,
+ * so the time overhead is alzo null.
+ * ---------------------------------------------------------------------------*/
+
+static void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+
+static Jim_ObjType sourceObjType = {
+    "source",
+    FreeSourceInternalRep,
+    DupSourceInternalRep,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+void FreeSourceInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    Jim_ReleaseSharedString(interp,
+            objPtr->internalRep.sourceValue.fileName);
+}
+
+void DupSourceInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+    dupPtr->internalRep.sourceValue.fileName =
+        Jim_GetSharedString(interp,
+                srcPtr->internalRep.sourceValue.fileName);
+    dupPtr->internalRep.sourceValue.lineNumber =
+        dupPtr->internalRep.sourceValue.lineNumber;
+    dupPtr->typePtr = &sourceObjType;
+}
+
+static void JimSetSourceInfo(Jim_Interp *interp, Jim_Obj *objPtr,
+        const char *fileName, int lineNumber)
+{
+    if (Jim_IsShared(objPtr))
+        Jim_Panic(interp,"JimSetSourceInfo called with shared object");
+    if (objPtr->typePtr != NULL)
+        Jim_Panic(interp,"JimSetSourceInfo called with typePtr != NULL");
+    objPtr->internalRep.sourceValue.fileName =
+        Jim_GetSharedString(interp, fileName);
+    objPtr->internalRep.sourceValue.lineNumber = lineNumber;
+    objPtr->typePtr = &sourceObjType;
+}
+
+/* -----------------------------------------------------------------------------
+ * Script Object
+ * ---------------------------------------------------------------------------*/
+
+#define JIM_CMDSTRUCT_EXPAND -1
+
+static void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static Jim_ObjType scriptObjType = {
+    "script",
+    FreeScriptInternalRep,
+    DupScriptInternalRep,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+/* The ScriptToken structure represents every token into a scriptObj.
+ * Every token contains an associated Jim_Obj that can be specialized
+ * by commands operating on it. */
+typedef struct ScriptToken {
+    int type;
+    Jim_Obj *objPtr;
+    int linenr;
+} ScriptToken;
+
+/* This is the script object internal representation. An array of
+ * ScriptToken structures, with an associated command structure array.
+ * The command structure is a pre-computed representation of the
+ * command length and arguments structure as a simple liner array
+ * of integers.
+ * 
+ * For example the script:
+ *
+ * puts hello
+ * set $i $x$y [foo]BAR
+ *
+ * will produce a ScriptObj with the following Tokens:
+ *
+ * ESC puts
+ * SEP
+ * ESC hello
+ * EOL
+ * ESC set
+ * EOL
+ * VAR i
+ * SEP
+ * VAR x
+ * VAR y
+ * SEP
+ * CMD foo
+ * ESC BAR
+ * EOL
+ *
+ * This is a description of the tokens, separators, and of lines.
+ * The command structure instead represents the number of arguments
+ * of every command, followed by the tokens of which every argument
+ * is composed. So for the example script, the cmdstruct array will
+ * contain:
+ *
+ * 2 1 1 4 1 1 2 2
+ *
+ * Because "puts hello" has two args (2), composed of single tokens (1 1)
+ * While "set $i $x$y [foo]BAR" has four (4) args, the first two
+ * composed of single tokens (1 1) and the last two of double tokens
+ * (2 2).
+ *
+ * The precomputation of the command structure makes Jim_Eval() faster,
+ * and simpler because there aren't dynamic lengths / allocations.
+ *
+ * -- {expand} handling --
+ *
+ * Expand is handled in a special way. When a command
+ * contains at least an argument with the {expand} prefix,
+ * the command structure presents a -1 before the integer
+ * describing the number of arguments. This is used in order
+ * to send the command exection to a different path in case
+ * of {expand} and guarantee a fast path for the more common
+ * case. Also, the integers describing the number of tokens
+ * are expressed with negative sign, to allow for fast check
+ * of what's an {expand}-prefixed argument and what not.
+ *
+ * For example the command:
+ *
+ * list {expand}{1 2}
+ *
+ * Will produce the following cmdstruct array:
+ *
+ * -1 2 1 -2
+ *
+ * -- the substFlags field of the structure --
+ *
+ * The scriptObj structure is used to represent both "script" objects
+ * and "subst" objects. In the second case, the cmdStruct related
+ * fields are not used at all, but there is an additional field used
+ * that is 'substFlags': this represents the flags used to turn
+ * the string into the intenral representation used to perform the
+ * substitution. If this flags are not what the application requires
+ * the scriptObj is created again. For example the script:
+ *
+ * subst -nocommands $string
+ * subst -novariables $string
+ *
+ * Will recreate the internal representation of the $string object
+ * two times.
+ */
+typedef struct ScriptObj {
+    int len; /* Length as number of tokens. */
+    int commands; /* number of top-level commands in script. */
+    ScriptToken *token; /* Tokens array. */
+    int *cmdStruct; /* commands structure */
+    int csLen; /* length of the cmdStruct array. */
+    int substFlags; /* flags used for the compilation of "subst" objects */
+    int inUse; /* Used to share a ScriptObj. Currently
+              only used by Jim_EvalObj() as protection against
+              shimmering of the currently evaluated object. */
+    char *fileName;
+} ScriptObj;
+
+void FreeScriptInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    int i;
+    struct ScriptObj *script = (void*) objPtr->internalRep.ptr;
+
+    script->inUse--;
+    if (script->inUse != 0) return;
+    for (i = 0; i < script->len; i++) {
+        if (script->token[i].objPtr != NULL)
+            Jim_DecrRefCount(interp, script->token[i].objPtr);
+    }
+    Jim_Free(script->token);
+    Jim_Free(script->cmdStruct);
+    Jim_Free(script->fileName);
+    Jim_Free(script);
+}
+
+void DupScriptInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+    JIM_NOTUSED(interp);
+    JIM_NOTUSED(srcPtr);
+
+    /* Just returns an simple string. */
+    dupPtr->typePtr = NULL;
+}
+
+/* Add a new token to the internal repr of a script object */
+static void ScriptObjAddToken(Jim_Interp *interp, struct ScriptObj *script,
+        char *strtoken, int len, int type, char *filename, int linenr)
+{
+    int prevtype;
+    struct ScriptToken *token;
+
+    prevtype = (script->len == 0) ? JIM_TT_EOL : \
+        script->token[script->len-1].type;
+    /* Skip tokens without meaning, like words separators
+     * following a word separator or an end of command and
+     * so on. */
+    if (prevtype == JIM_TT_EOL) {
+        if (type == JIM_TT_EOL || type == JIM_TT_SEP) {
+            Jim_Free(strtoken);
+            return;
+        }
+    } else if (prevtype == JIM_TT_SEP) {
+        if (type == JIM_TT_SEP) {
+            Jim_Free(strtoken);
+            return;
+        } else if (type == JIM_TT_EOL) {
+            /* If an EOL is following by a SEP, drop the previous
+             * separator. */
+            script->len--;
+            Jim_DecrRefCount(interp, script->token[script->len].objPtr);
+        }
+    } else if (prevtype != JIM_TT_EOL && prevtype != JIM_TT_SEP &&
+            type == JIM_TT_ESC && len == 0)
+    {
+        /* Don't add empty tokens used in interpolation */
+        Jim_Free(strtoken);
+        return;
+    }
+    /* Make space for a new istruction */
+    script->len++;
+    script->token = Jim_Realloc(script->token,
+            sizeof(ScriptToken)*script->len);
+    /* Initialize the new token */
+    token = script->token+(script->len-1);
+    token->type = type;
+    /* Every object is intially as a string, but the
+     * internal type may be specialized during execution of the
+     * script. */
+    token->objPtr = Jim_NewStringObjNoAlloc(interp, strtoken, len);
+    /* To add source info to SEP and EOL tokens is useless because
+     * they will never by called as arguments of Jim_EvalObj(). */
+    if (filename && type != JIM_TT_SEP && type != JIM_TT_EOL)
+        JimSetSourceInfo(interp, token->objPtr, filename, linenr);
+    Jim_IncrRefCount(token->objPtr);
+    token->linenr = linenr;
+}
+
+/* Add an integer into the command structure field of the script object. */
+static void ScriptObjAddInt(struct ScriptObj *script, int val)
+{
+    script->csLen++;
+    script->cmdStruct = Jim_Realloc(script->cmdStruct,
+                    sizeof(int)*script->csLen);
+    script->cmdStruct[script->csLen-1] = val;
+}
+
+/* Search a Jim_Obj contained in 'script' with the same stinrg repr.
+ * of objPtr. Search nested script objects recursively. */
+static Jim_Obj *ScriptSearchLiteral(Jim_Interp *interp, ScriptObj *script,
+        ScriptObj *scriptBarrier, Jim_Obj *objPtr)
+{
+    int i;
+
+    for (i = 0; i < script->len; i++) {
+        if (script->token[i].objPtr != objPtr &&
+            Jim_StringEqObj(script->token[i].objPtr, objPtr, 0)) {
+            return script->token[i].objPtr;
+        }
+        /* Enter recursively on scripts only if the object
+         * is not the same as the one we are searching for
+         * shared occurrences. */
+        if (script->token[i].objPtr->typePtr == &scriptObjType &&
+            script->token[i].objPtr != objPtr) {
+            Jim_Obj *foundObjPtr;
+
+            ScriptObj *subScript =
+                script->token[i].objPtr->internalRep.ptr;
+            /* Don't recursively enter the script we are trying
+             * to make shared to avoid circular references. */
+            if (subScript == scriptBarrier) continue;
+            if (subScript != script) {
+                foundObjPtr =
+                    ScriptSearchLiteral(interp, subScript,
+                            scriptBarrier, objPtr);
+                if (foundObjPtr != NULL)
+                    return foundObjPtr;
+            }
+        }
+    }
+    return NULL;
+}
+
+/* Share literals of a script recursively sharing sub-scripts literals. */
+static void ScriptShareLiterals(Jim_Interp *interp, ScriptObj *script,
+        ScriptObj *topLevelScript)
+{
+    int i, j;
+
+    return;
+    /* Try to share with toplevel object. */
+    if (topLevelScript != NULL) {
+        for (i = 0; i < script->len; i++) {
+            Jim_Obj *foundObjPtr;
+            char *str = script->token[i].objPtr->bytes;
+
+            if (script->token[i].objPtr->refCount != 1) continue;
+            if (script->token[i].objPtr->typePtr == &scriptObjType) continue;
+            if (strchr(str, ' ') || strchr(str, '\n')) continue;
+            foundObjPtr = ScriptSearchLiteral(interp,
+                    topLevelScript,
+                    script, /* barrier */
+                    script->token[i].objPtr);
+            if (foundObjPtr != NULL) {
+                Jim_IncrRefCount(foundObjPtr);
+                Jim_DecrRefCount(interp,
+                        script->token[i].objPtr);
+                script->token[i].objPtr = foundObjPtr;
+            }
+        }
+    }
+    /* Try to share locally */
+    for (i = 0; i < script->len; i++) {
+        char *str = script->token[i].objPtr->bytes;
+
+        if (script->token[i].objPtr->refCount != 1) continue;
+        if (strchr(str, ' ') || strchr(str, '\n')) continue;
+        for (j = 0; j < script->len; j++) {
+            if (script->token[i].objPtr !=
+                    script->token[j].objPtr &&
+                Jim_StringEqObj(script->token[i].objPtr,
+                            script->token[j].objPtr, 0))
+            {
+                Jim_IncrRefCount(script->token[j].objPtr);
+                Jim_DecrRefCount(interp,
+                        script->token[i].objPtr);
+                script->token[i].objPtr =
+                    script->token[j].objPtr;
+            }
+        }
+    }
+}
+
+/* This method takes the string representation of an object
+ * as a Tcl script, and generates the pre-parsed internal representation
+ * of the script. */
+int SetScriptFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+    int scriptTextLen;
+    const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
+    struct JimParserCtx parser;
+    struct ScriptObj *script = Jim_Alloc(sizeof(*script));
+    ScriptToken *token;
+    int args, tokens, start, end, i;
+    int initialLineNumber;
+    int propagateSourceInfo = 0;
+
+    script->len = 0;
+    script->csLen = 0;
+    script->commands = 0;
+    script->token = NULL;
+    script->cmdStruct = NULL;
+    script->inUse = 1;
+    /* Try to get information about filename / line number */
+    if (objPtr->typePtr == &sourceObjType) {
+        script->fileName =
+            Jim_StrDup(objPtr->internalRep.sourceValue.fileName);
+        initialLineNumber = objPtr->internalRep.sourceValue.lineNumber;
+        propagateSourceInfo = 1;
+    } else {
+        script->fileName = Jim_StrDup("?");
+        initialLineNumber = 1;
+    }
+
+    JimParserInit(&parser, scriptText, scriptTextLen, initialLineNumber);
+    while(!JimParserEof(&parser)) {
+        char *token;
+        int len, type, linenr;
+
+        JimParseScript(&parser);
+        token = JimParserGetToken(&parser, &len, &type, &linenr);
+        ScriptObjAddToken(interp, script, token, len, type,
+                propagateSourceInfo ? script->fileName : NULL,
+                linenr);
+    }
+    token = script->token;
+
+    /* Compute the command structure array
+     * (see the ScriptObj struct definition for more info) */
+    start = 0; /* Current command start token index */
+    end = -1; /* Current command end token index */
+    while (1) {
+        int expand = 0; /* expand flag. set to 1 on {expand} form. */
+        int interpolation = 0; /* set to 1 if there is at least one
+                      argument of the command obtained via
+                      interpolation of more tokens. */
+        /* Search for the end of command, while
+         * count the number of args. */
+        start = ++end;
+        if (start >= script->len) break;
+        args = 1; /* Number of args in current command */
+        while (token[end].type != JIM_TT_EOL) {
+            if (end == 0 || token[end-1].type == JIM_TT_SEP ||
+                    token[end-1].type == JIM_TT_EOL)
+            {
+                if (token[end].type == JIM_TT_STR &&
+                    token[end+1].type != JIM_TT_SEP &&
+                    token[end+1].type != JIM_TT_EOL &&
+                    (!strcmp(token[end].objPtr->bytes, "expand") ||
+                     !strcmp(token[end].objPtr->bytes, "*")))
+                    expand++;
+            }
+            if (token[end].type == JIM_TT_SEP)
+                args++;
+            end++;
+        }
+        interpolation = !((end-start+1) == args*2);
+        /* Add the 'number of arguments' info into cmdstruct.
+         * Negative value if there is list expansion involved. */
+        if (expand)
+            ScriptObjAddInt(script, -1);
+        ScriptObjAddInt(script, args);
+        /* Now add info about the number of tokens. */
+        tokens = 0; /* Number of tokens in current argument. */
+        expand = 0;
+        for (i = start; i <= end; i++) {
+            if (token[i].type == JIM_TT_SEP ||
+                token[i].type == JIM_TT_EOL)
+            {
+                if (tokens == 1 && expand)
+                    expand = 0;
+                ScriptObjAddInt(script,
+                        expand ? -tokens : tokens);
+
+                expand = 0;
+                tokens = 0;
+                continue;
+            } else if (tokens == 0 && token[i].type == JIM_TT_STR &&
+                   (!strcmp(token[i].objPtr->bytes, "expand") ||
+                    !strcmp(token[i].objPtr->bytes, "*")))
+            {
+                expand++;
+            }
+            tokens++;
+        }
+    }
+    /* Perform literal sharing, but only for objects that appear
+     * to be scripts written as literals inside the source code,
+     * and not computed at runtime. Literal sharing is a costly
+     * operation that should be done only against objects that
+     * are likely to require compilation only the first time, and
+     * then are executed multiple times. */
+    if (propagateSourceInfo && interp->framePtr->procBodyObjPtr) {
+        Jim_Obj *bodyObjPtr = interp->framePtr->procBodyObjPtr;
+        if (bodyObjPtr->typePtr == &scriptObjType) {
+            ScriptObj *bodyScript =
+                bodyObjPtr->internalRep.ptr;
+            ScriptShareLiterals(interp, script, bodyScript);
+        }
+    } else if (propagateSourceInfo) {
+        ScriptShareLiterals(interp, script, NULL);
+    }
+    /* Free the old internal rep and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    Jim_SetIntRepPtr(objPtr, script);
+    objPtr->typePtr = &scriptObjType;
+    return JIM_OK;
+}
+
+ScriptObj *Jim_GetScript(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    if (objPtr->typePtr != &scriptObjType) {
+        SetScriptFromAny(interp, objPtr);
+    }
+    return (ScriptObj*) Jim_GetIntRepPtr(objPtr);
+}
+
+/* -----------------------------------------------------------------------------
+ * Commands
+ * ---------------------------------------------------------------------------*/
+
+/* Commands HashTable Type.
+ *
+ * Keys are dynamic allocated strings, Values are Jim_Cmd structures. */
+static void Jim_CommandsHT_ValDestructor(void *interp, void *val)
+{
+    Jim_Cmd *cmdPtr = (void*) val;
+
+    if (cmdPtr->cmdProc == NULL) {
+        Jim_DecrRefCount(interp, cmdPtr->argListObjPtr);
+        Jim_DecrRefCount(interp, cmdPtr->bodyObjPtr);
+        if (cmdPtr->staticVars) {
+            Jim_FreeHashTable(cmdPtr->staticVars);
+            Jim_Free(cmdPtr->staticVars);
+        }
+    } else if (cmdPtr->delProc != NULL) {
+            /* If it was a C coded command, call the delProc if any */
+            cmdPtr->delProc(interp, cmdPtr->privData);
+    }
+    Jim_Free(val);
+}
+
+static Jim_HashTableType JimCommandsHashTableType = {
+    JimStringCopyHTHashFunction,        /* hash function */
+    JimStringCopyHTKeyDup,        /* key dup */
+    NULL,                    /* val dup */
+    JimStringCopyHTKeyCompare,        /* key compare */
+    JimStringCopyHTKeyDestructor,        /* key destructor */
+    Jim_CommandsHT_ValDestructor        /* val destructor */
+};
+
+/* ------------------------- Commands related functions --------------------- */
+
+int Jim_CreateCommand(Jim_Interp *interp, const char *cmdName,
+        Jim_CmdProc cmdProc, void *privData, Jim_DelCmdProc delProc)
+{
+    Jim_HashEntry *he;
+    Jim_Cmd *cmdPtr;
+
+    he = Jim_FindHashEntry(&interp->commands, cmdName);
+    if (he == NULL) { /* New command to create */
+        cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
+        cmdPtr->cmdProc = cmdProc;
+        cmdPtr->privData = privData;
+        cmdPtr->delProc = delProc;
+        Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);
+    } else {
+        Jim_InterpIncrProcEpoch(interp);
+        /* Free the arglist/body objects if it was a Tcl procedure */
+        cmdPtr = he->val;
+        if (cmdPtr->cmdProc == NULL) {
+            Jim_DecrRefCount(interp, cmdPtr->argListObjPtr);
+            Jim_DecrRefCount(interp, cmdPtr->bodyObjPtr);
+            if (cmdPtr->staticVars) {
+                Jim_FreeHashTable(cmdPtr->staticVars);
+                Jim_Free(cmdPtr->staticVars);
+            }
+            cmdPtr->staticVars = NULL;
+        } else if (cmdPtr->delProc != NULL) {
+            /* If it was a C coded command, call the delProc if any */
+            cmdPtr->delProc(interp, cmdPtr->privData);
+        }
+        cmdPtr->cmdProc = cmdProc;
+        cmdPtr->privData = privData;
+    }
+    /* There is no need to increment the 'proc epoch' because
+     * creation of a new procedure can never affect existing
+     * cached commands. We don't do negative caching. */
+    return JIM_OK;
+}
+
+int Jim_CreateProcedure(Jim_Interp *interp, const char *cmdName,
+        Jim_Obj *argListObjPtr, Jim_Obj *staticsListObjPtr, Jim_Obj *bodyObjPtr,
+        int arityMin, int arityMax)
+{
+    Jim_Cmd *cmdPtr;
+
+    cmdPtr = Jim_Alloc(sizeof(*cmdPtr));
+    cmdPtr->cmdProc = NULL; /* Not a C coded command */
+    cmdPtr->argListObjPtr = argListObjPtr;
+    cmdPtr->bodyObjPtr = bodyObjPtr;
+    Jim_IncrRefCount(argListObjPtr);
+    Jim_IncrRefCount(bodyObjPtr);
+    cmdPtr->arityMin = arityMin;
+    cmdPtr->arityMax = arityMax;
+    cmdPtr->staticVars = NULL;
+   
+    /* Create the statics hash table. */
+    if (staticsListObjPtr) {
+        int len, i;
+
+        Jim_ListLength(interp, staticsListObjPtr, &len);
+        if (len != 0) {
+            cmdPtr->staticVars = Jim_Alloc(sizeof(Jim_HashTable));
+            Jim_InitHashTable(cmdPtr->staticVars, &JimVariablesHashTableType,
+                    interp);
+            for (i = 0; i < len; i++) {
+                Jim_Obj *objPtr, *initObjPtr, *nameObjPtr;
+                Jim_Var *varPtr;
+                int subLen;
+
+                Jim_ListIndex(interp, staticsListObjPtr, i, &objPtr, JIM_NONE);
+                /* Check if it's composed of two elements. */
+                Jim_ListLength(interp, objPtr, &subLen);
+                if (subLen == 1 || subLen == 2) {
+                    /* Try to get the variable value from the current
+                     * environment. */
+                    Jim_ListIndex(interp, objPtr, 0, &nameObjPtr, JIM_NONE);
+                    if (subLen == 1) {
+                        initObjPtr = Jim_GetVariable(interp, nameObjPtr,
+                                JIM_NONE);
+                        if (initObjPtr == NULL) {
+                            Jim_SetResult(interp,
+                                    Jim_NewEmptyStringObj(interp));
+                            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                                "variable for initialization of static \"",
+                                Jim_GetString(nameObjPtr, NULL),
+                                "\" not found in the local context",
+                                NULL);
+                            goto err;
+                        }
+                    } else {
+                        Jim_ListIndex(interp, objPtr, 1, &initObjPtr, JIM_NONE);
+                    }
+                    varPtr = Jim_Alloc(sizeof(*varPtr));
+                    varPtr->objPtr = initObjPtr;
+                    Jim_IncrRefCount(initObjPtr);
+                    varPtr->linkFramePtr = NULL;
+                    if (Jim_AddHashEntry(cmdPtr->staticVars,
+                            Jim_GetString(nameObjPtr, NULL),
+                            varPtr) != JIM_OK)
+                    {
+                        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+                        Jim_AppendStrings(interp, Jim_GetResult(interp),
+                            "static variable name \"",
+                            Jim_GetString(objPtr, NULL), "\"",
+                            " duplicated in statics list", NULL);
+                        Jim_DecrRefCount(interp, initObjPtr);
+                        Jim_Free(varPtr);
+                        goto err;
+                    }
+                } else {
+                    Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+                    Jim_AppendStrings(interp, Jim_GetResult(interp),
+                        "too many fields in static specifier \"",
+                        objPtr, "\"", NULL);
+                    goto err;
+                }
+            }
+        }
+    }
+
+    /* Add the new command */
+
+    /* it may already exist, so we try to delete the old one */
+    if (Jim_DeleteHashEntry(&interp->commands, cmdName) != JIM_ERR) {
+        /* There was an old procedure with the same name, this requires
+         * a 'proc epoch' update. */
+        Jim_InterpIncrProcEpoch(interp);
+    }
+    /* If a procedure with the same name didn't existed there is no need
+     * to increment the 'proc epoch' because creation of a new procedure
+     * can never affect existing cached commands. We don't do
+     * negative caching. */
+    Jim_AddHashEntry(&interp->commands, cmdName, cmdPtr);
+    return JIM_OK;
+
+err:
+    Jim_FreeHashTable(cmdPtr->staticVars);
+    Jim_Free(cmdPtr->staticVars);
+    Jim_DecrRefCount(interp, argListObjPtr);
+    Jim_DecrRefCount(interp, bodyObjPtr);
+    Jim_Free(cmdPtr);
+    return JIM_ERR;
+}
+
+int Jim_DeleteCommand(Jim_Interp *interp, const char *cmdName)
+{
+    if (Jim_DeleteHashEntry(&interp->commands, cmdName) == JIM_ERR)
+        return JIM_ERR;
+    Jim_InterpIncrProcEpoch(interp);
+    return JIM_OK;
+}
+
+int Jim_RenameCommand(Jim_Interp *interp, const char *oldName, 
+        const char *newName)
+{
+    Jim_Cmd *cmdPtr;
+    Jim_HashEntry *he;
+    Jim_Cmd *copyCmdPtr;
+
+    if (newName[0] == '\0') /* Delete! */
+        return Jim_DeleteCommand(interp, oldName);
+    /* Rename */
+    he = Jim_FindHashEntry(&interp->commands, oldName);
+    if (he == NULL)
+        return JIM_ERR; /* Invalid command name */
+    cmdPtr = he->val;
+    copyCmdPtr = Jim_Alloc(sizeof(Jim_Cmd));
+    *copyCmdPtr = *cmdPtr;
+    /* In order to avoid that a procedure will get arglist/body/statics
+     * freed by the hash table methods, fake a C-coded command
+     * setting cmdPtr->cmdProc as not NULL */
+    cmdPtr->cmdProc = (void*)1;
+    /* Also make sure delProc is NULL. */
+    cmdPtr->delProc = NULL;
+    /* Destroy the old command, and make sure the new is freed
+     * as well. */
+    Jim_DeleteHashEntry(&interp->commands, oldName);
+    Jim_DeleteHashEntry(&interp->commands, newName);
+    /* Now the new command. We are sure it can't fail because
+     * the target name was already freed. */
+    Jim_AddHashEntry(&interp->commands, newName, copyCmdPtr);
+    /* Increment the epoch */
+    Jim_InterpIncrProcEpoch(interp);
+    return JIM_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Command object
+ * ---------------------------------------------------------------------------*/
+
+static int SetCommandFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static Jim_ObjType commandObjType = {
+    "command",
+    NULL,
+    NULL,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+int SetCommandFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    Jim_HashEntry *he;
+    const char *cmdName;
+
+    /* Get the string representation */
+    cmdName = Jim_GetString(objPtr, NULL);
+    /* Lookup this name into the commands hash table */
+    he = Jim_FindHashEntry(&interp->commands, cmdName);
+    if (he == NULL)
+        return JIM_ERR;
+
+    /* Free the old internal repr and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &commandObjType;
+    objPtr->internalRep.cmdValue.procEpoch = interp->procEpoch;
+    objPtr->internalRep.cmdValue.cmdPtr = (void*)he->val;
+    return JIM_OK;
+}
+
+/* This function returns the command structure for the command name
+ * stored in objPtr. It tries to specialize the objPtr to contain
+ * a cached info instead to perform the lookup into the hash table
+ * every time. The information cached may not be uptodate, in such
+ * a case the lookup is performed and the cache updated. */
+Jim_Cmd *Jim_GetCommand(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+    if ((objPtr->typePtr != &commandObjType ||
+        objPtr->internalRep.cmdValue.procEpoch != interp->procEpoch) &&
+        SetCommandFromAny(interp, objPtr) == JIM_ERR) {
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "invalid command name \"", objPtr->bytes, "\"",
+                NULL);
+        }
+        return NULL;
+    }
+    return objPtr->internalRep.cmdValue.cmdPtr;
+}
+
+/* -----------------------------------------------------------------------------
+ * Variables
+ * ---------------------------------------------------------------------------*/
+
+/* Variables HashTable Type.
+ *
+ * Keys are dynamic allocated strings, Values are Jim_Var structures. */
+static void JimVariablesHTValDestructor(void *interp, void *val)
+{
+    Jim_Var *varPtr = (void*) val;
+
+    Jim_DecrRefCount(interp, varPtr->objPtr);
+    Jim_Free(val);
+}
+
+static Jim_HashTableType JimVariablesHashTableType = {
+    JimStringCopyHTHashFunction,        /* hash function */
+    JimStringCopyHTKeyDup,              /* key dup */
+    NULL,                               /* val dup */
+    JimStringCopyHTKeyCompare,        /* key compare */
+    JimStringCopyHTKeyDestructor,     /* key destructor */
+    JimVariablesHTValDestructor       /* val destructor */
+};
+
+/* -----------------------------------------------------------------------------
+ * Variable object
+ * ---------------------------------------------------------------------------*/
+
+#define JIM_DICT_SUGAR 100 /* Only returned by SetVariableFromAny() */
+
+static int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static Jim_ObjType variableObjType = {
+    "variable",
+    NULL,
+    NULL,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+/* Return true if the string "str" looks like syntax sugar for [dict]. I.e.
+ * is in the form "varname(key)". */
+static int Jim_NameIsDictSugar(const char *str, int len)
+{
+    if (len == -1)
+        len = strlen(str);
+    if (len && str[len-1] == ')' && strchr(str, '(') != NULL)
+        return 1;
+    return 0;
+}
+
+/* This method should be called only by the variable API.
+ * It returns JIM_OK on success (variable already exists),
+ * JIM_ERR if it does not exists, JIM_DICT_GLUE if it's not
+ * a variable name, but syntax glue for [dict] i.e. the last
+ * character is ')' */
+int SetVariableFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+    Jim_HashEntry *he;
+    const char *varName;
+    int len;
+
+    /* Check if the object is already an uptodate variable */
+    if (objPtr->typePtr == &variableObjType &&
+        objPtr->internalRep.varValue.callFrameId == interp->framePtr->id)
+        return JIM_OK; /* nothing to do */
+    /* Get the string representation */
+    varName = Jim_GetString(objPtr, &len);
+    /* Make sure it's not syntax glue to get/set dict. */
+    if (Jim_NameIsDictSugar(varName, len))
+            return JIM_DICT_SUGAR;
+    /* Lookup this name into the variables hash table */
+    he = Jim_FindHashEntry(&interp->framePtr->vars, varName);
+    if (he == NULL) {
+        /* Try with static vars. */
+        if (interp->framePtr->staticVars == NULL)
+            return JIM_ERR;
+        if (!(he = Jim_FindHashEntry(interp->framePtr->staticVars, varName)))
+            return JIM_ERR;
+    }
+    /* Free the old internal repr and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &variableObjType;
+    objPtr->internalRep.varValue.callFrameId = interp->framePtr->id;
+    objPtr->internalRep.varValue.varPtr = (void*)he->val;
+    return JIM_OK;
+}
+
+/* -------------------- Variables related functions ------------------------- */
+static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *ObjPtr,
+        Jim_Obj *valObjPtr);
+static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *ObjPtr);
+
+/* For now that's dummy. Variables lookup should be optimized
+ * in many ways, with caching of lookups, and possibly with
+ * a table of pre-allocated vars in every CallFrame for local vars.
+ * All the caching should also have an 'epoch' mechanism similar
+ * to the one used by Tcl for procedures lookup caching. */
+
+int Jim_SetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, Jim_Obj *valObjPtr)
+{
+    const char *name;
+    Jim_Var *var;
+    int err;
+
+    if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {
+        /* Check for [dict] syntax sugar. */
+        if (err == JIM_DICT_SUGAR)
+            return JimDictSugarSet(interp, nameObjPtr, valObjPtr);
+        /* New variable to create */
+        name = Jim_GetString(nameObjPtr, NULL);
+
+        var = Jim_Alloc(sizeof(*var));
+        var->objPtr = valObjPtr;
+        Jim_IncrRefCount(valObjPtr);
+        var->linkFramePtr = NULL;
+        /* Insert the new variable */
+        Jim_AddHashEntry(&interp->framePtr->vars, name, var);
+        /* Make the object int rep a variable */
+        Jim_FreeIntRep(interp, nameObjPtr);
+        nameObjPtr->typePtr = &variableObjType;
+        nameObjPtr->internalRep.varValue.callFrameId =
+            interp->framePtr->id;
+        nameObjPtr->internalRep.varValue.varPtr = var;
+    } else {
+        var = nameObjPtr->internalRep.varValue.varPtr;
+        if (var->linkFramePtr == NULL) {
+            Jim_IncrRefCount(valObjPtr);
+            Jim_DecrRefCount(interp, var->objPtr);
+            var->objPtr = valObjPtr;
+        } else { /* Else handle the link */
+            Jim_CallFrame *savedCallFrame;
+
+            savedCallFrame = interp->framePtr;
+            interp->framePtr = var->linkFramePtr;
+            err = Jim_SetVariable(interp, var->objPtr, valObjPtr);
+            interp->framePtr = savedCallFrame;
+            if (err != JIM_OK)
+                return err;
+        }
+    }
+    return JIM_OK;
+}
+
+int Jim_SetVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
+{
+    Jim_Obj *nameObjPtr;
+    int result;
+
+    nameObjPtr = Jim_NewStringObj(interp, name, -1);
+    Jim_IncrRefCount(nameObjPtr);
+    result = Jim_SetVariable(interp, nameObjPtr, objPtr);
+    Jim_DecrRefCount(interp, nameObjPtr);
+    return result;
+}
+
+int Jim_SetGlobalVariableStr(Jim_Interp *interp, const char *name, Jim_Obj *objPtr)
+{
+    Jim_CallFrame *savedFramePtr;
+    int result;
+
+    savedFramePtr = interp->framePtr;
+    interp->framePtr = interp->topFramePtr;
+    result = Jim_SetVariableStr(interp, name, objPtr);
+    interp->framePtr = savedFramePtr;
+    return result;
+}
+
+int Jim_SetVariableStrWithStr(Jim_Interp *interp, const char *name, const char *val)
+{
+    Jim_Obj *nameObjPtr, *valObjPtr;
+    int result;
+
+    nameObjPtr = Jim_NewStringObj(interp, name, -1);
+    valObjPtr = Jim_NewStringObj(interp, val, -1);
+    Jim_IncrRefCount(nameObjPtr);
+    Jim_IncrRefCount(valObjPtr);
+    result = Jim_SetVariable(interp, nameObjPtr, valObjPtr);
+    Jim_DecrRefCount(interp, nameObjPtr);
+    Jim_DecrRefCount(interp, valObjPtr);
+    return result;
+}
+
+int Jim_SetVariableLink(Jim_Interp *interp, Jim_Obj *nameObjPtr,
+        Jim_Obj *targetNameObjPtr, Jim_CallFrame *targetCallFrame)
+{
+    const char *varName;
+    int len;
+
+    /* Check for cycles. */
+    if (interp->framePtr == targetCallFrame) {
+        Jim_Obj *objPtr = targetNameObjPtr;
+        Jim_Var *varPtr;
+        /* Cycles are only possible with 'uplevel 0' */
+        while(1) {
+            if (Jim_StringEqObj(objPtr, nameObjPtr, 0)) {
+                Jim_SetResultString(interp,
+                    "can't upvar from variable to itself", -1);
+                return JIM_ERR;
+            }
+            if (SetVariableFromAny(interp, objPtr) != JIM_OK)
+                break;
+            varPtr = objPtr->internalRep.varValue.varPtr;
+            if (varPtr->linkFramePtr != targetCallFrame) break;
+            objPtr = varPtr->objPtr;
+        }
+    }
+    varName = Jim_GetString(nameObjPtr, &len);
+    if (Jim_NameIsDictSugar(varName, len)) {
+        Jim_SetResultString(interp,
+            "Dict key syntax invalid as link source", -1);
+        return JIM_ERR;
+    }
+    /* Perform the binding */
+    Jim_SetVariable(interp, nameObjPtr, targetNameObjPtr);
+    /* We are now sure 'nameObjPtr' type is variableObjType */
+    nameObjPtr->internalRep.varValue.varPtr->linkFramePtr = targetCallFrame;
+    return JIM_OK;
+}
+
+/* Return the Jim_Obj pointer associated with a variable name,
+ * or NULL if the variable was not found in the current context.
+ * The same optimization discussed in the comment to the
+ * 'SetVariable' function should apply here. */
+Jim_Obj *Jim_GetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+{
+    int err;
+
+    /* All the rest is handled here */
+    if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {
+        /* Check for [dict] syntax sugar. */
+        if (err == JIM_DICT_SUGAR)
+            return JimDictSugarGet(interp, nameObjPtr);
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "can't read \"", nameObjPtr->bytes,
+                "\": no such variable", NULL);
+        }
+        return NULL;
+    } else {
+        Jim_Var *varPtr;
+        Jim_Obj *objPtr;
+        Jim_CallFrame *savedCallFrame;
+
+        varPtr = nameObjPtr->internalRep.varValue.varPtr;
+        if (varPtr->linkFramePtr == NULL)
+            return varPtr->objPtr;
+        /* The variable is a link? Resolve it. */
+        savedCallFrame = interp->framePtr;
+        interp->framePtr = varPtr->linkFramePtr;
+        objPtr = Jim_GetVariable(interp, varPtr->objPtr, JIM_NONE);
+        if (objPtr == NULL && flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "can't read \"", nameObjPtr->bytes,
+                "\": no such variable", NULL);
+        }
+        interp->framePtr = savedCallFrame;
+        return objPtr;
+    }
+}
+
+Jim_Obj *Jim_GetGlobalVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr,
+        int flags)
+{
+    Jim_CallFrame *savedFramePtr;
+    Jim_Obj *objPtr;
+
+    savedFramePtr = interp->framePtr;
+    interp->framePtr = interp->topFramePtr;
+    objPtr = Jim_GetVariable(interp, nameObjPtr, flags);
+    interp->framePtr = savedFramePtr;
+
+    return objPtr;
+}
+
+Jim_Obj *Jim_GetVariableStr(Jim_Interp *interp, const char *name, int flags)
+{
+    Jim_Obj *nameObjPtr, *varObjPtr;
+
+    nameObjPtr = Jim_NewStringObj(interp, name, -1);
+    Jim_IncrRefCount(nameObjPtr);
+    varObjPtr = Jim_GetVariable(interp, nameObjPtr, flags);
+    Jim_DecrRefCount(interp, nameObjPtr);
+    return varObjPtr;
+}
+
+Jim_Obj *Jim_GetGlobalVariableStr(Jim_Interp *interp, const char *name,
+        int flags)
+{
+    Jim_CallFrame *savedFramePtr;
+    Jim_Obj *objPtr;
+
+    savedFramePtr = interp->framePtr;
+    interp->framePtr = interp->topFramePtr;
+    objPtr = Jim_GetVariableStr(interp, name, flags);
+    interp->framePtr = savedFramePtr;
+
+    return objPtr;
+}
+
+/* Unset a variable.
+ * Note: On success unset invalidates all the variable objects created
+ * in the current call frame incrementing. */
+int Jim_UnsetVariable(Jim_Interp *interp, Jim_Obj *nameObjPtr, int flags)
+{
+    const char *name;
+    Jim_Var *varPtr;
+    int err;
+    
+    if ((err = SetVariableFromAny(interp, nameObjPtr)) != JIM_OK) {
+        /* Check for [dict] syntax sugar. */
+        if (err == JIM_DICT_SUGAR)
+            return JimDictSugarSet(interp, nameObjPtr, NULL);
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "can't unset \"", nameObjPtr->bytes,
+            "\": no such variable", NULL);
+        return JIM_ERR; /* var not found */
+    }
+    varPtr = nameObjPtr->internalRep.varValue.varPtr;
+    /* If it's a link call UnsetVariable recursively */
+    if (varPtr->linkFramePtr) {
+        int retval;
+
+        Jim_CallFrame *savedCallFrame;
+
+        savedCallFrame = interp->framePtr;
+        interp->framePtr = varPtr->linkFramePtr;
+        retval = Jim_UnsetVariable(interp, varPtr->objPtr, JIM_NONE);
+        interp->framePtr = savedCallFrame;
+        if (retval != JIM_OK && flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "can't unset \"", nameObjPtr->bytes,
+                "\": no such variable", NULL);
+        }
+        return retval;
+    } else {
+        name = Jim_GetString(nameObjPtr, NULL);
+        if (Jim_DeleteHashEntry(&interp->framePtr->vars, name)
+                != JIM_OK) return JIM_ERR;
+        /* Change the callframe id, invalidating var lookup caching */
+        JimChangeCallFrameId(interp, interp->framePtr);
+        return JIM_OK;
+    }
+}
+
+/* ----------  Dict syntax sugar (similar to array Tcl syntax) -------------- */
+
+/* Given a variable name for [dict] operation syntax sugar,
+ * this function returns two objects, the first with the name
+ * of the variable to set, and the second with the rispective key.
+ * For example "foo(bar)" will return objects with string repr. of
+ * "foo" and "bar".
+ *
+ * The returned objects have refcount = 1. The function can't fail. */
+static void JimDictSugarParseVarKey(Jim_Interp *interp, Jim_Obj *objPtr,
+        Jim_Obj **varPtrPtr, Jim_Obj **keyPtrPtr)
+{
+    const char *str, *p;
+    char *t;
+    int len, keyLen, nameLen;
+    Jim_Obj *varObjPtr, *keyObjPtr;
+
+    str = Jim_GetString(objPtr, &len);
+    p = strchr(str, '(');
+    p++;
+    keyLen = len-((p-str)+1);
+    nameLen = (p-str)-1;
+    /* Create the objects with the variable name and key. */
+    t = Jim_Alloc(nameLen+1);
+    memcpy(t, str, nameLen);
+    t[nameLen] = '\0';
+    varObjPtr = Jim_NewStringObjNoAlloc(interp, t, nameLen);
+
+    t = Jim_Alloc(keyLen+1);
+    memcpy(t, p, keyLen);
+    t[keyLen] = '\0';
+    keyObjPtr = Jim_NewStringObjNoAlloc(interp, t, keyLen);
+
+    Jim_IncrRefCount(varObjPtr);
+    Jim_IncrRefCount(keyObjPtr);
+    *varPtrPtr = varObjPtr;
+    *keyPtrPtr = keyObjPtr;
+}
+
+/* Helper of Jim_SetVariable() to deal with dict-syntax variable names.
+ * Also used by Jim_UnsetVariable() with valObjPtr = NULL. */
+static int JimDictSugarSet(Jim_Interp *interp, Jim_Obj *objPtr,
+        Jim_Obj *valObjPtr)
+{
+    Jim_Obj *varObjPtr, *keyObjPtr;
+    int err = JIM_OK;
+
+    JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
+    err = Jim_SetDictKeysVector(interp, varObjPtr, &keyObjPtr, 1,
+            valObjPtr);
+    Jim_DecrRefCount(interp, varObjPtr);
+    Jim_DecrRefCount(interp, keyObjPtr);
+    return err;
+}
+
+/* Helper of Jim_GetVariable() to deal with dict-syntax variable names */
+static Jim_Obj *JimDictSugarGet(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    Jim_Obj *varObjPtr, *keyObjPtr, *dictObjPtr, *resObjPtr;
+
+    JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
+    dictObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
+    if (!dictObjPtr) {
+        resObjPtr = NULL;
+        goto err;
+    }
+    if (Jim_DictKey(interp, dictObjPtr, keyObjPtr, &resObjPtr, JIM_ERRMSG)
+            != JIM_OK) {
+        resObjPtr = NULL;
+    }
+err:
+    Jim_DecrRefCount(interp, varObjPtr);
+    Jim_DecrRefCount(interp, keyObjPtr);
+    return resObjPtr;
+}
+
+/* --------- $var(INDEX) substitution, using a specialized object ----------- */
+
+static void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr,
+        Jim_Obj *dupPtr);
+
+static Jim_ObjType dictSubstObjType = {
+    "dict-substitution",
+    FreeDictSubstInternalRep,
+    DupDictSubstInternalRep,
+    NULL,
+    JIM_TYPE_NONE,
+};
+
+void FreeDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.varNameObjPtr);
+    Jim_DecrRefCount(interp, objPtr->internalRep.dictSubstValue.indexObjPtr);
+}
+
+void DupDictSubstInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr,
+        Jim_Obj *dupPtr)
+{
+    JIM_NOTUSED(interp);
+
+    dupPtr->internalRep.dictSubstValue.varNameObjPtr =
+        srcPtr->internalRep.dictSubstValue.varNameObjPtr;
+    dupPtr->internalRep.dictSubstValue.indexObjPtr =
+        srcPtr->internalRep.dictSubstValue.indexObjPtr;
+    dupPtr->typePtr = &dictSubstObjType;
+}
+
+/* This function is used to expand [dict get] sugar in the form
+ * of $var(INDEX). The function is mainly used by Jim_EvalObj()
+ * to deal with tokens of type JIM_TT_DICTSUGAR. objPtr points to an
+ * object that is *guaranteed* to be in the form VARNAME(INDEX).
+ * The 'index' part is [subst]ituted, and is used to lookup a key inside
+ * the [dict]ionary contained in variable VARNAME. */
+Jim_Obj *Jim_ExpandDictSugar(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    Jim_Obj *varObjPtr, *keyObjPtr, *dictObjPtr, *resObjPtr;
+    Jim_Obj *substKeyObjPtr = NULL;
+
+    if (objPtr->typePtr != &dictSubstObjType) {
+        JimDictSugarParseVarKey(interp, objPtr, &varObjPtr, &keyObjPtr);
+        Jim_FreeIntRep(interp, objPtr);
+        objPtr->typePtr = &dictSubstObjType;
+        objPtr->internalRep.dictSubstValue.varNameObjPtr = varObjPtr;
+        objPtr->internalRep.dictSubstValue.indexObjPtr = keyObjPtr;
+    }
+    if (Jim_SubstObj(interp, objPtr->internalRep.dictSubstValue.indexObjPtr,
+                &substKeyObjPtr, JIM_NONE)
+            != JIM_OK) {
+        substKeyObjPtr = NULL;
+        goto err;
+    }
+    Jim_IncrRefCount(substKeyObjPtr);
+    dictObjPtr = Jim_GetVariable(interp,
+            objPtr->internalRep.dictSubstValue.varNameObjPtr, JIM_ERRMSG);
+    if (!dictObjPtr) {
+        resObjPtr = NULL;
+        goto err;
+    }
+    if (Jim_DictKey(interp, dictObjPtr, substKeyObjPtr, &resObjPtr, JIM_ERRMSG)
+            != JIM_OK) {
+        resObjPtr = NULL;
+        goto err;
+    }
+err:
+    if (substKeyObjPtr) Jim_DecrRefCount(interp, substKeyObjPtr);
+    return resObjPtr;
+}
+
+/* -----------------------------------------------------------------------------
+ * CallFrame
+ * ---------------------------------------------------------------------------*/
+
+static Jim_CallFrame *JimCreateCallFrame(Jim_Interp *interp)
+{
+    Jim_CallFrame *cf;
+    if (interp->freeFramesList) {
+        cf = interp->freeFramesList;
+        interp->freeFramesList = cf->nextFramePtr;
+    } else {
+        cf = Jim_Alloc(sizeof(*cf));
+        cf->vars.table = NULL;
+    }
+
+    cf->id = interp->callFrameEpoch++;
+    cf->parentCallFrame = NULL;
+    cf->argv = NULL;
+    cf->argc = 0;
+    cf->procArgsObjPtr = NULL;
+    cf->procBodyObjPtr = NULL;
+    cf->nextFramePtr = NULL;
+    cf->staticVars = NULL;
+    if (cf->vars.table == NULL)
+        Jim_InitHashTable(&cf->vars, &JimVariablesHashTableType, interp);
+    return cf;
+}
+
+/* Used to invalidate every caching related to callframe stability. */
+static void JimChangeCallFrameId(Jim_Interp *interp, Jim_CallFrame *cf)
+{
+    cf->id = interp->callFrameEpoch++;
+}
+
+#define JIM_FCF_NONE 0 /* no flags */
+#define JIM_FCF_NOHT 1 /* don't free the hash table */
+static void JimFreeCallFrame(Jim_Interp *interp, Jim_CallFrame *cf,
+        int flags)
+{
+    if (cf->procArgsObjPtr) Jim_DecrRefCount(interp, cf->procArgsObjPtr);
+    if (cf->procBodyObjPtr) Jim_DecrRefCount(interp, cf->procBodyObjPtr);
+    if (!(flags & JIM_FCF_NOHT))
+        Jim_FreeHashTable(&cf->vars);
+    else {
+        int i;
+        Jim_HashEntry **table = cf->vars.table, *he;
+
+        for (i = 0; i < JIM_HT_INITIAL_SIZE; i++) {
+            he = table[i];
+            while (he != NULL) {
+                Jim_HashEntry *nextEntry = he->next;
+                Jim_Var *varPtr = (void*) he->val;
+
+                Jim_DecrRefCount(interp, varPtr->objPtr);
+                Jim_Free(he->val);
+                Jim_Free((void*)he->key); /* ATTENTION: const cast */
+                Jim_Free(he);
+                table[i] = NULL;
+                he = nextEntry;
+            }
+        }
+        cf->vars.used = 0;
+    }
+    cf->nextFramePtr = interp->freeFramesList;
+    interp->freeFramesList = cf;
+}
+
+/* -----------------------------------------------------------------------------
+ * References
+ * ---------------------------------------------------------------------------*/
+
+/* References HashTable Type.
+ *
+ * Keys are jim_wide integers, dynamically allocated for now but in the
+ * future it's worth to cache this 8 bytes objects. Values are poitners
+ * to Jim_References. */
+static void JimReferencesHTValDestructor(void *interp, void *val)
+{
+    Jim_Reference *refPtr = (void*) val;
+
+    Jim_DecrRefCount(interp, refPtr->objPtr);
+    if (refPtr->finalizerCmdNamePtr != NULL) {
+        Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
+    }
+    Jim_Free(val);
+}
+
+unsigned int JimReferencesHTHashFunction(const void *key)
+{
+    /* Only the least significant bits are used. */
+    const jim_wide *widePtr = key;
+    unsigned int intValue = (unsigned int) *widePtr;
+    return Jim_IntHashFunction(intValue);
+}
+
+unsigned int JimReferencesHTDoubleHashFunction(const void *key)
+{
+    /* Only the least significant bits are used. */
+    const jim_wide *widePtr = key;
+    unsigned int intValue = (unsigned int) *widePtr;
+    return intValue; /* identity function. */
+}
+
+const void *JimReferencesHTKeyDup(void *privdata, const void *key)
+{
+    void *copy = Jim_Alloc(sizeof(jim_wide));
+    JIM_NOTUSED(privdata);
+
+    memcpy(copy, key, sizeof(jim_wide));
+    return copy;
+}
+
+int JimReferencesHTKeyCompare(void *privdata, const void *key1, 
+        const void *key2)
+{
+    JIM_NOTUSED(privdata);
+
+    return memcmp(key1, key2, sizeof(jim_wide)) == 0;
+}
+
+void JimReferencesHTKeyDestructor(void *privdata, const void *key)
+{
+    JIM_NOTUSED(privdata);
+
+    Jim_Free((void*)key);
+}
+
+static Jim_HashTableType JimReferencesHashTableType = {
+    JimReferencesHTHashFunction,    /* hash function */
+    JimReferencesHTKeyDup,          /* key dup */
+    NULL,                           /* val dup */
+    JimReferencesHTKeyCompare,      /* key compare */
+    JimReferencesHTKeyDestructor,   /* key destructor */
+    JimReferencesHTValDestructor    /* val destructor */
+};
+
+/* -----------------------------------------------------------------------------
+ * Reference object type and References API
+ * ---------------------------------------------------------------------------*/
+
+static void UpdateStringOfReference(struct Jim_Obj *objPtr);
+
+static Jim_ObjType referenceObjType = {
+    "reference",
+    NULL,
+    NULL,
+    UpdateStringOfReference,
+    JIM_TYPE_REFERENCES,
+};
+
+void UpdateStringOfReference(struct Jim_Obj *objPtr)
+{
+    int len;
+    char buf[JIM_REFERENCE_SPACE+1];
+    Jim_Reference *refPtr;
+
+    refPtr = objPtr->internalRep.refValue.refPtr;
+    len = JimFormatReference(buf, refPtr, objPtr->internalRep.refValue.id);
+    objPtr->bytes = Jim_Alloc(len+1);
+    memcpy(objPtr->bytes, buf, len+1);
+    objPtr->length = len;
+}
+
+/* returns true if 'c' is a valid reference tag character.
+ * i.e. inside the range [_a-zA-Z0-9] */
+static int isrefchar(int c)
+{
+    if (c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+        (c >= '0' && c <= '9')) return 1;
+    return 0;
+}
+
+int SetReferenceFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    jim_wide wideValue;
+    int i, len;
+    const char *str, *start, *end;
+    char refId[21];
+    Jim_Reference *refPtr;
+    Jim_HashEntry *he;
+
+    /* Get the string representation */
+    str = Jim_GetString(objPtr, &len);
+    /* Check if it looks like a reference */
+    if (len < JIM_REFERENCE_SPACE) goto badformat;
+    /* Trim spaces */
+    start = str;
+    end = str+len-1;
+    while (*start == ' ') start++;
+    while (*end == ' ' && end > start) end--;
+    if (end-start+1 != JIM_REFERENCE_SPACE) goto badformat;
+    /* <reference.<1234567>.%020> */
+    if (memcmp(start, "<reference.<", 12) != 0) goto badformat;
+    if (start[12+JIM_REFERENCE_TAGLEN] != '>' || end[0] != '>') goto badformat;
+    /* The tag can't contain chars other than a-zA-Z0-9 + '_'. */
+    for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
+        if (!isrefchar(start[12+i])) goto badformat;
+    }
+    /* Extract info from the refernece. */
+    memcpy(refId, start+14+JIM_REFERENCE_TAGLEN, 20);
+    refId[20] = '\0';
+    /* Try to convert the ID into a jim_wide */
+    if (Jim_StringToWide(refId, &wideValue, 10) != JIM_OK) goto badformat;
+    /* Check if the reference really exists! */
+    he = Jim_FindHashEntry(&interp->references, &wideValue);
+    if (he == NULL) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "Invalid reference ID \"", str, "\"", NULL);
+        return JIM_ERR;
+    }
+    refPtr = he->val;
+    /* Free the old internal repr and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &referenceObjType;
+    objPtr->internalRep.refValue.id = wideValue;
+    objPtr->internalRep.refValue.refPtr = refPtr;
+    return JIM_OK;
+
+badformat:
+    Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+    Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "expected reference but got \"", str, "\"", NULL);
+    return JIM_ERR;
+}
+
+/* Returns a new reference pointing to objPtr, having cmdNamePtr
+ * as finalizer command (or NULL if there is no finalizer).
+ * The returned reference object has refcount = 0. */
+Jim_Obj *Jim_NewReference(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *tagPtr,
+        Jim_Obj *cmdNamePtr)
+{
+    struct Jim_Reference *refPtr;
+    jim_wide wideValue = interp->referenceNextId;
+    Jim_Obj *refObjPtr;
+    const char *tag;
+    int tagLen, i;
+
+    /* Perform the Garbage Collection if needed. */
+    Jim_CollectIfNeeded(interp);
+
+    refPtr = Jim_Alloc(sizeof(*refPtr));
+    refPtr->objPtr = objPtr;
+    Jim_IncrRefCount(objPtr);
+    refPtr->finalizerCmdNamePtr = cmdNamePtr;
+    if (cmdNamePtr)
+        Jim_IncrRefCount(cmdNamePtr);
+    Jim_AddHashEntry(&interp->references, &wideValue, refPtr);
+    refObjPtr = Jim_NewObj(interp);
+    refObjPtr->typePtr = &referenceObjType;
+    refObjPtr->bytes = NULL;
+    refObjPtr->internalRep.refValue.id = interp->referenceNextId;
+    refObjPtr->internalRep.refValue.refPtr = refPtr;
+    interp->referenceNextId++;
+    /* Set the tag. Trimmered at JIM_REFERENCE_TAGLEN. Everything
+     * that does not pass the 'isrefchar' test is replaced with '_' */
+    tag = Jim_GetString(tagPtr, &tagLen);
+    if (tagLen > JIM_REFERENCE_TAGLEN)
+        tagLen = JIM_REFERENCE_TAGLEN;
+    for (i = 0; i < JIM_REFERENCE_TAGLEN; i++) {
+        if (i < tagLen)
+            refPtr->tag[i] = tag[i];
+        else
+            refPtr->tag[i] = '_';
+    }
+    refPtr->tag[JIM_REFERENCE_TAGLEN] = '\0';
+    return refObjPtr;
+}
+
+Jim_Reference *Jim_GetReference(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    if (objPtr->typePtr != &referenceObjType &&
+        SetReferenceFromAny(interp, objPtr) == JIM_ERR)
+        return NULL;
+    return objPtr->internalRep.refValue.refPtr;
+}
+
+int Jim_SetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj *cmdNamePtr)
+{
+    Jim_Reference *refPtr;
+
+    if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
+        return JIM_ERR;
+    Jim_IncrRefCount(cmdNamePtr);
+    if (refPtr->finalizerCmdNamePtr)
+        Jim_DecrRefCount(interp, refPtr->finalizerCmdNamePtr);
+    refPtr->finalizerCmdNamePtr = cmdNamePtr;
+    return JIM_OK;
+}
+
+int Jim_GetFinalizer(Jim_Interp *interp, Jim_Obj *objPtr, Jim_Obj **cmdNamePtrPtr)
+{
+    Jim_Reference *refPtr;
+
+    if ((refPtr = Jim_GetReference(interp, objPtr)) == NULL)
+        return JIM_ERR;
+    *cmdNamePtrPtr = refPtr->finalizerCmdNamePtr;
+    return JIM_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * References Garbage Collection
+ * ---------------------------------------------------------------------------*/
+
+/* This the hash table type for the "MARK" phase of the GC */
+static Jim_HashTableType JimRefMarkHashTableType = {
+    JimReferencesHTHashFunction,    /* hash function */
+    JimReferencesHTKeyDup,          /* key dup */
+    NULL,                           /* val dup */
+    JimReferencesHTKeyCompare,      /* key compare */
+    JimReferencesHTKeyDestructor,   /* key destructor */
+    NULL                            /* val destructor */
+};
+
+/* #define JIM_DEBUG_GC 1 */
+
+/* Performs the garbage collection. */
+int Jim_Collect(Jim_Interp *interp)
+{
+    Jim_HashTable marks;
+    Jim_HashTableIterator *htiter;
+    Jim_HashEntry *he;
+    Jim_Obj *objPtr;
+    int collected = 0;
+
+    /* Avoid recursive calls */
+    if (interp->lastCollectId == -1) {
+        /* Jim_Collect() already running. Return just now. */
+        return 0;
+    }
+    interp->lastCollectId = -1;
+
+    /* Mark all the references found into the 'mark' hash table.
+     * The references are searched in every live object that
+     * is of a type that can contain references. */
+    Jim_InitHashTable(&marks, &JimRefMarkHashTableType, NULL);
+    objPtr = interp->liveList;
+    while(objPtr) {
+        if (objPtr->typePtr == NULL ||
+            objPtr->typePtr->flags & JIM_TYPE_REFERENCES) {
+            const char *str, *p;
+            int len;
+
+            /* If the object is of type reference, to get the
+             * Id is simple... */
+            if (objPtr->typePtr == &referenceObjType) {
+                Jim_AddHashEntry(&marks,
+                    &objPtr->internalRep.refValue.id, NULL);
+#ifdef JIM_DEBUG_GC
+                fprintf(interp->stdout,
+                    "MARK (reference): %d refcount: %d" JIM_NL, 
+                    (int) objPtr->internalRep.refValue.id,
+                    objPtr->refCount);
+#endif
+                objPtr = objPtr->nextObjPtr;
+                continue;
+            }
+            /* Get the string repr of the object we want
+             * to scan for references. */
+            p = str = Jim_GetString(objPtr, &len);
+            /* Skip objects too little to contain references. */
+            if (len < JIM_REFERENCE_SPACE) {
+                objPtr = objPtr->nextObjPtr;
+                continue;
+            }
+            /* Extract references from the object string repr. */
+            while(1) {
+                int i;
+                jim_wide id;
+                char buf[21];
+
+                if ((p = strstr(p, "<reference.<")) == NULL)
+                    break;
+                /* Check if it's a valid reference. */
+                if (len-(p-str) < JIM_REFERENCE_SPACE) break;
+                if (p[41] != '>' || p[19] != '>' || p[20] != '.') break;
+                for (i = 21; i <= 40; i++)
+                    if (!isdigit((int)p[i]))
+                        break;
+                /* Get the ID */
+                memcpy(buf, p+21, 20);
+                buf[20] = '\0';
+                Jim_StringToWide(buf, &id, 10);
+
+                /* Ok, a reference for the given ID
+                 * was found. Mark it. */
+                Jim_AddHashEntry(&marks, &id, NULL);
+#ifdef JIM_DEBUG_GC
+                fprintf(interp->stdout,"MARK: %d" JIM_NL, (int)id);
+#endif
+                p += JIM_REFERENCE_SPACE;
+            }
+        }
+        objPtr = objPtr->nextObjPtr;
+    }
+
+    /* Run the references hash table to destroy every reference that
+     * is not referenced outside (not present in the mark HT). */
+    htiter = Jim_GetHashTableIterator(&interp->references);
+    while ((he = Jim_NextHashEntry(htiter)) != NULL) {
+        const jim_wide *refId;
+        Jim_Reference *refPtr;
+
+        refId = he->key;
+        /* Check if in the mark phase we encountered
+         * this reference. */
+        if (Jim_FindHashEntry(&marks, refId) == NULL) {
+#ifdef JIM_DEBUG_GC
+            fprintf(interp->stdout,"COLLECTING %d" JIM_NL, (int)*refId);
+#endif
+            collected++;
+            /* Drop the reference, but call the
+             * finalizer first if registered. */
+            refPtr = he->val;
+            if (refPtr->finalizerCmdNamePtr) {
+                char *refstr = Jim_Alloc(JIM_REFERENCE_SPACE+1);
+                Jim_Obj *objv[3], *oldResult;
+
+                JimFormatReference(refstr, refPtr, *refId);
+
+                objv[0] = refPtr->finalizerCmdNamePtr;
+                objv[1] = Jim_NewStringObjNoAlloc(interp,
+                        refstr, 32);
+                objv[2] = refPtr->objPtr;
+                Jim_IncrRefCount(objv[0]);
+                Jim_IncrRefCount(objv[1]);
+                Jim_IncrRefCount(objv[2]);
+
+                /* Drop the reference itself */
+                Jim_DeleteHashEntry(&interp->references, refId);
+
+                /* Call the finalizer. Errors ignored. */
+                oldResult = interp->result;
+                Jim_IncrRefCount(oldResult);
+                Jim_EvalObjVector(interp, 3, objv);
+                Jim_SetResult(interp, oldResult);
+                Jim_DecrRefCount(interp, oldResult);
+
+                Jim_DecrRefCount(interp, objv[0]);
+                Jim_DecrRefCount(interp, objv[1]);
+                Jim_DecrRefCount(interp, objv[2]);
+            } else {
+                Jim_DeleteHashEntry(&interp->references, refId);
+            }
+        }
+    }
+    Jim_FreeHashTableIterator(htiter);
+    Jim_FreeHashTable(&marks);
+    interp->lastCollectId = interp->referenceNextId;
+    interp->lastCollectTime = time(NULL);
+    return collected;
+}
+
+#define JIM_COLLECT_ID_PERIOD 5000
+#define JIM_COLLECT_TIME_PERIOD 300
+
+void Jim_CollectIfNeeded(Jim_Interp *interp)
+{
+    jim_wide elapsedId;
+    int elapsedTime;
+    
+    elapsedId = interp->referenceNextId - interp->lastCollectId;
+    elapsedTime = time(NULL) - interp->lastCollectTime;
+
+
+    if (elapsedId > JIM_COLLECT_ID_PERIOD ||
+        elapsedTime > JIM_COLLECT_TIME_PERIOD) {
+        Jim_Collect(interp);
+    }
+}
+
+/* -----------------------------------------------------------------------------
+ * Interpreter related functions
+ * ---------------------------------------------------------------------------*/
+
+Jim_Interp *Jim_CreateInterp(void)
+{
+    Jim_Interp *i = Jim_Alloc(sizeof(*i));
+    Jim_Obj *pathPtr;
+
+    i->errorLine = 0;
+    i->errorFileName = Jim_StrDup("");
+    i->numLevels = 0;
+    i->maxNestingDepth = JIM_MAX_NESTING_DEPTH;
+    i->returnCode = JIM_OK;
+    i->exitCode = 0;
+    i->procEpoch = 0;
+    i->callFrameEpoch = 0;
+    i->liveList = i->freeList = NULL;
+    i->scriptFileName = Jim_StrDup("");
+    i->referenceNextId = 0;
+    i->lastCollectId = 0;
+    i->lastCollectTime = time(NULL);
+    i->freeFramesList = NULL;
+    i->prngState = NULL;
+    i->evalRetcodeLevel = -1;
+    i->stdin = stdin;
+    i->stdout = stdout;
+    i->stderr = stderr;
+
+    /* Note that we can create objects only after the
+     * interpreter liveList and freeList pointers are
+     * initialized to NULL. */
+    Jim_InitHashTable(&i->commands, &JimCommandsHashTableType, i);
+    Jim_InitHashTable(&i->references, &JimReferencesHashTableType, i);
+    Jim_InitHashTable(&i->sharedStrings, &JimSharedStringsHashTableType,
+            NULL);
+    Jim_InitHashTable(&i->stub, &JimStringCopyHashTableType, NULL);
+    Jim_InitHashTable(&i->assocData, &JimAssocDataHashTableType, i);
+    Jim_InitHashTable(&i->packages, &JimStringKeyValCopyHashTableType, NULL);
+    i->framePtr = i->topFramePtr = JimCreateCallFrame(i);
+    i->emptyObj = Jim_NewEmptyStringObj(i);
+    i->result = i->emptyObj;
+    i->stackTrace = Jim_NewListObj(i, NULL, 0);
+    i->unknown = Jim_NewStringObj(i, "unknown", -1);
+    Jim_IncrRefCount(i->emptyObj);
+    Jim_IncrRefCount(i->result);
+    Jim_IncrRefCount(i->stackTrace);
+    Jim_IncrRefCount(i->unknown);
+
+    /* Initialize key variables every interpreter should contain */
+    pathPtr = Jim_NewStringObj(i, "./", -1);
+    Jim_SetVariableStr(i, "jim_libpath", pathPtr);
+    Jim_SetVariableStrWithStr(i, "jim_interactive", "0");
+
+    /* Export the core API to extensions */
+    JimRegisterCoreApi(i);
+    return i;
+}
+
+/* This is the only function Jim exports directly without
+ * to use the STUB system. It is only used by embedders
+ * in order to get an interpreter with the Jim API pointers
+ * registered. */
+Jim_Interp *ExportedJimCreateInterp(void)
+{
+    return Jim_CreateInterp();
+}
+
+void Jim_FreeInterp(Jim_Interp *i)
+{
+    Jim_CallFrame *cf = i->framePtr, *prevcf, *nextcf;
+    Jim_Obj *objPtr, *nextObjPtr;
+
+    Jim_DecrRefCount(i, i->emptyObj);
+    Jim_DecrRefCount(i, i->result);
+    Jim_DecrRefCount(i, i->stackTrace);
+    Jim_DecrRefCount(i, i->unknown);
+    Jim_Free((void*)i->errorFileName);
+    Jim_Free((void*)i->scriptFileName);
+    Jim_FreeHashTable(&i->commands);
+    Jim_FreeHashTable(&i->references);
+    Jim_FreeHashTable(&i->stub);
+    Jim_FreeHashTable(&i->assocData);
+    Jim_FreeHashTable(&i->packages);
+    Jim_Free(i->prngState);
+    /* Free the call frames list */
+    while(cf) {
+        prevcf = cf->parentCallFrame;
+        JimFreeCallFrame(i, cf, JIM_FCF_NONE);
+        cf = prevcf;
+    }
+    /* Check that the live object list is empty, otherwise
+     * there is a memory leak. */
+    if (i->liveList != NULL) {
+        Jim_Obj *objPtr = i->liveList;
+    
+        fprintf(i->stdout,JIM_NL "-------------------------------------" JIM_NL);
+        fprintf(i->stdout,"Objects still in the free list:" JIM_NL);
+        while(objPtr) {
+            const char *type = objPtr->typePtr ?
+                objPtr->typePtr->name : "";
+            fprintf(i->stdout,"%p \"%-10s\": '%.20s' (refCount: %d)" JIM_NL,
+                    objPtr, type,
+                    objPtr->bytes ? objPtr->bytes
+                    : "(null)", objPtr->refCount);
+            if (objPtr->typePtr == &sourceObjType) {
+                fprintf(i->stdout, "FILE %s LINE %d" JIM_NL,
+                objPtr->internalRep.sourceValue.fileName,
+                objPtr->internalRep.sourceValue.lineNumber);
+            }
+            objPtr = objPtr->nextObjPtr;
+        }
+        fprintf(stdout, "-------------------------------------" JIM_NL JIM_NL);
+        Jim_Panic(i,"Live list non empty freeing the interpreter! Leak?");
+    }
+    /* Free all the freed objects. */
+    objPtr = i->freeList;
+    while (objPtr) {
+        nextObjPtr = objPtr->nextObjPtr;
+        Jim_Free(objPtr);
+        objPtr = nextObjPtr;
+    }
+    /* Free cached CallFrame structures */
+    cf = i->freeFramesList;
+    while(cf) {
+        nextcf = cf->nextFramePtr;
+        if (cf->vars.table != NULL)
+            Jim_Free(cf->vars.table);
+        Jim_Free(cf);
+        cf = nextcf;
+    }
+    /* Free the sharedString hash table. Make sure to free it
+     * after every other Jim_Object was freed. */
+    Jim_FreeHashTable(&i->sharedStrings);
+    /* Free the interpreter structure. */
+    Jim_Free(i);
+}
+
+/* Store the call frame relative to the level represented by
+ * levelObjPtr into *framePtrPtr. If levelObjPtr == NULL, the
+ * level is assumed to be '1'.
+ *
+ * If a newLevelptr int pointer is specified, the function stores
+ * the absolute level integer value of the new target callframe into
+ * *newLevelPtr. (this is used to adjust interp->numLevels
+ * in the implementation of [uplevel], so that [info level] will
+ * return a correct information).
+ *
+ * This function accepts the 'level' argument in the form
+ * of the commands [uplevel] and [upvar].
+ *
+ * For a function accepting a relative integer as level suitable
+ * for implementation of [info level ?level?] check the
+ * GetCallFrameByInteger() function. */
+int Jim_GetCallFrameByLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
+        Jim_CallFrame **framePtrPtr, int *newLevelPtr)
+{
+    long level;
+    const char *str;
+    Jim_CallFrame *framePtr;
+
+    if (newLevelPtr) *newLevelPtr = interp->numLevels;
+    if (levelObjPtr) {
+        str = Jim_GetString(levelObjPtr, NULL);
+        if (str[0] == '#') {
+            char *endptr;
+            /* speedup for the toplevel (level #0) */
+            if (str[1] == '0' && str[2] == '\0') {
+                if (newLevelPtr) *newLevelPtr = 0;
+                *framePtrPtr = interp->topFramePtr;
+                return JIM_OK;
+            }
+
+            level = strtol(str+1, &endptr, 0);
+            if (str[1] == '\0' || endptr[0] != '\0' || level < 0)
+                goto badlevel;
+            /* An 'absolute' level is converted into the
+             * 'number of levels to go back' format. */
+            level = interp->numLevels - level;
+            if (level < 0) goto badlevel;
+        } else {
+            if (Jim_GetLong(interp, levelObjPtr, &level) != JIM_OK || level < 0)
+                goto badlevel;
+        }
+    } else {
+        str = "1"; /* Needed to format the error message. */
+        level = 1;
+    }
+    /* Lookup */
+    framePtr = interp->framePtr;
+    if (newLevelPtr) *newLevelPtr = (*newLevelPtr)-level;
+    while (level--) {
+        framePtr = framePtr->parentCallFrame;
+        if (framePtr == NULL) goto badlevel;
+    }
+    *framePtrPtr = framePtr;
+    return JIM_OK;
+badlevel:
+    Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+    Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "bad level \"", str, "\"", NULL);
+    return JIM_ERR;
+}
+
+/* Similar to Jim_GetCallFrameByLevel() but the level is specified
+ * as a relative integer like in the [info level ?level?] command. */
+static int JimGetCallFrameByInteger(Jim_Interp *interp, Jim_Obj *levelObjPtr,
+        Jim_CallFrame **framePtrPtr)
+{
+    jim_wide level;
+    jim_wide relLevel; /* level relative to the current one. */
+    Jim_CallFrame *framePtr;
+
+    if (Jim_GetWide(interp, levelObjPtr, &level) != JIM_OK)
+        goto badlevel;
+    if (level > 0) {
+        /* An 'absolute' level is converted into the
+         * 'number of levels to go back' format. */
+        relLevel = interp->numLevels - level;
+    } else {
+        relLevel = -level;
+    }
+    /* Lookup */
+    framePtr = interp->framePtr;
+    while (relLevel--) {
+        framePtr = framePtr->parentCallFrame;
+        if (framePtr == NULL) goto badlevel;
+    }
+    *framePtrPtr = framePtr;
+    return JIM_OK;
+badlevel:
+    Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+    Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "bad level \"", Jim_GetString(levelObjPtr, NULL), "\"", NULL);
+    return JIM_ERR;
+}
+
+static void JimSetErrorFileName(Jim_Interp *interp, char *filename)
+{
+    Jim_Free((void*)interp->errorFileName);
+    interp->errorFileName = Jim_StrDup(filename);
+}
+
+static void JimSetErrorLineNumber(Jim_Interp *interp, int linenr)
+{
+    interp->errorLine = linenr;
+}
+
+static void JimResetStackTrace(Jim_Interp *interp)
+{
+    Jim_DecrRefCount(interp, interp->stackTrace);
+    interp->stackTrace = Jim_NewListObj(interp, NULL, 0);
+    Jim_IncrRefCount(interp->stackTrace);
+}
+
+static void JimAppendStackTrace(Jim_Interp *interp, const char *procname,
+        const char *filename, int linenr)
+{
+    if (Jim_IsShared(interp->stackTrace)) {
+        interp->stackTrace =
+            Jim_DuplicateObj(interp, interp->stackTrace);
+        Jim_IncrRefCount(interp->stackTrace);
+    }
+    Jim_ListAppendElement(interp, interp->stackTrace,
+            Jim_NewStringObj(interp, procname, -1));
+    Jim_ListAppendElement(interp, interp->stackTrace,
+            Jim_NewStringObj(interp, filename, -1));
+    Jim_ListAppendElement(interp, interp->stackTrace,
+            Jim_NewIntObj(interp, linenr));
+}
+
+int Jim_SetAssocData(Jim_Interp *interp, const char *key, Jim_InterpDeleteProc *delProc, void *data)
+{
+    AssocDataValue *assocEntryPtr = (AssocDataValue *)Jim_Alloc(sizeof(AssocDataValue));
+    assocEntryPtr->delProc = delProc;
+    assocEntryPtr->data = data;
+    return Jim_AddHashEntry(&interp->assocData, key, assocEntryPtr);
+}
+
+void *Jim_GetAssocData(Jim_Interp *interp, const char *key)
+{
+    Jim_HashEntry *entryPtr = Jim_FindHashEntry(&interp->assocData, key);
+    if (entryPtr != NULL) {
+        AssocDataValue *assocEntryPtr = (AssocDataValue *)entryPtr->val;
+        return assocEntryPtr->data;
+    }
+    return NULL;
+}
+
+int Jim_DeleteAssocData(Jim_Interp *interp, const char *key)
+{
+    return Jim_DeleteHashEntry(&interp->assocData, key);
+}
+
+int Jim_GetExitCode(Jim_Interp *interp) {
+    return interp->exitCode;
+}
+
+FILE *Jim_SetStdin(Jim_Interp *interp, FILE *fp)
+{
+    if (fp != NULL) interp->stdin = fp;
+    return interp->stdin;
+}
+
+FILE *Jim_SetStdout(Jim_Interp *interp, FILE *fp)
+{
+    if (fp != NULL) interp->stdout = fp;
+    return interp->stdout;
+}
+
+FILE *Jim_SetStderr(Jim_Interp *interp, FILE *fp)
+{
+    if (fp != NULL) interp->stderr = fp;
+    return interp->stderr;
+}
+
+/* -----------------------------------------------------------------------------
+ * Shared strings.
+ * Every interpreter has an hash table where to put shared dynamically
+ * allocate strings that are likely to be used a lot of times.
+ * For example, in the 'source' object type, there is a pointer to
+ * the filename associated with that object. Every script has a lot
+ * of this objects with the identical file name, so it is wise to share
+ * this info.
+ *
+ * The API is trivial: Jim_GetSharedString(interp, "foobar")
+ * returns the pointer to the shared string. Every time a reference
+ * to the string is no longer used, the user should call
+ * Jim_ReleaseSharedString(interp, stringPointer). Once no one is using
+ * a given string, it is removed from the hash table.
+ * ---------------------------------------------------------------------------*/
+const char *Jim_GetSharedString(Jim_Interp *interp, const char *str)
+{
+    Jim_HashEntry *he = Jim_FindHashEntry(&interp->sharedStrings, str);
+
+    if (he == NULL) {
+        char *strCopy = Jim_StrDup(str);
+
+        Jim_AddHashEntry(&interp->sharedStrings, strCopy, (void*)1);
+        return strCopy;
+    } else {
+        long refCount = (long) he->val;
+
+        refCount++;
+        he->val = (void*) refCount;
+        return he->key;
+    }
+}
+
+void Jim_ReleaseSharedString(Jim_Interp *interp, const char *str)
+{
+    long refCount;
+    Jim_HashEntry *he = Jim_FindHashEntry(&interp->sharedStrings, str);
+
+    if (he == NULL)
+        Jim_Panic(interp,"Jim_ReleaseSharedString called with "
+              "unknown shared string '%s'", str);
+    refCount = (long) he->val;
+    refCount--;
+    if (refCount == 0) {
+        Jim_DeleteHashEntry(&interp->sharedStrings, str);
+    } else {
+        he->val = (void*) refCount;
+    }
+}
+
+/* -----------------------------------------------------------------------------
+ * Integer object
+ * ---------------------------------------------------------------------------*/
+#define JIM_INTEGER_SPACE 24
+
+static void UpdateStringOfInt(struct Jim_Obj *objPtr);
+static int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags);
+
+static Jim_ObjType intObjType = {
+    "int",
+    NULL,
+    NULL,
+    UpdateStringOfInt,
+    JIM_TYPE_NONE,
+};
+
+void UpdateStringOfInt(struct Jim_Obj *objPtr)
+{
+    int len;
+    char buf[JIM_INTEGER_SPACE+1];
+
+    len = Jim_WideToString(buf, objPtr->internalRep.wideValue);
+    objPtr->bytes = Jim_Alloc(len+1);
+    memcpy(objPtr->bytes, buf, len+1);
+    objPtr->length = len;
+}
+
+int SetIntFromAny(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+    jim_wide wideValue;
+    const char *str;
+
+    /* Get the string representation */
+    str = Jim_GetString(objPtr, NULL);
+    /* Try to convert into a jim_wide */
+    if (Jim_StringToWide(str, &wideValue, 0) != JIM_OK) {
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                    "expected integer but got \"", str, "\"", NULL);
+        }
+        return JIM_ERR;
+    }
+    if ((wideValue == JIM_WIDE_MIN || wideValue == JIM_WIDE_MAX) &&
+        errno == ERANGE) {
+        Jim_SetResultString(interp,
+            "Integer value too big to be represented", -1);
+        return JIM_ERR;
+    }
+    /* Free the old internal repr and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &intObjType;
+    objPtr->internalRep.wideValue = wideValue;
+    return JIM_OK;
+}
+
+int Jim_GetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide *widePtr)
+{
+    if (objPtr->typePtr != &intObjType &&
+        SetIntFromAny(interp, objPtr, JIM_ERRMSG) == JIM_ERR)
+        return JIM_ERR;
+    *widePtr = objPtr->internalRep.wideValue;
+    return JIM_OK;
+}
+
+/* Get a wide but does not set an error if the format is bad. */
+static int JimGetWideNoErr(Jim_Interp *interp, Jim_Obj *objPtr,
+        jim_wide *widePtr)
+{
+    if (objPtr->typePtr != &intObjType &&
+        SetIntFromAny(interp, objPtr, JIM_NONE) == JIM_ERR)
+        return JIM_ERR;
+    *widePtr = objPtr->internalRep.wideValue;
+    return JIM_OK;
+}
+
+int Jim_GetLong(Jim_Interp *interp, Jim_Obj *objPtr, long *longPtr)
+{
+    jim_wide wideValue;
+    int retval;
+
+    retval = Jim_GetWide(interp, objPtr, &wideValue);
+    if (retval == JIM_OK) {
+        *longPtr = (long) wideValue;
+        return JIM_OK;
+    }
+    return JIM_ERR;
+}
+
+void Jim_SetWide(Jim_Interp *interp, Jim_Obj *objPtr, jim_wide wideValue)
+{
+    if (Jim_IsShared(objPtr))
+        Jim_Panic(interp,"Jim_SetWide called with shared object");
+    if (objPtr->typePtr != &intObjType) {
+        Jim_FreeIntRep(interp, objPtr);
+        objPtr->typePtr = &intObjType;
+    }
+    Jim_InvalidateStringRep(objPtr);
+    objPtr->internalRep.wideValue = wideValue;
+}
+
+Jim_Obj *Jim_NewIntObj(Jim_Interp *interp, jim_wide wideValue)
+{
+    Jim_Obj *objPtr;
+
+    objPtr = Jim_NewObj(interp);
+    objPtr->typePtr = &intObjType;
+    objPtr->bytes = NULL;
+    objPtr->internalRep.wideValue = wideValue;
+    return objPtr;
+}
+
+/* -----------------------------------------------------------------------------
+ * Double object
+ * ---------------------------------------------------------------------------*/
+#define JIM_DOUBLE_SPACE 30
+
+static void UpdateStringOfDouble(struct Jim_Obj *objPtr);
+static int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
+
+static Jim_ObjType doubleObjType = {
+    "double",
+    NULL,
+    NULL,
+    UpdateStringOfDouble,
+    JIM_TYPE_NONE,
+};
+
+void UpdateStringOfDouble(struct Jim_Obj *objPtr)
+{
+    int len;
+    char buf[JIM_DOUBLE_SPACE+1];
+
+    len = Jim_DoubleToString(buf, objPtr->internalRep.doubleValue);
+    objPtr->bytes = Jim_Alloc(len+1);
+    memcpy(objPtr->bytes, buf, len+1);
+    objPtr->length = len;
+}
+
+int SetDoubleFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    double doubleValue;
+    const char *str;
+
+    /* Get the string representation */
+    str = Jim_GetString(objPtr, NULL);
+    /* Try to convert into a double */
+    if (Jim_StringToDouble(str, &doubleValue) != JIM_OK) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "expected number but got '", str, "'", NULL);
+        return JIM_ERR;
+    }
+    /* Free the old internal repr and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &doubleObjType;
+    objPtr->internalRep.doubleValue = doubleValue;
+    return JIM_OK;
+}
+
+int Jim_GetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double *doublePtr)
+{
+    if (objPtr->typePtr != &doubleObjType &&
+        SetDoubleFromAny(interp, objPtr) == JIM_ERR)
+        return JIM_ERR;
+    *doublePtr = objPtr->internalRep.doubleValue;
+    return JIM_OK;
+}
+
+void Jim_SetDouble(Jim_Interp *interp, Jim_Obj *objPtr, double doubleValue)
+{
+    if (Jim_IsShared(objPtr))
+        Jim_Panic(interp,"Jim_SetDouble called with shared object");
+    if (objPtr->typePtr != &doubleObjType) {
+        Jim_FreeIntRep(interp, objPtr);
+        objPtr->typePtr = &doubleObjType;
+    }
+    Jim_InvalidateStringRep(objPtr);
+    objPtr->internalRep.doubleValue = doubleValue;
+}
+
+Jim_Obj *Jim_NewDoubleObj(Jim_Interp *interp, double doubleValue)
+{
+    Jim_Obj *objPtr;
+
+    objPtr = Jim_NewObj(interp);
+    objPtr->typePtr = &doubleObjType;
+    objPtr->bytes = NULL;
+    objPtr->internalRep.doubleValue = doubleValue;
+    return objPtr;
+}
+
+/* -----------------------------------------------------------------------------
+ * List object
+ * ---------------------------------------------------------------------------*/
+static void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr);
+static void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static void UpdateStringOfList(struct Jim_Obj *objPtr);
+static int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+/* Note that while the elements of the list may contain references,
+ * the list object itself can't. This basically means that the
+ * list object string representation as a whole can't contain references
+ * that are not presents in the single elements. */
+static Jim_ObjType listObjType = {
+    "list",
+    FreeListInternalRep,
+    DupListInternalRep,
+    UpdateStringOfList,
+    JIM_TYPE_NONE,
+};
+
+void FreeListInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    int i;
+
+    for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
+        Jim_DecrRefCount(interp, objPtr->internalRep.listValue.ele[i]);
+    }
+    Jim_Free(objPtr->internalRep.listValue.ele);
+}
+
+void DupListInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+    int i;
+    JIM_NOTUSED(interp);
+
+    dupPtr->internalRep.listValue.len = srcPtr->internalRep.listValue.len;
+    dupPtr->internalRep.listValue.maxLen = srcPtr->internalRep.listValue.maxLen;
+    dupPtr->internalRep.listValue.ele =
+        Jim_Alloc(sizeof(Jim_Obj*)*srcPtr->internalRep.listValue.maxLen);
+    memcpy(dupPtr->internalRep.listValue.ele, srcPtr->internalRep.listValue.ele,
+            sizeof(Jim_Obj*)*srcPtr->internalRep.listValue.len);
+    for (i = 0; i < dupPtr->internalRep.listValue.len; i++) {
+        Jim_IncrRefCount(dupPtr->internalRep.listValue.ele[i]);
+    }
+    dupPtr->typePtr = &listObjType;
+}
+
+/* The following function checks if a given string can be encoded
+ * into a list element without any kind of quoting, surrounded by braces,
+ * or using escapes to quote. */
+#define JIM_ELESTR_SIMPLE 0
+#define JIM_ELESTR_BRACE 1
+#define JIM_ELESTR_QUOTE 2
+static int ListElementQuotingType(const char *s, int len)
+{
+    int i, level, trySimple = 1;
+
+    /* Try with the SIMPLE case */
+    if (len == 0) return JIM_ELESTR_BRACE;
+    if (s[0] == '"' || s[0] == '{') {
+        trySimple = 0;
+        goto testbrace;
+    }
+    for (i = 0; i < len; i++) {
+        switch(s[i]) {
+        case ' ':
+        case '$':
+        case '"':
+        case '[':
+        case ']':
+        case ';':
+        case '\\':
+        case '\r':
+        case '\n':
+        case '\t':
+        case '\f':
+        case '\v':
+            trySimple = 0;
+        case '{':
+        case '}':
+            goto testbrace;
+        }
+    }
+    return JIM_ELESTR_SIMPLE;
+
+testbrace:
+    /* Test if it's possible to do with braces */
+    if (s[len-1] == '\\' ||
+        s[len-1] == ']') return JIM_ELESTR_QUOTE;
+    level = 0;
+    for (i = 0; i < len; i++) {
+        switch(s[i]) {
+        case '{': level++; break;
+        case '}': level--;
+              if (level < 0) return JIM_ELESTR_QUOTE;
+              break;
+        case '\\':
+              if (s[i+1] == '\n')
+                  return JIM_ELESTR_QUOTE;
+              else
+                  if (s[i+1] != '\0') i++;
+              break;
+        }
+    }
+    if (level == 0) {
+        if (!trySimple) return JIM_ELESTR_BRACE;
+        for (i = 0; i < len; i++) {
+            switch(s[i]) {
+            case ' ':
+            case '$':
+            case '"':
+            case '[':
+            case ']':
+            case ';':
+            case '\\':
+            case '\r':
+            case '\n':
+            case '\t':
+            case '\f':
+            case '\v':
+                return JIM_ELESTR_BRACE;
+                break;
+            }
+        }
+        return JIM_ELESTR_SIMPLE;
+    }
+    return JIM_ELESTR_QUOTE;
+}
+
+/* Returns the malloc-ed representation of a string
+ * using backslash to quote special chars. */
+char *BackslashQuoteString(const char *s, int len, int *qlenPtr)
+{
+    char *q = Jim_Alloc(len*2+1), *p;
+
+    p = q;
+    while(*s) {
+        switch (*s) {
+        case ' ':
+        case '$':
+        case '"':
+        case '[':
+        case ']':
+        case '{':
+        case '}':
+        case ';':
+        case '\\':
+            *p++ = '\\';
+            *p++ = *s++;
+            break;
+        case '\n': *p++ = '\\'; *p++ = 'n'; s++; break;
+        case '\r': *p++ = '\\'; *p++ = 'r'; s++; break;
+        case '\t': *p++ = '\\'; *p++ = 't'; s++; break;
+        case '\f': *p++ = '\\'; *p++ = 'f'; s++; break;
+        case '\v': *p++ = '\\'; *p++ = 'v'; s++; break;
+        default:
+            *p++ = *s++;
+            break;
+        }
+    }
+    *p = '\0';
+    *qlenPtr = p-q;
+    return q;
+}
+
+void UpdateStringOfList(struct Jim_Obj *objPtr)
+{
+    int i, bufLen, realLength;
+    const char *strRep;
+    char *p;
+    int *quotingType;
+    Jim_Obj **ele = objPtr->internalRep.listValue.ele;
+
+    /* (Over) Estimate the space needed. */
+    quotingType = Jim_Alloc(sizeof(int)*objPtr->internalRep.listValue.len+1);
+    bufLen = 0;
+    for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
+        int len;
+
+        strRep = Jim_GetString(ele[i], &len);
+        quotingType[i] = ListElementQuotingType(strRep, len);
+        switch (quotingType[i]) {
+        case JIM_ELESTR_SIMPLE: bufLen += len; break;
+        case JIM_ELESTR_BRACE: bufLen += len+2; break;
+        case JIM_ELESTR_QUOTE: bufLen += len*2; break;
+        }
+        bufLen++; /* elements separator. */
+    }
+    bufLen++;
+
+    /* Generate the string rep. */
+    p = objPtr->bytes = Jim_Alloc(bufLen+1);
+    realLength = 0;
+    for (i = 0; i < objPtr->internalRep.listValue.len; i++) {
+        int len, qlen;
+        const char *strRep = Jim_GetString(ele[i], &len);
+        char *q;
+
+        switch(quotingType[i]) {
+        case JIM_ELESTR_SIMPLE:
+            memcpy(p, strRep, len);
+            p += len;
+            realLength += len;
+            break;
+        case JIM_ELESTR_BRACE:
+            *p++ = '{';
+            memcpy(p, strRep, len);
+            p += len;
+            *p++ = '}';
+            realLength += len+2;
+            break;
+        case JIM_ELESTR_QUOTE:
+            q = BackslashQuoteString(strRep, len, &qlen);
+            memcpy(p, q, qlen);
+            Jim_Free(q);
+            p += qlen;
+            realLength += qlen;
+            break;
+        }
+        /* Add a separating space */
+        if (i+1 != objPtr->internalRep.listValue.len) {
+            *p++ = ' ';
+            realLength ++;
+        }
+    }
+    *p = '\0'; /* nul term. */
+    objPtr->length = realLength;
+    Jim_Free(quotingType);
+}
+
+int SetListFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+    struct JimParserCtx parser;
+    const char *str;
+    int strLen;
+
+    /* Get the string representation */
+    str = Jim_GetString(objPtr, &strLen);
+
+    /* Free the old internal repr just now and initialize the
+     * new one just now. The string->list conversion can't fail. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &listObjType;
+    objPtr->internalRep.listValue.len = 0;
+    objPtr->internalRep.listValue.maxLen = 0;
+    objPtr->internalRep.listValue.ele = NULL;
+
+    /* Convert into a list */
+    JimParserInit(&parser, str, strLen, 1);
+    while(!JimParserEof(&parser)) {
+        char *token;
+        int tokenLen, type;
+        Jim_Obj *elementPtr;
+
+        JimParseList(&parser);
+        if (JimParserTtype(&parser) != JIM_TT_STR &&
+            JimParserTtype(&parser) != JIM_TT_ESC)
+            continue;
+        token = JimParserGetToken(&parser, &tokenLen, &type, NULL);
+        elementPtr = Jim_NewStringObjNoAlloc(interp, token, tokenLen);
+        ListAppendElement(objPtr, elementPtr);
+    }
+    return JIM_OK;
+}
+
+Jim_Obj *Jim_NewListObj(Jim_Interp *interp, Jim_Obj *const *elements, 
+        int len)
+{
+    Jim_Obj *objPtr;
+    int i;
+
+    objPtr = Jim_NewObj(interp);
+    objPtr->typePtr = &listObjType;
+    objPtr->bytes = NULL;
+    objPtr->internalRep.listValue.ele = NULL;
+    objPtr->internalRep.listValue.len = 0;
+    objPtr->internalRep.listValue.maxLen = 0;
+    for (i = 0; i < len; i++) {
+        ListAppendElement(objPtr, elements[i]);
+    }
+    return objPtr;
+}
+
+/* Return a vector of Jim_Obj with the elements of a Jim list, and the
+ * length of the vector. Note that the user of this function should make
+ * sure that the list object can't shimmer while the vector returned
+ * is in use, this vector is the one stored inside the internal representation
+ * of the list object. This function is not exported, extensions should
+ * always access to the List object elements using Jim_ListIndex(). */
+static void JimListGetElements(Jim_Interp *interp, Jim_Obj *listObj, int *argc,
+        Jim_Obj ***listVec)
+{
+    Jim_ListLength(interp, listObj, argc);
+    assert(listObj->typePtr == &listObjType);
+    *listVec = listObj->internalRep.listValue.ele;
+}
+
+/* ListSortElements type values */
+enum {JIM_LSORT_ASCII, JIM_LSORT_NOCASE, JIM_LSORT_ASCII_DECR,
+      JIM_LSORT_NOCASE_DECR};
+
+/* Sort the internal rep of a list. */
+static int ListSortString(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+    return Jim_StringCompareObj(*lhsObj, *rhsObj, 0);
+}
+
+static int ListSortStringDecr(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+    return Jim_StringCompareObj(*lhsObj, *rhsObj, 0) * -1;
+}
+
+static int ListSortStringNoCase(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+    return Jim_StringCompareObj(*lhsObj, *rhsObj, 1);
+}
+
+static int ListSortStringNoCaseDecr(Jim_Obj **lhsObj, Jim_Obj **rhsObj)
+{
+    return Jim_StringCompareObj(*lhsObj, *rhsObj, 1) * -1;
+}
+
+/* Sort a list *in place*. MUST be called with non-shared objects. */
+static void ListSortElements(Jim_Interp *interp, Jim_Obj *listObjPtr, int type)
+{
+    typedef int (qsort_comparator)(const void *, const void *);
+    int (*fn)(Jim_Obj**, Jim_Obj**);
+    Jim_Obj **vector;
+    int len;
+
+    if (Jim_IsShared(listObjPtr))
+        Jim_Panic(interp,"Jim_ListSortElements called with shared object");
+    if (listObjPtr->typePtr != &listObjType)
+        SetListFromAny(interp, listObjPtr);
+
+    vector = listObjPtr->internalRep.listValue.ele;
+    len = listObjPtr->internalRep.listValue.len;
+    switch (type) {
+        case JIM_LSORT_ASCII: fn = ListSortString;  break;
+        case JIM_LSORT_NOCASE: fn = ListSortStringNoCase;  break;
+        case JIM_LSORT_ASCII_DECR: fn = ListSortStringDecr;  break;
+        case JIM_LSORT_NOCASE_DECR: fn = ListSortStringNoCaseDecr;  break;
+        default:
+            fn = NULL; /* avoid warning */
+            Jim_Panic(interp,"ListSort called with invalid sort type");
+    }
+    qsort(vector, len, sizeof(Jim_Obj *), (qsort_comparator *)fn);
+    Jim_InvalidateStringRep(listObjPtr);
+}
+
+/* This is the low-level function to append an element to a list.
+ * The higher-level Jim_ListAppendElement() performs shared object
+ * check and invalidate the string repr. This version is used
+ * in the internals of the List Object and is not exported.
+ *
+ * NOTE: this function can be called only against objects
+ * with internal type of List. */
+void ListAppendElement(Jim_Obj *listPtr, Jim_Obj *objPtr)
+{
+    int requiredLen = listPtr->internalRep.listValue.len + 1;
+
+    if (requiredLen > listPtr->internalRep.listValue.maxLen) {
+        int maxLen = requiredLen * 2;
+
+        listPtr->internalRep.listValue.ele =
+            Jim_Realloc(listPtr->internalRep.listValue.ele,
+                    sizeof(Jim_Obj*)*maxLen);
+        listPtr->internalRep.listValue.maxLen = maxLen;
+    }
+    listPtr->internalRep.listValue.ele[listPtr->internalRep.listValue.len] =
+        objPtr;
+    listPtr->internalRep.listValue.len ++;
+    Jim_IncrRefCount(objPtr);
+}
+
+/* This is the low-level function to insert elements into a list.
+ * The higher-level Jim_ListInsertElements() performs shared object
+ * check and invalidate the string repr. This version is used
+ * in the internals of the List Object and is not exported.
+ *
+ * NOTE: this function can be called only against objects
+ * with internal type of List. */
+void ListInsertElements(Jim_Obj *listPtr, int index, int elemc,
+        Jim_Obj *const *elemVec)
+{
+    int currentLen = listPtr->internalRep.listValue.len;
+    int requiredLen = currentLen + elemc;
+    int i;
+    Jim_Obj **point;
+
+    if (requiredLen > listPtr->internalRep.listValue.maxLen) {
+        int maxLen = requiredLen * 2;
+
+        listPtr->internalRep.listValue.ele =
+            Jim_Realloc(listPtr->internalRep.listValue.ele,
+                    sizeof(Jim_Obj*)*maxLen);
+        listPtr->internalRep.listValue.maxLen = maxLen;
+    }
+    point = listPtr->internalRep.listValue.ele + index;
+    memmove(point+elemc, point, (currentLen-index) * sizeof(Jim_Obj*));
+    for (i=0; i < elemc; ++i) {
+        point[i] = elemVec[i];
+        Jim_IncrRefCount(point[i]);
+    }
+    listPtr->internalRep.listValue.len += elemc;
+}
+
+/* Appends every element of appendListPtr into listPtr.
+ * Both have to be of the list type. */
+void ListAppendList(Jim_Obj *listPtr, Jim_Obj *appendListPtr)
+{
+    int i, oldLen = listPtr->internalRep.listValue.len;
+    int appendLen = appendListPtr->internalRep.listValue.len;
+    int requiredLen = oldLen + appendLen;
+
+    if (requiredLen > listPtr->internalRep.listValue.maxLen) {
+        int maxLen = requiredLen * 2;
+
+        listPtr->internalRep.listValue.ele =
+            Jim_Realloc(listPtr->internalRep.listValue.ele,
+                    sizeof(Jim_Obj*)*maxLen);
+        listPtr->internalRep.listValue.maxLen = maxLen;
+    }
+    for (i = 0; i < appendLen; i++) {
+        Jim_Obj *objPtr = appendListPtr->internalRep.listValue.ele[i];
+        listPtr->internalRep.listValue.ele[oldLen+i] = objPtr;
+        Jim_IncrRefCount(objPtr);
+    }
+    listPtr->internalRep.listValue.len += appendLen;
+}
+
+void Jim_ListAppendElement(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *objPtr)
+{
+    if (Jim_IsShared(listPtr))
+        Jim_Panic(interp,"Jim_ListAppendElement called with shared object");
+    if (listPtr->typePtr != &listObjType)
+        SetListFromAny(interp, listPtr);
+    Jim_InvalidateStringRep(listPtr);
+    ListAppendElement(listPtr, objPtr);
+}
+
+void Jim_ListAppendList(Jim_Interp *interp, Jim_Obj *listPtr, Jim_Obj *appendListPtr)
+{
+    if (Jim_IsShared(listPtr))
+        Jim_Panic(interp,"Jim_ListAppendList called with shared object");
+    if (listPtr->typePtr != &listObjType)
+        SetListFromAny(interp, listPtr);
+    Jim_InvalidateStringRep(listPtr);
+    ListAppendList(listPtr, appendListPtr);
+}
+
+void Jim_ListLength(Jim_Interp *interp, Jim_Obj *listPtr, int *intPtr)
+{
+    if (listPtr->typePtr != &listObjType)
+        SetListFromAny(interp, listPtr);
+    *intPtr = listPtr->internalRep.listValue.len;
+}
+
+void Jim_ListInsertElements(Jim_Interp *interp, Jim_Obj *listPtr, int index,
+        int objc, Jim_Obj *const *objVec)
+{
+    if (Jim_IsShared(listPtr))
+        Jim_Panic(interp,"Jim_ListInsertElement called with shared object");
+    if (listPtr->typePtr != &listObjType)
+        SetListFromAny(interp, listPtr);
+    if (index >= 0 && index > listPtr->internalRep.listValue.len)
+        index = listPtr->internalRep.listValue.len;
+    else if (index < 0 ) 
+        index = 0;
+    Jim_InvalidateStringRep(listPtr);
+    ListInsertElements(listPtr, index, objc, objVec);
+}
+
+int Jim_ListIndex(Jim_Interp *interp, Jim_Obj *listPtr, int index,
+        Jim_Obj **objPtrPtr, int flags)
+{
+    if (listPtr->typePtr != &listObjType)
+        SetListFromAny(interp, listPtr);
+    if ((index >= 0 && index >= listPtr->internalRep.listValue.len) ||
+        (index < 0 && (-index-1) >= listPtr->internalRep.listValue.len)) {
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResultString(interp,
+                "list index out of range", -1);
+        }
+        return JIM_ERR;
+    }
+    if (index < 0)
+        index = listPtr->internalRep.listValue.len+index;
+    *objPtrPtr = listPtr->internalRep.listValue.ele[index];
+    return JIM_OK;
+}
+
+static int ListSetIndex(Jim_Interp *interp, Jim_Obj *listPtr, int index,
+        Jim_Obj *newObjPtr, int flags)
+{
+    if (listPtr->typePtr != &listObjType)
+        SetListFromAny(interp, listPtr);
+    if ((index >= 0 && index >= listPtr->internalRep.listValue.len) ||
+        (index < 0 && (-index-1) >= listPtr->internalRep.listValue.len)) {
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResultString(interp,
+                "list index out of range", -1);
+        }
+        return JIM_ERR;
+    }
+    if (index < 0)
+        index = listPtr->internalRep.listValue.len+index;
+    Jim_DecrRefCount(interp, listPtr->internalRep.listValue.ele[index]);
+    listPtr->internalRep.listValue.ele[index] = newObjPtr;
+    Jim_IncrRefCount(newObjPtr);
+    return JIM_OK;
+}
+
+/* Modify the list stored into the variable named 'varNamePtr'
+ * setting the element specified by the 'indexc' indexes objects in 'indexv',
+ * with the new element 'newObjptr'. */
+int Jim_SetListIndex(Jim_Interp *interp, Jim_Obj *varNamePtr,
+        Jim_Obj *const *indexv, int indexc, Jim_Obj *newObjPtr)
+{
+    Jim_Obj *varObjPtr, *objPtr, *listObjPtr;
+    int shared, i, index;
+
+    varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
+    if (objPtr == NULL)
+        return JIM_ERR;
+    if ((shared = Jim_IsShared(objPtr)))
+        varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
+    for (i = 0; i < indexc-1; i++) {
+        listObjPtr = objPtr;
+        if (Jim_GetIndex(interp, indexv[i], &index) != JIM_OK)
+            goto err;
+        if (Jim_ListIndex(interp, listObjPtr, index, &objPtr,
+                    JIM_ERRMSG) != JIM_OK) {
+            goto err;
+        }
+        if (Jim_IsShared(objPtr)) {
+            objPtr = Jim_DuplicateObj(interp, objPtr);
+            ListSetIndex(interp, listObjPtr, index, objPtr, JIM_NONE);
+        }
+        Jim_InvalidateStringRep(listObjPtr);
+    }
+    if (Jim_GetIndex(interp, indexv[indexc-1], &index) != JIM_OK)
+        goto err;
+    if (ListSetIndex(interp, objPtr, index, newObjPtr, JIM_ERRMSG) == JIM_ERR)
+        goto err;
+    Jim_InvalidateStringRep(objPtr);
+    Jim_InvalidateStringRep(varObjPtr);
+    if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
+        goto err;
+    Jim_SetResult(interp, varObjPtr);
+    return JIM_OK;
+err:
+    if (shared) {
+        Jim_FreeNewObj(interp, varObjPtr);
+    }
+    return JIM_ERR;
+}
+
+Jim_Obj *Jim_ConcatObj(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+{
+    int i;
+
+    /* If all the objects in objv are lists without string rep.
+     * it's possible to return a list as result, that's the
+     * concatenation of all the lists. */
+    for (i = 0; i < objc; i++) {
+        if (objv[i]->typePtr != &listObjType || objv[i]->bytes)
+            break;
+    }
+    if (i == objc) {
+        Jim_Obj *objPtr = Jim_NewListObj(interp, NULL, 0);
+        for (i = 0; i < objc; i++)
+            Jim_ListAppendList(interp, objPtr, objv[i]);
+        return objPtr;
+    } else {
+        /* Else... we have to glue strings together */
+        int len = 0, objLen;
+        char *bytes, *p;
+
+        /* Compute the length */
+        for (i = 0; i < objc; i++) {
+            Jim_GetString(objv[i], &objLen);
+            len += objLen;
+        }
+        if (objc) len += objc-1;
+        /* Create the string rep, and a stinrg object holding it. */
+        p = bytes = Jim_Alloc(len+1);
+        for (i = 0; i < objc; i++) {
+            const char *s = Jim_GetString(objv[i], &objLen);
+            while (objLen && (*s == ' ' || *s == '\t' || *s == '\n'))
+            {
+                s++; objLen--; len--;
+            }
+            while (objLen && (s[objLen-1] == ' ' ||
+                s[objLen-1] == '\n' || s[objLen-1] == '\t')) {
+                objLen--; len--;
+            }
+            memcpy(p, s, objLen);
+            p += objLen;
+            if (objLen && i+1 != objc) {
+                *p++ = ' ';
+            } else if (i+1 != objc) {
+                /* Drop the space calcuated for this
+                 * element that is instead null. */
+                len--;
+            }
+        }
+        *p = '\0';
+        return Jim_NewStringObjNoAlloc(interp, bytes, len);
+    }
+}
+
+/* Returns a list composed of the elements in the specified range.
+ * first and start are directly accepted as Jim_Objects and
+ * processed for the end?-index? case. */
+Jim_Obj *Jim_ListRange(Jim_Interp *interp, Jim_Obj *listObjPtr, Jim_Obj *firstObjPtr, Jim_Obj *lastObjPtr)
+{
+    int first, last;
+    int len, rangeLen;
+
+    if (Jim_GetIndex(interp, firstObjPtr, &first) != JIM_OK ||
+        Jim_GetIndex(interp, lastObjPtr, &last) != JIM_OK)
+        return NULL;
+    Jim_ListLength(interp, listObjPtr, &len); /* will convert into list */
+    first = JimRelToAbsIndex(len, first);
+    last = JimRelToAbsIndex(len, last);
+    JimRelToAbsRange(len, first, last, &first, &last, &rangeLen);
+    return Jim_NewListObj(interp,
+            listObjPtr->internalRep.listValue.ele+first, rangeLen);
+}
+
+/* -----------------------------------------------------------------------------
+ * Dict object
+ * ---------------------------------------------------------------------------*/
+static void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static void UpdateStringOfDict(struct Jim_Obj *objPtr);
+static int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+/* Dict HashTable Type.
+ *
+ * Keys and Values are Jim objects. */
+
+unsigned int JimObjectHTHashFunction(const void *key)
+{
+    const char *str;
+    Jim_Obj *objPtr = (Jim_Obj*) key;
+    int len, h;
+
+    str = Jim_GetString(objPtr, &len);
+    h = Jim_GenHashFunction((unsigned char*)str, len);
+    return h;
+}
+
+int JimObjectHTKeyCompare(void *privdata, const void *key1, const void *key2)
+{
+    JIM_NOTUSED(privdata);
+
+    return Jim_StringEqObj((Jim_Obj*)key1, (Jim_Obj*)key2, 0);
+}
+
+static void JimObjectHTKeyValDestructor(void *interp, void *val)
+{
+    Jim_Obj *objPtr = val;
+
+    Jim_DecrRefCount(interp, objPtr);
+}
+
+static Jim_HashTableType JimDictHashTableType = {
+    JimObjectHTHashFunction,            /* hash function */
+    NULL,                               /* key dup */
+    NULL,                               /* val dup */
+    JimObjectHTKeyCompare,              /* key compare */
+    (void(*)(void*, const void*))       /* ATTENTION: const cast */
+        JimObjectHTKeyValDestructor,    /* key destructor */
+    JimObjectHTKeyValDestructor         /* val destructor */
+};
+
+/* Note that while the elements of the dict may contain references,
+ * the list object itself can't. This basically means that the
+ * dict object string representation as a whole can't contain references
+ * that are not presents in the single elements. */
+static Jim_ObjType dictObjType = {
+    "dict",
+    FreeDictInternalRep,
+    DupDictInternalRep,
+    UpdateStringOfDict,
+    JIM_TYPE_NONE,
+};
+
+void FreeDictInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    JIM_NOTUSED(interp);
+
+    Jim_FreeHashTable(objPtr->internalRep.ptr);
+    Jim_Free(objPtr->internalRep.ptr);
+}
+
+void DupDictInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+    Jim_HashTable *ht, *dupHt;
+    Jim_HashTableIterator *htiter;
+    Jim_HashEntry *he;
+
+    /* Create a new hash table */
+    ht = srcPtr->internalRep.ptr;
+    dupHt = Jim_Alloc(sizeof(*dupHt));
+    Jim_InitHashTable(dupHt, &JimDictHashTableType, interp);
+    if (ht->size != 0)
+        Jim_ExpandHashTable(dupHt, ht->size);
+    /* Copy every element from the source to the dup hash table */
+    htiter = Jim_GetHashTableIterator(ht);
+    while ((he = Jim_NextHashEntry(htiter)) != NULL) {
+        const Jim_Obj *keyObjPtr = he->key;
+        Jim_Obj *valObjPtr = he->val;
+
+        Jim_IncrRefCount((Jim_Obj*)keyObjPtr);  /* ATTENTION: const cast */
+        Jim_IncrRefCount(valObjPtr);
+        Jim_AddHashEntry(dupHt, keyObjPtr, valObjPtr);
+    }
+    Jim_FreeHashTableIterator(htiter);
+
+    dupPtr->internalRep.ptr = dupHt;
+    dupPtr->typePtr = &dictObjType;
+}
+
+void UpdateStringOfDict(struct Jim_Obj *objPtr)
+{
+    int i, bufLen, realLength;
+    const char *strRep;
+    char *p;
+    int *quotingType, objc;
+    Jim_HashTable *ht;
+    Jim_HashTableIterator *htiter;
+    Jim_HashEntry *he;
+    Jim_Obj **objv;
+
+    /* Trun the hash table into a flat vector of Jim_Objects. */
+    ht = objPtr->internalRep.ptr;
+    objc = ht->used*2;
+    objv = Jim_Alloc(objc*sizeof(Jim_Obj*));
+    htiter = Jim_GetHashTableIterator(ht);
+    i = 0;
+    while ((he = Jim_NextHashEntry(htiter)) != NULL) {
+        objv[i++] = (Jim_Obj*)he->key;  /* ATTENTION: const cast */
+        objv[i++] = he->val;
+    }
+    Jim_FreeHashTableIterator(htiter);
+    /* (Over) Estimate the space needed. */
+    quotingType = Jim_Alloc(sizeof(int)*objc);
+    bufLen = 0;
+    for (i = 0; i < objc; i++) {
+        int len;
+
+        strRep = Jim_GetString(objv[i], &len);
+        quotingType[i] = ListElementQuotingType(strRep, len);
+        switch (quotingType[i]) {
+        case JIM_ELESTR_SIMPLE: bufLen += len; break;
+        case JIM_ELESTR_BRACE: bufLen += len+2; break;
+        case JIM_ELESTR_QUOTE: bufLen += len*2; break;
+        }
+        bufLen++; /* elements separator. */
+    }
+    bufLen++;
+
+    /* Generate the string rep. */
+    p = objPtr->bytes = Jim_Alloc(bufLen+1);
+    realLength = 0;
+    for (i = 0; i < objc; i++) {
+        int len, qlen;
+        const char *strRep = Jim_GetString(objv[i], &len);
+        char *q;
+
+        switch(quotingType[i]) {
+        case JIM_ELESTR_SIMPLE:
+            memcpy(p, strRep, len);
+            p += len;
+            realLength += len;
+            break;
+        case JIM_ELESTR_BRACE:
+            *p++ = '{';
+            memcpy(p, strRep, len);
+            p += len;
+            *p++ = '}';
+            realLength += len+2;
+            break;
+        case JIM_ELESTR_QUOTE:
+            q = BackslashQuoteString(strRep, len, &qlen);
+            memcpy(p, q, qlen);
+            Jim_Free(q);
+            p += qlen;
+            realLength += qlen;
+            break;
+        }
+        /* Add a separating space */
+        if (i+1 != objc) {
+            *p++ = ' ';
+            realLength ++;
+        }
+    }
+    *p = '\0'; /* nul term. */
+    objPtr->length = realLength;
+    Jim_Free(quotingType);
+    Jim_Free(objv);
+}
+
+int SetDictFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+    struct JimParserCtx parser;
+    Jim_HashTable *ht;
+    Jim_Obj *objv[2];
+    const char *str;
+    int i, strLen;
+
+    /* Get the string representation */
+    str = Jim_GetString(objPtr, &strLen);
+
+    /* Free the old internal repr just now and initialize the
+     * new one just now. The string->list conversion can't fail. */
+    Jim_FreeIntRep(interp, objPtr);
+    ht = Jim_Alloc(sizeof(*ht));
+    Jim_InitHashTable(ht, &JimDictHashTableType, interp);
+    objPtr->typePtr = &dictObjType;
+    objPtr->internalRep.ptr = ht;
+
+    /* Convert into a dict */
+    JimParserInit(&parser, str, strLen, 1);
+    i = 0;
+    while(!JimParserEof(&parser)) {
+        char *token;
+        int tokenLen, type;
+
+        JimParseList(&parser);
+        if (JimParserTtype(&parser) != JIM_TT_STR &&
+            JimParserTtype(&parser) != JIM_TT_ESC)
+            continue;
+        token = JimParserGetToken(&parser, &tokenLen, &type, NULL);
+        objv[i++] = Jim_NewStringObjNoAlloc(interp, token, tokenLen);
+        if (i == 2) {
+            i = 0;
+            Jim_IncrRefCount(objv[0]);
+            Jim_IncrRefCount(objv[1]);
+            if (Jim_AddHashEntry(ht, objv[0], objv[1]) != JIM_OK) {
+                Jim_HashEntry *he;
+                he = Jim_FindHashEntry(ht, objv[0]);
+                Jim_DecrRefCount(interp, objv[0]);
+                /* ATTENTION: const cast */
+                Jim_DecrRefCount(interp, (Jim_Obj*)he->val);
+                he->val = objv[1];
+            }
+        }
+    }
+    if (i) {
+        Jim_FreeNewObj(interp, objv[0]);
+        objPtr->typePtr = NULL;
+        Jim_FreeHashTable(ht);
+        Jim_SetResultString(interp, "invalid dictionary value: must be a list with an even number of elements", -1);
+        return JIM_ERR;
+    }
+    return JIM_OK;
+}
+
+/* Dict object API */
+
+/* Add an element to a dict. objPtr must be of the "dict" type.
+ * The higer-level exported function is Jim_DictAddElement().
+ * If an element with the specified key already exists, the value
+ * associated is replaced with the new one.
+ *
+ * if valueObjPtr == NULL, the key is instead removed if it exists. */
+static void DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+        Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
+{
+    Jim_HashTable *ht = objPtr->internalRep.ptr;
+
+    if (valueObjPtr == NULL) { /* unset */
+        Jim_DeleteHashEntry(ht, keyObjPtr);
+        return;
+    }
+    Jim_IncrRefCount(keyObjPtr);
+    Jim_IncrRefCount(valueObjPtr);
+    if (Jim_AddHashEntry(ht, keyObjPtr, valueObjPtr) != JIM_OK) {
+        Jim_HashEntry *he = Jim_FindHashEntry(ht, keyObjPtr);
+        Jim_DecrRefCount(interp, keyObjPtr);
+        /* ATTENTION: const cast */
+        Jim_DecrRefCount(interp, (Jim_Obj*)he->val);
+        he->val = valueObjPtr;
+    }
+}
+
+/* Add an element, higher-level interface for DictAddElement().
+ * If valueObjPtr == NULL, the key is removed if it exists. */
+int Jim_DictAddElement(Jim_Interp *interp, Jim_Obj *objPtr,
+        Jim_Obj *keyObjPtr, Jim_Obj *valueObjPtr)
+{
+    if (Jim_IsShared(objPtr))
+        Jim_Panic(interp,"Jim_DictAddElement called with shared object");
+    if (objPtr->typePtr != &dictObjType) {
+        if (SetDictFromAny(interp, objPtr) != JIM_OK)
+            return JIM_ERR;
+    }
+    DictAddElement(interp, objPtr, keyObjPtr, valueObjPtr);
+    Jim_InvalidateStringRep(objPtr);
+    return JIM_OK;
+}
+
+Jim_Obj *Jim_NewDictObj(Jim_Interp *interp, Jim_Obj *const *elements, int len)
+{
+    Jim_Obj *objPtr;
+    int i;
+
+    if (len % 2)
+        Jim_Panic(interp,"Jim_NewDicObj() 'len' argument must be even");
+
+    objPtr = Jim_NewObj(interp);
+    objPtr->typePtr = &dictObjType;
+    objPtr->bytes = NULL;
+    objPtr->internalRep.ptr = Jim_Alloc(sizeof(Jim_HashTable));
+    Jim_InitHashTable(objPtr->internalRep.ptr, &JimDictHashTableType, interp);
+    for (i = 0; i < len; i += 2)
+        DictAddElement(interp, objPtr, elements[i], elements[i+1]);
+    return objPtr;
+}
+
+/* Return the value associated to the specified dict key */
+int Jim_DictKey(Jim_Interp *interp, Jim_Obj *dictPtr, Jim_Obj *keyPtr,
+        Jim_Obj **objPtrPtr, int flags)
+{
+    Jim_HashEntry *he;
+    Jim_HashTable *ht;
+
+    if (dictPtr->typePtr != &dictObjType) {
+        if (SetDictFromAny(interp, dictPtr) != JIM_OK)
+            return JIM_ERR;
+    }
+    ht = dictPtr->internalRep.ptr;
+    if ((he = Jim_FindHashEntry(ht, keyPtr)) == NULL) {
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                    "key \"", Jim_GetString(keyPtr, NULL),
+                    "\" not found in dictionary", NULL);
+        }
+        return JIM_ERR;
+    }
+    *objPtrPtr = he->val;
+    return JIM_OK;
+}
+
+/* Return the value associated to the specified dict keys */
+int Jim_DictKeysVector(Jim_Interp *interp, Jim_Obj *dictPtr,
+        Jim_Obj *const *keyv, int keyc, Jim_Obj **objPtrPtr, int flags)
+{
+    Jim_Obj *objPtr;
+    int i;
+
+    if (keyc == 0) {
+        *objPtrPtr = dictPtr;
+        return JIM_OK;
+    }
+
+    for (i = 0; i < keyc; i++) {
+        if (Jim_DictKey(interp, dictPtr, keyv[i], &objPtr, flags)
+                != JIM_OK)
+            return JIM_ERR;
+        dictPtr = objPtr;
+    }
+    *objPtrPtr = objPtr;
+    return JIM_OK;
+}
+
+/* Modify the dict stored into the variable named 'varNamePtr'
+ * setting the element specified by the 'keyc' keys objects in 'keyv',
+ * with the new value of the element 'newObjPtr'.
+ *
+ * If newObjPtr == NULL the operation is to remove the given key
+ * from the dictionary. */
+int Jim_SetDictKeysVector(Jim_Interp *interp, Jim_Obj *varNamePtr,
+        Jim_Obj *const *keyv, int keyc, Jim_Obj *newObjPtr)
+{
+    Jim_Obj *varObjPtr, *objPtr, *dictObjPtr;
+    int shared, i;
+
+    varObjPtr = objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
+    if (objPtr == NULL) {
+        if (newObjPtr == NULL) /* Cannot remove a key from non existing var */
+            return JIM_ERR;
+        varObjPtr = objPtr = Jim_NewDictObj(interp, NULL, 0);
+        if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
+            Jim_FreeNewObj(interp, varObjPtr);
+            return JIM_ERR;
+        }
+    }
+    if ((shared = Jim_IsShared(objPtr)))
+        varObjPtr = objPtr = Jim_DuplicateObj(interp, objPtr);
+    for (i = 0; i < keyc-1; i++) {
+        dictObjPtr = objPtr;
+
+        /* Check if it's a valid dictionary */
+        if (dictObjPtr->typePtr != &dictObjType) {
+            if (SetDictFromAny(interp, dictObjPtr) != JIM_OK)
+                goto err;
+        }
+        /* Check if the given key exists. */
+        Jim_InvalidateStringRep(dictObjPtr);
+        if (Jim_DictKey(interp, dictObjPtr, keyv[i], &objPtr,
+            newObjPtr ? JIM_NONE : JIM_ERRMSG) == JIM_OK)
+        {
+            /* This key exists at the current level.
+             * Make sure it's not shared!. */
+            if (Jim_IsShared(objPtr)) {
+                objPtr = Jim_DuplicateObj(interp, objPtr);
+                DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
+            }
+        } else {
+            /* Key not found. If it's an [unset] operation
+             * this is an error. Only the last key may not
+             * exist. */
+            if (newObjPtr == NULL)
+                goto err;
+            /* Otherwise set an empty dictionary
+             * as key's value. */
+            objPtr = Jim_NewDictObj(interp, NULL, 0);
+            DictAddElement(interp, dictObjPtr, keyv[i], objPtr);
+        }
+    }
+    if (Jim_DictAddElement(interp, objPtr, keyv[keyc-1], newObjPtr)
+            != JIM_OK)
+        goto err;
+    Jim_InvalidateStringRep(objPtr);
+    Jim_InvalidateStringRep(varObjPtr);
+    if (Jim_SetVariable(interp, varNamePtr, varObjPtr) != JIM_OK)
+        goto err;
+    Jim_SetResult(interp, varObjPtr);
+    return JIM_OK;
+err:
+    if (shared) {
+        Jim_FreeNewObj(interp, varObjPtr);
+    }
+    return JIM_ERR;
+}
+
+/* -----------------------------------------------------------------------------
+ * Index object
+ * ---------------------------------------------------------------------------*/
+static void UpdateStringOfIndex(struct Jim_Obj *objPtr);
+static int SetIndexFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static Jim_ObjType indexObjType = {
+    "index",
+    NULL,
+    NULL,
+    UpdateStringOfIndex,
+    JIM_TYPE_NONE,
+};
+
+void UpdateStringOfIndex(struct Jim_Obj *objPtr)
+{
+    int len;
+    char buf[JIM_INTEGER_SPACE+1];
+
+    if (objPtr->internalRep.indexValue >= 0)
+        len = sprintf(buf, "%d", objPtr->internalRep.indexValue);
+    else if (objPtr->internalRep.indexValue == -1)
+        len = sprintf(buf, "end");
+    else {
+        len = sprintf(buf, "end%d", objPtr->internalRep.indexValue+1);
+    }
+    objPtr->bytes = Jim_Alloc(len+1);
+    memcpy(objPtr->bytes, buf, len+1);
+    objPtr->length = len;
+}
+
+int SetIndexFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    int index, end = 0;
+    const char *str;
+
+    /* Get the string representation */
+    str = Jim_GetString(objPtr, NULL);
+    /* Try to convert into an index */
+    if (!strcmp(str, "end")) {
+        index = 0;
+        end = 1;
+    } else {
+        if (!strncmp(str, "end-", 4)) {
+            str += 4;
+            end = 1;
+        }
+        if (Jim_StringToIndex(str, &index) != JIM_OK) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                    "bad index \"", Jim_GetString(objPtr, NULL), "\": "
+                    "must be integer or end?-integer?", NULL);
+            return JIM_ERR;
+        }
+    }
+    if (end) {
+        if (index < 0)
+            index = INT_MAX;
+        else
+            index = -(index+1);
+    } else if (!end && index < 0)
+        index = -INT_MAX;
+    /* Free the old internal repr and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &indexObjType;
+    objPtr->internalRep.indexValue = index;
+    return JIM_OK;
+}
+
+int Jim_GetIndex(Jim_Interp *interp, Jim_Obj *objPtr, int *indexPtr)
+{
+    /* Avoid shimmering if the object is an integer. */
+    if (objPtr->typePtr == &intObjType) {
+        jim_wide val = objPtr->internalRep.wideValue;
+        if (!(val < LONG_MIN) && !(val > LONG_MAX)) {
+            *indexPtr = (val < 0) ? -INT_MAX : (long)val;;
+            return JIM_OK;
+        }
+    }
+    if (objPtr->typePtr != &indexObjType &&
+        SetIndexFromAny(interp, objPtr) == JIM_ERR)
+        return JIM_ERR;
+    *indexPtr = objPtr->internalRep.indexValue;
+    return JIM_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Return Code Object.
+ * ---------------------------------------------------------------------------*/
+
+static int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr);
+
+static Jim_ObjType returnCodeObjType = {
+    "return-code",
+    NULL,
+    NULL,
+    NULL,
+    JIM_TYPE_NONE,
+};
+
+int SetReturnCodeFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    const char *str;
+    int strLen, returnCode;
+    jim_wide wideValue;
+
+    /* Get the string representation */
+    str = Jim_GetString(objPtr, &strLen);
+    /* Try to convert into an integer */
+    if (JimGetWideNoErr(interp, objPtr, &wideValue) != JIM_ERR)
+        returnCode = (int) wideValue;
+    else if (!JimStringCompare(str, strLen, "ok", 2, JIM_NOCASE))
+        returnCode = JIM_OK;
+    else if (!JimStringCompare(str, strLen, "error", 5, JIM_NOCASE))
+        returnCode = JIM_ERR;
+    else if (!JimStringCompare(str, strLen, "return", 6, JIM_NOCASE))
+        returnCode = JIM_RETURN;
+    else if (!JimStringCompare(str, strLen, "break", 5, JIM_NOCASE))
+        returnCode = JIM_BREAK;
+    else if (!JimStringCompare(str, strLen, "continue", 8, JIM_NOCASE))
+        returnCode = JIM_CONTINUE;
+    else if (!JimStringCompare(str, strLen, "eval", 4, JIM_NOCASE))
+        returnCode = JIM_EVAL;
+    else if (!JimStringCompare(str, strLen, "exit", 4, JIM_NOCASE))
+        returnCode = JIM_EXIT;
+    else {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "expected return code but got '", str, "'",
+                NULL);
+        return JIM_ERR;
+    }
+    /* Free the old internal repr and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    objPtr->typePtr = &returnCodeObjType;
+    objPtr->internalRep.returnCode = returnCode;
+    return JIM_OK;
+}
+
+int Jim_GetReturnCode(Jim_Interp *interp, Jim_Obj *objPtr, int *intPtr)
+{
+    if (objPtr->typePtr != &returnCodeObjType &&
+        SetReturnCodeFromAny(interp, objPtr) == JIM_ERR)
+        return JIM_ERR;
+    *intPtr = objPtr->internalRep.returnCode;
+    return JIM_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Expression Parsing
+ * ---------------------------------------------------------------------------*/
+static int JimParseExprOperator(struct JimParserCtx *pc);
+static int JimParseExprNumber(struct JimParserCtx *pc);
+static int JimParseExprIrrational(struct JimParserCtx *pc);
+
+/* Exrp's Stack machine operators opcodes. */
+
+/* Binary operators (numbers) */
+#define JIM_EXPROP_BINARY_NUM_FIRST 0 /* first */
+#define JIM_EXPROP_MUL 0
+#define JIM_EXPROP_DIV 1
+#define JIM_EXPROP_MOD 2
+#define JIM_EXPROP_SUB 3
+#define JIM_EXPROP_ADD 4
+#define JIM_EXPROP_LSHIFT 5
+#define JIM_EXPROP_RSHIFT 6
+#define JIM_EXPROP_ROTL 7
+#define JIM_EXPROP_ROTR 8
+#define JIM_EXPROP_LT 9
+#define JIM_EXPROP_GT 10
+#define JIM_EXPROP_LTE 11
+#define JIM_EXPROP_GTE 12
+#define JIM_EXPROP_NUMEQ 13
+#define JIM_EXPROP_NUMNE 14
+#define JIM_EXPROP_BITAND 15
+#define JIM_EXPROP_BITXOR 16
+#define JIM_EXPROP_BITOR 17
+#define JIM_EXPROP_LOGICAND 18
+#define JIM_EXPROP_LOGICOR 19
+#define JIM_EXPROP_LOGICAND_LEFT 20
+#define JIM_EXPROP_LOGICOR_LEFT 21
+#define JIM_EXPROP_POW 22
+#define JIM_EXPROP_BINARY_NUM_LAST 22 /* last */
+
+/* Binary operators (strings) */
+#define JIM_EXPROP_STREQ 23
+#define JIM_EXPROP_STRNE 24
+
+/* Unary operators (numbers) */
+#define JIM_EXPROP_NOT 25
+#define JIM_EXPROP_BITNOT 26
+#define JIM_EXPROP_UNARYMINUS 27
+#define JIM_EXPROP_UNARYPLUS 28
+#define JIM_EXPROP_LOGICAND_RIGHT 29
+#define JIM_EXPROP_LOGICOR_RIGHT 30
+
+/* Ternary operators */
+#define JIM_EXPROP_TERNARY 31
+
+/* Operands */
+#define JIM_EXPROP_NUMBER 32
+#define JIM_EXPROP_COMMAND 33
+#define JIM_EXPROP_VARIABLE 34
+#define JIM_EXPROP_DICTSUGAR 35
+#define JIM_EXPROP_SUBST 36
+#define JIM_EXPROP_STRING 37
+
+/* Operators table */
+typedef struct Jim_ExprOperator {
+    const char *name;
+    int precedence;
+    int arity;
+    int opcode;
+} Jim_ExprOperator;
+
+/* name - precedence - arity - opcode */
+static struct Jim_ExprOperator Jim_ExprOperators[] = {
+    {"!", 300, 1, JIM_EXPROP_NOT},
+    {"~", 300, 1, JIM_EXPROP_BITNOT},
+    {"unarymin", 300, 1, JIM_EXPROP_UNARYMINUS},
+    {"unaryplus", 300, 1, JIM_EXPROP_UNARYPLUS},
+
+    {"**", 250, 2, JIM_EXPROP_POW},
+
+    {"*", 200, 2, JIM_EXPROP_MUL},
+    {"/", 200, 2, JIM_EXPROP_DIV},
+    {"%", 200, 2, JIM_EXPROP_MOD},
+
+    {"-", 100, 2, JIM_EXPROP_SUB},
+    {"+", 100, 2, JIM_EXPROP_ADD},
+
+    {"<<<", 90, 3, JIM_EXPROP_ROTL},
+    {">>>", 90, 3, JIM_EXPROP_ROTR},
+    {"<<", 90, 2, JIM_EXPROP_LSHIFT},
+    {">>", 90, 2, JIM_EXPROP_RSHIFT},
+
+    {"<",  80, 2, JIM_EXPROP_LT},
+    {">",  80, 2, JIM_EXPROP_GT},
+    {"<=", 80, 2, JIM_EXPROP_LTE},
+    {">=", 80, 2, JIM_EXPROP_GTE},
+
+    {"==", 70, 2, JIM_EXPROP_NUMEQ},
+    {"!=", 70, 2, JIM_EXPROP_NUMNE},
+
+    {"eq", 60, 2, JIM_EXPROP_STREQ},
+    {"ne", 60, 2, JIM_EXPROP_STRNE},
+
+    {"&", 50, 2, JIM_EXPROP_BITAND},
+    {"^", 49, 2, JIM_EXPROP_BITXOR},
+    {"|", 48, 2, JIM_EXPROP_BITOR},
+
+    {"&&", 10, 2, JIM_EXPROP_LOGICAND},
+    {"||", 10, 2, JIM_EXPROP_LOGICOR},
+
+    {"?", 5, 3, JIM_EXPROP_TERNARY},
+    /* private operators */
+    {NULL, 10, 2, JIM_EXPROP_LOGICAND_LEFT},
+    {NULL, 10, 1, JIM_EXPROP_LOGICAND_RIGHT},
+    {NULL, 10, 2, JIM_EXPROP_LOGICOR_LEFT},
+    {NULL, 10, 1, JIM_EXPROP_LOGICOR_RIGHT},
+};
+
+#define JIM_EXPR_OPERATORS_NUM \
+    (sizeof(Jim_ExprOperators)/sizeof(struct Jim_ExprOperator))
+
+int JimParseExpression(struct JimParserCtx *pc)
+{
+    /* Discard spaces and quoted newline */
+    while(*(pc->p) == ' ' ||
+          *(pc->p) == '\t' ||
+          *(pc->p) == '\r' ||
+          *(pc->p) == '\n' ||
+            (*(pc->p) == '\\' && *(pc->p+1) == '\n')) {
+        pc->p++; pc->len--;
+    }
+
+    if (pc->len == 0) {
+        pc->tstart = pc->tend = pc->p;
+        pc->tline = pc->linenr;
+        pc->tt = JIM_TT_EOL;
+        pc->eof = 1;
+        return JIM_OK;
+    }
+    switch(*(pc->p)) {
+    case '(':
+        pc->tstart = pc->tend = pc->p;
+        pc->tline = pc->linenr;
+        pc->tt = JIM_TT_SUBEXPR_START;
+        pc->p++; pc->len--;
+        break;
+    case ')':
+        pc->tstart = pc->tend = pc->p;
+        pc->tline = pc->linenr;
+        pc->tt = JIM_TT_SUBEXPR_END;
+        pc->p++; pc->len--;
+        break;
+    case '[':
+        return JimParseCmd(pc);
+        break;
+    case '$':
+        if (JimParseVar(pc) == JIM_ERR)
+            return JimParseExprOperator(pc);
+        else
+            return JIM_OK;
+        break;
+    case '-':
+        if ((pc->tt == JIM_TT_NONE || pc->tt == JIM_TT_EXPR_OPERATOR) &&
+            isdigit((int)*(pc->p+1)))
+            return JimParseExprNumber(pc);
+        else
+            return JimParseExprOperator(pc);
+        break;
+    case '0': case '1': case '2': case '3': case '4':
+    case '5': case '6': case '7': case '8': case '9': case '.':
+        return JimParseExprNumber(pc);
+        break;
+    case '"':
+    case '{':
+        /* Here it's possible to reuse the List String parsing. */
+        pc->tt = JIM_TT_NONE; /* Make sure it's sensed as a new word. */
+        return JimParseListStr(pc);
+        break;
+    case 'N': case 'I':
+    case 'n': case 'i':
+        if (JimParseExprIrrational(pc) == JIM_ERR)
+            return JimParseExprOperator(pc);
+        break;
+    default:
+        return JimParseExprOperator(pc);
+        break;
+    }
+    return JIM_OK;
+}
+
+int JimParseExprNumber(struct JimParserCtx *pc)
+{
+    int allowdot = 1;
+
+    pc->tstart = pc->p;
+    pc->tline = pc->linenr;
+    if (*pc->p == '-') {
+        pc->p++; pc->len--;
+    }
+    while (isdigit((int)*pc->p) || (allowdot && *pc->p == '.') ||
+           (pc->p-pc->tstart == 1 && *pc->tstart == '0' &&
+              (*pc->p == 'x' || *pc->p == 'X')))
+    {
+        if (*pc->p == '.')
+            allowdot = 0;
+        pc->p++; pc->len--;
+        if (!allowdot && *pc->p == 'e' && *(pc->p+1) == '-') {
+            pc->p += 2; pc->len -= 2;
+        }
+    }
+    pc->tend = pc->p-1;
+    pc->tt = JIM_TT_EXPR_NUMBER;
+    return JIM_OK;
+}
+
+int JimParseExprIrrational(struct JimParserCtx *pc)
+{
+    const char *Tokens[] = {"NaN", "nan", "NAN", "Inf", "inf", "INF", NULL};
+    const char **token;
+    for (token = Tokens; *token != NULL; token++) {
+        int len = strlen(*token);
+        if (strncmp(*token, pc->p, len) == 0) {
+            pc->tstart = pc->p;
+            pc->tend = pc->p + len - 1;
+            pc->p += len; pc->len -= len;
+            pc->tline = pc->linenr;
+            pc->tt = JIM_TT_EXPR_NUMBER;
+            return JIM_OK;
+        }
+    }
+    return JIM_ERR;
+}
+
+int JimParseExprOperator(struct JimParserCtx *pc)
+{
+    int i;
+    int bestIdx = -1, bestLen = 0;
+
+    /* Try to get the longest match. */
+    for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++) {
+        const char *opname;
+        int oplen;
+
+        opname = Jim_ExprOperators[i].name;
+        if (opname == NULL) continue;
+        oplen = strlen(opname);
+
+        if (strncmp(opname, pc->p, oplen) == 0 && oplen > bestLen) {
+            bestIdx = i;
+            bestLen = oplen;
+        }
+    }
+    if (bestIdx == -1) return JIM_ERR;
+    pc->tstart = pc->p;
+    pc->tend = pc->p + bestLen - 1;
+    pc->p += bestLen; pc->len -= bestLen;
+    pc->tline = pc->linenr;
+    pc->tt = JIM_TT_EXPR_OPERATOR;
+    return JIM_OK;
+}
+
+struct Jim_ExprOperator *JimExprOperatorInfo(const char *opname)
+{
+    int i;
+    for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++)
+        if (Jim_ExprOperators[i].name &&
+            strcmp(opname, Jim_ExprOperators[i].name) == 0)
+            return &Jim_ExprOperators[i];
+    return NULL;
+}
+
+struct Jim_ExprOperator *JimExprOperatorInfoByOpcode(int opcode)
+{
+    int i;
+    for (i = 0; i < (signed)JIM_EXPR_OPERATORS_NUM; i++)
+        if (Jim_ExprOperators[i].opcode == opcode)
+            return &Jim_ExprOperators[i];
+    return NULL;
+}
+
+/* -----------------------------------------------------------------------------
+ * Expression Object
+ * ---------------------------------------------------------------------------*/
+static void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr);
+
+static Jim_ObjType exprObjType = {
+    "expression",
+    FreeExprInternalRep,
+    DupExprInternalRep,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+/* Expr bytecode structure */
+typedef struct ExprByteCode {
+    int *opcode;        /* Integer array of opcodes. */
+    Jim_Obj **obj;      /* Array of associated Jim Objects. */
+    int len;            /* Bytecode length */
+    int inUse;          /* Used for sharing. */
+} ExprByteCode;
+
+void FreeExprInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    int i;
+    ExprByteCode *expr = (void*) objPtr->internalRep.ptr;
+
+    expr->inUse--;
+    if (expr->inUse != 0) return;
+    for (i = 0; i < expr->len; i++)
+        Jim_DecrRefCount(interp, expr->obj[i]);
+    Jim_Free(expr->opcode);
+    Jim_Free(expr->obj);
+    Jim_Free(expr);
+}
+
+void DupExprInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+    JIM_NOTUSED(interp);
+    JIM_NOTUSED(srcPtr);
+
+    /* Just returns an simple string. */
+    dupPtr->typePtr = NULL;
+}
+
+/* Add a new instruction to an expression bytecode structure. */
+static void ExprObjAddInstr(Jim_Interp *interp, ExprByteCode *expr,
+        int opcode, char *str, int len)
+{
+    expr->opcode = Jim_Realloc(expr->opcode, sizeof(int)*(expr->len+1));
+    expr->obj = Jim_Realloc(expr->obj, sizeof(Jim_Obj*)*(expr->len+1));
+    expr->opcode[expr->len] = opcode;
+    expr->obj[expr->len] = Jim_NewStringObjNoAlloc(interp, str, len);
+    Jim_IncrRefCount(expr->obj[expr->len]);
+    expr->len++;
+}
+
+/* Check if an expr program looks correct. */
+static int ExprCheckCorrectness(ExprByteCode *expr)
+{
+    int i;
+    int stacklen = 0;
+
+    /* Try to check if there are stack underflows,
+     * and make sure at the end of the program there is
+     * a single result on the stack. */
+    for (i = 0; i < expr->len; i++) {
+        switch(expr->opcode[i]) {
+        case JIM_EXPROP_NUMBER:
+        case JIM_EXPROP_STRING:
+        case JIM_EXPROP_SUBST:
+        case JIM_EXPROP_VARIABLE:
+        case JIM_EXPROP_DICTSUGAR:
+        case JIM_EXPROP_COMMAND:
+            stacklen++;
+            break;
+        case JIM_EXPROP_NOT:
+        case JIM_EXPROP_BITNOT:
+        case JIM_EXPROP_UNARYMINUS:
+        case JIM_EXPROP_UNARYPLUS:
+            /* Unary operations */
+            if (stacklen < 1) return JIM_ERR;
+            break;
+        case JIM_EXPROP_ADD:
+        case JIM_EXPROP_SUB:
+        case JIM_EXPROP_MUL:
+        case JIM_EXPROP_DIV:
+        case JIM_EXPROP_MOD:
+        case JIM_EXPROP_LT:
+        case JIM_EXPROP_GT:
+        case JIM_EXPROP_LTE:
+        case JIM_EXPROP_GTE:
+        case JIM_EXPROP_ROTL:
+        case JIM_EXPROP_ROTR:
+        case JIM_EXPROP_LSHIFT:
+        case JIM_EXPROP_RSHIFT:
+        case JIM_EXPROP_NUMEQ:
+        case JIM_EXPROP_NUMNE:
+        case JIM_EXPROP_STREQ:
+        case JIM_EXPROP_STRNE:
+        case JIM_EXPROP_BITAND:
+        case JIM_EXPROP_BITXOR:
+        case JIM_EXPROP_BITOR:
+        case JIM_EXPROP_LOGICAND:
+        case JIM_EXPROP_LOGICOR:
+        case JIM_EXPROP_POW:
+            /* binary operations */
+            if (stacklen < 2) return JIM_ERR;
+            stacklen--;
+            break;
+        default:
+            Jim_Panic(NULL,"Default opcode reached ExprCheckCorrectness");
+            break;
+        }
+    }
+    if (stacklen != 1) return JIM_ERR;
+    return JIM_OK;
+}
+
+static void ExprShareLiterals(Jim_Interp *interp, ExprByteCode *expr,
+        ScriptObj *topLevelScript)
+{
+    int i;
+
+    return;
+    for (i = 0; i < expr->len; i++) {
+        Jim_Obj *foundObjPtr;
+
+        if (expr->obj[i] == NULL) continue;
+        foundObjPtr = ScriptSearchLiteral(interp, topLevelScript,
+                NULL, expr->obj[i]);
+        if (foundObjPtr != NULL) {
+            Jim_IncrRefCount(foundObjPtr);
+            Jim_DecrRefCount(interp, expr->obj[i]);
+            expr->obj[i] = foundObjPtr;
+        }
+    }
+}
+
+/* This procedure converts every occurrence of || and && opereators
+ * in lazy unary versions.
+ *
+ * a b || is converted into:
+ *
+ * a <offset> |L b |R
+ *
+ * a b && is converted into:
+ *
+ * a <offset> &L b &R
+ *
+ * "|L" checks if 'a' is true:
+ *   1) if it is true pushes 1 and skips <offset> istructions to reach
+ *      the opcode just after |R.
+ *   2) if it is false does nothing.
+ * "|R" checks if 'b' is true:
+ *   1) if it is true pushes 1, otherwise pushes 0.
+ *
+ * "&L" checks if 'a' is true:
+ *   1) if it is true does nothing.
+ *   2) If it is false pushes 0 and skips <offset> istructions to reach
+ *      the opcode just after &R
+ * "&R" checks if 'a' is true:
+ *      if it is true pushes 1, otherwise pushes 0.
+ */
+static void ExprMakeLazy(Jim_Interp *interp, ExprByteCode *expr)
+{
+    while (1) {
+        int index = -1, leftindex, arity, i, offset;
+        Jim_ExprOperator *op;
+
+        /* Search for || or && */
+        for (i = 0; i < expr->len; i++) {
+            if (expr->opcode[i] == JIM_EXPROP_LOGICAND ||
+                expr->opcode[i] == JIM_EXPROP_LOGICOR) {
+                index = i;
+                break;
+            }
+        }
+        if (index == -1) return;
+        /* Search for the end of the first operator */
+        leftindex = index-1;
+        arity = 1;
+        while(arity) {
+            switch(expr->opcode[leftindex]) {
+            case JIM_EXPROP_NUMBER:
+            case JIM_EXPROP_COMMAND:
+            case JIM_EXPROP_VARIABLE:
+            case JIM_EXPROP_DICTSUGAR:
+            case JIM_EXPROP_SUBST:
+            case JIM_EXPROP_STRING:
+                break;
+            default:
+                op = JimExprOperatorInfoByOpcode(expr->opcode[i]);
+                if (op == NULL) {
+                    Jim_Panic(interp,"Default reached in ExprMakeLazy()");
+                }
+                arity += op->arity;
+                break;
+            }
+            arity--;
+            leftindex--;
+        }
+        leftindex++;
+        expr->opcode = Jim_Realloc(expr->opcode, sizeof(int)*(expr->len+2));
+        expr->obj = Jim_Realloc(expr->obj, sizeof(Jim_Obj*)*(expr->len+2));
+        memmove(&expr->opcode[leftindex+2], &expr->opcode[leftindex],
+                sizeof(int)*(expr->len-leftindex));
+        memmove(&expr->obj[leftindex+2], &expr->obj[leftindex],
+                sizeof(Jim_Obj*)*(expr->len-leftindex));
+        expr->len += 2;
+        index += 2;
+        offset = (index-leftindex)-1;
+        Jim_DecrRefCount(interp, expr->obj[index]);
+        if (expr->opcode[index] == JIM_EXPROP_LOGICAND) {
+            expr->opcode[leftindex+1] = JIM_EXPROP_LOGICAND_LEFT;
+            expr->opcode[index] = JIM_EXPROP_LOGICAND_RIGHT;
+            expr->obj[leftindex+1] = Jim_NewStringObj(interp, "&L", -1);
+            expr->obj[index] = Jim_NewStringObj(interp, "&R", -1);
+        } else {
+            expr->opcode[leftindex+1] = JIM_EXPROP_LOGICOR_LEFT;
+            expr->opcode[index] = JIM_EXPROP_LOGICOR_RIGHT;
+            expr->obj[leftindex+1] = Jim_NewStringObj(interp, "|L", -1);
+            expr->obj[index] = Jim_NewStringObj(interp, "|R", -1);
+        }
+        expr->opcode[leftindex] = JIM_EXPROP_NUMBER;
+        expr->obj[leftindex] = Jim_NewIntObj(interp, offset);
+        Jim_IncrRefCount(expr->obj[index]);
+        Jim_IncrRefCount(expr->obj[leftindex]);
+        Jim_IncrRefCount(expr->obj[leftindex+1]);
+    }
+}
+
+/* This method takes the string representation of an expression
+ * and generates a program for the Expr's stack-based VM. */
+int SetExprFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr)
+{
+    int exprTextLen;
+    const char *exprText = Jim_GetString(objPtr, &exprTextLen);
+    struct JimParserCtx parser;
+    int i, shareLiterals;
+    ExprByteCode *expr = Jim_Alloc(sizeof(*expr));
+    Jim_Stack stack;
+    Jim_ExprOperator *op;
+
+    /* Perform literal sharing with the current procedure
+     * running only if this expression appears to be not generated
+     * at runtime. */
+    shareLiterals = objPtr->typePtr == &sourceObjType;
+
+    expr->opcode = NULL;
+    expr->obj = NULL;
+    expr->len = 0;
+    expr->inUse = 1;
+
+    Jim_InitStack(&stack);
+    JimParserInit(&parser, exprText, exprTextLen, 1);
+    while(!JimParserEof(&parser)) {
+        char *token;
+        int len, type;
+
+        if (JimParseExpression(&parser) != JIM_OK) {
+            Jim_SetResultString(interp, "Syntax error in expression", -1);
+            goto err;
+        }
+        token = JimParserGetToken(&parser, &len, &type, NULL);
+        if (type == JIM_TT_EOL) {
+            Jim_Free(token);
+            break;
+        }
+        switch(type) {
+        case JIM_TT_STR:
+            ExprObjAddInstr(interp, expr, JIM_EXPROP_STRING, token, len);
+            break;
+        case JIM_TT_ESC:
+            ExprObjAddInstr(interp, expr, JIM_EXPROP_SUBST, token, len);
+            break;
+        case JIM_TT_VAR:
+            ExprObjAddInstr(interp, expr, JIM_EXPROP_VARIABLE, token, len);
+            break;
+        case JIM_TT_DICTSUGAR:
+            ExprObjAddInstr(interp, expr, JIM_EXPROP_DICTSUGAR, token, len);
+            break;
+        case JIM_TT_CMD:
+            ExprObjAddInstr(interp, expr, JIM_EXPROP_COMMAND, token, len);
+            break;
+        case JIM_TT_EXPR_NUMBER:
+            ExprObjAddInstr(interp, expr, JIM_EXPROP_NUMBER, token, len);
+            break;
+        case JIM_TT_EXPR_OPERATOR:
+            op = JimExprOperatorInfo(token);
+            while(1) {
+                Jim_ExprOperator *stackTopOp;
+
+                if (Jim_StackPeek(&stack) != NULL) {
+                    stackTopOp = JimExprOperatorInfo(Jim_StackPeek(&stack));
+                } else {
+                    stackTopOp = NULL;
+                }
+                if (Jim_StackLen(&stack) && op->arity != 1 &&
+                    stackTopOp && stackTopOp->precedence >= op->precedence)
+                {
+                    ExprObjAddInstr(interp, expr, stackTopOp->opcode,
+                        Jim_StackPeek(&stack), -1);
+                    Jim_StackPop(&stack);
+                } else {
+                    break;
+                }
+            }
+            Jim_StackPush(&stack, token);
+            break;
+        case JIM_TT_SUBEXPR_START:
+            Jim_StackPush(&stack, Jim_StrDup("("));
+            Jim_Free(token);
+            break;
+        case JIM_TT_SUBEXPR_END:
+            {
+                int found = 0;
+                while(Jim_StackLen(&stack)) {
+                    char *opstr = Jim_StackPop(&stack);
+                    if (!strcmp(opstr, "(")) {
+                        Jim_Free(opstr);
+                        found = 1;
+                        break;
+                    }
+                    op = JimExprOperatorInfo(opstr);
+                    ExprObjAddInstr(interp, expr, op->opcode, opstr, -1);
+                }
+                if (!found) {
+                    Jim_SetResultString(interp,
+                        "Unexpected close parenthesis", -1);
+                    goto err;
+                }
+            }
+            Jim_Free(token);
+            break;
+        default:
+            Jim_Panic(interp,"Default reached in SetExprFromAny()");
+            break;
+        }
+    }
+    while (Jim_StackLen(&stack)) {
+        char *opstr = Jim_StackPop(&stack);
+        op = JimExprOperatorInfo(opstr);
+        if (op == NULL && !strcmp(opstr, "(")) {
+            Jim_Free(opstr);
+            Jim_SetResultString(interp, "Missing close parenthesis", -1);
+            goto err;
+        }
+        ExprObjAddInstr(interp, expr, op->opcode, opstr, -1);
+    }
+    /* Check program correctness. */
+    if (ExprCheckCorrectness(expr) != JIM_OK) {
+        Jim_SetResultString(interp, "Invalid expression", -1);
+        goto err;
+    }
+
+    /* Free the stack used for the compilation. */
+    Jim_FreeStackElements(&stack, Jim_Free);
+    Jim_FreeStack(&stack);
+
+    /* Convert || and && operators in unary |L |R and &L &R for lazyness */
+    ExprMakeLazy(interp, expr);
+
+    /* Perform literal sharing */
+    if (shareLiterals && interp->framePtr->procBodyObjPtr) {
+        Jim_Obj *bodyObjPtr = interp->framePtr->procBodyObjPtr;
+        if (bodyObjPtr->typePtr == &scriptObjType) {
+            ScriptObj *bodyScript = bodyObjPtr->internalRep.ptr;
+            ExprShareLiterals(interp, expr, bodyScript);
+        }
+    }
+
+    /* Free the old internal rep and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    Jim_SetIntRepPtr(objPtr, expr);
+    objPtr->typePtr = &exprObjType;
+    return JIM_OK;
+
+err:    /* we jump here on syntax/compile errors. */
+    Jim_FreeStackElements(&stack, Jim_Free);
+    Jim_FreeStack(&stack);
+    Jim_Free(expr->opcode);
+    for (i = 0; i < expr->len; i++) {
+        Jim_DecrRefCount(interp,expr->obj[i]);
+    }
+    Jim_Free(expr->obj);
+    Jim_Free(expr);
+    return JIM_ERR;
+}
+
+ExprByteCode *Jim_GetExpression(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    if (objPtr->typePtr != &exprObjType) {
+        if (SetExprFromAny(interp, objPtr) != JIM_OK)
+            return NULL;
+    }
+    return (ExprByteCode*) Jim_GetIntRepPtr(objPtr);
+}
+
+/* -----------------------------------------------------------------------------
+ * Expressions evaluation.
+ * Jim uses a specialized stack-based virtual machine for expressions,
+ * that takes advantage of the fact that expr's operators
+ * can't be redefined.
+ *
+ * Jim_EvalExpression() uses the bytecode compiled by
+ * SetExprFromAny() method of the "expression" object.
+ *
+ * On success a Tcl Object containing the result of the evaluation
+ * is stored into expResultPtrPtr (having refcount of 1), and JIM_OK is
+ * returned.
+ * On error the function returns a retcode != to JIM_OK and set a suitable
+ * error on the interp.
+ * ---------------------------------------------------------------------------*/
+#define JIM_EE_STATICSTACK_LEN 10
+
+int Jim_EvalExpression(Jim_Interp *interp, Jim_Obj *exprObjPtr,
+        Jim_Obj **exprResultPtrPtr)
+{
+    ExprByteCode *expr;
+    Jim_Obj **stack, *staticStack[JIM_EE_STATICSTACK_LEN];
+    int stacklen = 0, i, error = 0, errRetCode = JIM_ERR;
+
+    Jim_IncrRefCount(exprObjPtr);
+    expr = Jim_GetExpression(interp, exprObjPtr);
+    if (!expr) {
+        Jim_DecrRefCount(interp, exprObjPtr);
+        return JIM_ERR; /* error in expression. */
+    }
+    /* In order to avoid that the internal repr gets freed due to
+     * shimmering of the exprObjPtr's object, we make the internal rep
+     * shared. */
+    expr->inUse++;
+
+    /* The stack-based expr VM itself */
+
+    /* Stack allocation. Expr programs have the feature that
+     * a program of length N can't require a stack longer than
+     * N. */
+    if (expr->len > JIM_EE_STATICSTACK_LEN)
+        stack = Jim_Alloc(sizeof(Jim_Obj*)*expr->len);
+    else
+        stack = staticStack;
+
+    /* Execute every istruction */
+    for (i = 0; i < expr->len; i++) {
+        Jim_Obj *A, *B, *objPtr;
+        jim_wide wA, wB, wC;
+        double dA, dB, dC;
+        const char *sA, *sB;
+        int Alen, Blen, retcode;
+        int opcode = expr->opcode[i];
+
+        if (opcode == JIM_EXPROP_NUMBER || opcode == JIM_EXPROP_STRING) {
+            stack[stacklen++] = expr->obj[i];
+            Jim_IncrRefCount(expr->obj[i]);
+        } else if (opcode == JIM_EXPROP_VARIABLE) {
+            objPtr = Jim_GetVariable(interp, expr->obj[i], JIM_ERRMSG);
+            if (objPtr == NULL) {
+                error = 1;
+                goto err;
+            }
+            stack[stacklen++] = objPtr;
+            Jim_IncrRefCount(objPtr);
+        } else if (opcode == JIM_EXPROP_SUBST) {
+            if ((retcode = Jim_SubstObj(interp, expr->obj[i],
+                        &objPtr, JIM_NONE)) != JIM_OK)
+            {
+                error = 1;
+                errRetCode = retcode;
+                goto err;
+            }
+            stack[stacklen++] = objPtr;
+            Jim_IncrRefCount(objPtr);
+        } else if (opcode == JIM_EXPROP_DICTSUGAR) {
+            objPtr = Jim_ExpandDictSugar(interp, expr->obj[i]);
+            if (objPtr == NULL) {
+                error = 1;
+                goto err;
+            }
+            stack[stacklen++] = objPtr;
+            Jim_IncrRefCount(objPtr);
+        } else if (opcode == JIM_EXPROP_COMMAND) {
+            if ((retcode = Jim_EvalObj(interp, expr->obj[i])) != JIM_OK) {
+                error = 1;
+                errRetCode = retcode;
+                goto err;
+            }
+            stack[stacklen++] = interp->result;
+            Jim_IncrRefCount(interp->result);
+        } else if (opcode >= JIM_EXPROP_BINARY_NUM_FIRST &&
+                   opcode <= JIM_EXPROP_BINARY_NUM_LAST)
+        {
+            /* Note that there isn't to increment the
+             * refcount of objects. the references are moved
+             * from stack to A and B. */
+            B = stack[--stacklen];
+            A = stack[--stacklen];
+
+            /* --- Integer --- */
+            if ((A->typePtr == &doubleObjType && !A->bytes) ||
+                (B->typePtr == &doubleObjType && !B->bytes) ||
+                JimGetWideNoErr(interp, A, &wA) != JIM_OK ||
+                JimGetWideNoErr(interp, B, &wB) != JIM_OK) {
+                goto trydouble;
+            }
+            Jim_DecrRefCount(interp, A);
+            Jim_DecrRefCount(interp, B);
+            switch(expr->opcode[i]) {
+            case JIM_EXPROP_ADD: wC = wA+wB; break;
+            case JIM_EXPROP_SUB: wC = wA-wB; break;
+            case JIM_EXPROP_MUL: wC = wA*wB; break;
+            case JIM_EXPROP_LT: wC = wA<wB; break;
+            case JIM_EXPROP_GT: wC = wA>wB; break;
+            case JIM_EXPROP_LTE: wC = wA<=wB; break;
+            case JIM_EXPROP_GTE: wC = wA>=wB; break;
+            case JIM_EXPROP_LSHIFT: wC = wA<<wB; break;
+            case JIM_EXPROP_RSHIFT: wC = wA>>wB; break;
+            case JIM_EXPROP_NUMEQ: wC = wA==wB; break;
+            case JIM_EXPROP_NUMNE: wC = wA!=wB; break;
+            case JIM_EXPROP_BITAND: wC = wA&wB; break;
+            case JIM_EXPROP_BITXOR: wC = wA^wB; break;
+            case JIM_EXPROP_BITOR: wC = wA|wB; break;
+            case JIM_EXPROP_POW: wC = JimPowWide(wA,wB); break;
+            case JIM_EXPROP_LOGICAND_LEFT:
+                if (wA == 0) {
+                    i += (int)wB;
+                    wC = 0;
+                } else {
+                    continue;
+                }
+                break;
+            case JIM_EXPROP_LOGICOR_LEFT:
+                if (wA != 0) {
+                    i += (int)wB;
+                    wC = 1;
+                } else {
+                    continue;
+                }
+                break;
+            case JIM_EXPROP_DIV:
+                if (wB == 0) goto divbyzero;
+                wC = wA/wB;
+                break;
+            case JIM_EXPROP_MOD:
+                if (wB == 0) goto divbyzero;
+                wC = wA%wB;
+                break;
+            case JIM_EXPROP_ROTL: {
+                /* uint32_t would be better. But not everyone has inttypes.h?*/
+                unsigned long uA = (unsigned long)wA;
+#ifdef _MSC_VER
+                wC = _rotl(uA,(unsigned long)wB);
+#else
+                const unsigned int S = sizeof(unsigned long) * 8;
+                wC = (unsigned long)((uA<<wB)|(uA>>(S-wB)));
+#endif
+                break;
+            }
+            case JIM_EXPROP_ROTR: {
+                unsigned long uA = (unsigned long)wA;
+#ifdef _MSC_VER
+                wC = _rotr(uA,(unsigned long)wB);
+#else
+                const unsigned int S = sizeof(unsigned long) * 8;
+                wC = (unsigned long)((uA>>wB)|(uA<<(S-wB)));
+#endif
+                break;
+            }
+
+            default:
+                wC = 0; /* avoid gcc warning */
+                break;
+            }
+            stack[stacklen] = Jim_NewIntObj(interp, wC);
+            Jim_IncrRefCount(stack[stacklen]);
+            stacklen++;
+            continue;
+trydouble:
+            /* --- Double --- */
+            if (Jim_GetDouble(interp, A, &dA) != JIM_OK ||
+                Jim_GetDouble(interp, B, &dB) != JIM_OK) {
+                Jim_DecrRefCount(interp, A);
+                Jim_DecrRefCount(interp, B);
+                error = 1;
+                goto err;
+            }
+            Jim_DecrRefCount(interp, A);
+            Jim_DecrRefCount(interp, B);
+            switch(expr->opcode[i]) {
+            case JIM_EXPROP_ROTL:
+            case JIM_EXPROP_ROTR:
+            case JIM_EXPROP_LSHIFT:
+            case JIM_EXPROP_RSHIFT:
+            case JIM_EXPROP_BITAND:
+            case JIM_EXPROP_BITXOR:
+            case JIM_EXPROP_BITOR:
+            case JIM_EXPROP_MOD:
+            case JIM_EXPROP_POW:
+                Jim_SetResultString(interp,
+                    "Got floating-point value where integer was expected", -1);
+                error = 1;
+                goto err;
+                break;
+            case JIM_EXPROP_ADD: dC = dA+dB; break;
+            case JIM_EXPROP_SUB: dC = dA-dB; break;
+            case JIM_EXPROP_MUL: dC = dA*dB; break;
+            case JIM_EXPROP_LT: dC = dA<dB; break;
+            case JIM_EXPROP_GT: dC = dA>dB; break;
+            case JIM_EXPROP_LTE: dC = dA<=dB; break;
+            case JIM_EXPROP_GTE: dC = dA>=dB; break;
+            case JIM_EXPROP_NUMEQ: dC = dA==dB; break;
+            case JIM_EXPROP_NUMNE: dC = dA!=dB; break;
+            case JIM_EXPROP_LOGICAND_LEFT:
+                if (dA == 0) {
+                    i += (int)dB;
+                    dC = 0;
+                } else {
+                    continue;
+                }
+                break;
+            case JIM_EXPROP_LOGICOR_LEFT:
+                if (dA != 0) {
+                    i += (int)dB;
+                    dC = 1;
+                } else {
+                    continue;
+                }
+                break;
+            case JIM_EXPROP_DIV:
+                if (dB == 0) goto divbyzero;
+                dC = dA/dB;
+                break;
+            default:
+                dC = 0; /* avoid gcc warning */
+                break;
+            }
+            stack[stacklen] = Jim_NewDoubleObj(interp, dC);
+            Jim_IncrRefCount(stack[stacklen]);
+            stacklen++;
+        } else if (opcode == JIM_EXPROP_STREQ || opcode == JIM_EXPROP_STRNE) {
+            B = stack[--stacklen];
+            A = stack[--stacklen];
+            sA = Jim_GetString(A, &Alen);
+            sB = Jim_GetString(B, &Blen);
+            switch(expr->opcode[i]) {
+            case JIM_EXPROP_STREQ:
+                if (Alen == Blen && memcmp(sA, sB, Alen) ==0)
+                    wC = 1;
+                else
+                    wC = 0;
+                break;
+            case JIM_EXPROP_STRNE:
+                if (Alen != Blen || memcmp(sA, sB, Alen) != 0)
+                    wC = 1;
+                else
+                    wC = 0;
+                break;
+            default:
+                wC = 0; /* avoid gcc warning */
+                break;
+            }
+            Jim_DecrRefCount(interp, A);
+            Jim_DecrRefCount(interp, B);
+            stack[stacklen] = Jim_NewIntObj(interp, wC);
+            Jim_IncrRefCount(stack[stacklen]);
+            stacklen++;
+        } else if (opcode == JIM_EXPROP_NOT ||
+                   opcode == JIM_EXPROP_BITNOT ||
+                   opcode == JIM_EXPROP_LOGICAND_RIGHT ||
+                   opcode == JIM_EXPROP_LOGICOR_RIGHT) {
+            /* Note that there isn't to increment the
+             * refcount of objects. the references are moved
+             * from stack to A and B. */
+            A = stack[--stacklen];
+
+            /* --- Integer --- */
+            if ((A->typePtr == &doubleObjType && !A->bytes) ||
+                JimGetWideNoErr(interp, A, &wA) != JIM_OK) {
+                goto trydouble_unary;
+            }
+            Jim_DecrRefCount(interp, A);
+            switch(expr->opcode[i]) {
+            case JIM_EXPROP_NOT: wC = !wA; break;
+            case JIM_EXPROP_BITNOT: wC = ~wA; break;
+            case JIM_EXPROP_LOGICAND_RIGHT:
+            case JIM_EXPROP_LOGICOR_RIGHT: wC = (wA != 0); break;
+            default:
+                wC = 0; /* avoid gcc warning */
+                break;
+            }
+            stack[stacklen] = Jim_NewIntObj(interp, wC);
+            Jim_IncrRefCount(stack[stacklen]);
+            stacklen++;
+            continue;
+trydouble_unary:
+            /* --- Double --- */
+            if (Jim_GetDouble(interp, A, &dA) != JIM_OK) {
+                Jim_DecrRefCount(interp, A);
+                error = 1;
+                goto err;
+            }
+            Jim_DecrRefCount(interp, A);
+            switch(expr->opcode[i]) {
+            case JIM_EXPROP_NOT: dC = !dA; break;
+            case JIM_EXPROP_LOGICAND_RIGHT:
+            case JIM_EXPROP_LOGICOR_RIGHT: dC = (dA != 0); break;
+            case JIM_EXPROP_BITNOT:
+                Jim_SetResultString(interp,
+                    "Got floating-point value where integer was expected", -1);
+                error = 1;
+                goto err;
+                break;
+            default:
+                dC = 0; /* avoid gcc warning */
+                break;
+            }
+            stack[stacklen] = Jim_NewDoubleObj(interp, dC);
+            Jim_IncrRefCount(stack[stacklen]);
+            stacklen++;
+        } else {
+            Jim_Panic(interp,"Unknown opcode in Jim_EvalExpression");
+        }
+    }
+err:
+    /* There is no need to decerement the inUse field because
+     * this reference is transfered back into the exprObjPtr. */
+    Jim_FreeIntRep(interp, exprObjPtr);
+    exprObjPtr->typePtr = &exprObjType;
+    Jim_SetIntRepPtr(exprObjPtr, expr);
+    Jim_DecrRefCount(interp, exprObjPtr);
+    if (!error) {
+        *exprResultPtrPtr = stack[0];
+        Jim_IncrRefCount(stack[0]);
+        errRetCode = JIM_OK;
+    }
+    for (i = 0; i < stacklen; i++) {
+        Jim_DecrRefCount(interp, stack[i]);
+    }
+    if (stack != staticStack)
+        Jim_Free(stack);
+    return errRetCode;
+divbyzero:
+    error = 1;
+    Jim_SetResultString(interp, "Division by zero", -1);
+    goto err;
+}
+
+int Jim_GetBoolFromExpr(Jim_Interp *interp, Jim_Obj *exprObjPtr, int *boolPtr)
+{
+    int retcode;
+    jim_wide wideValue;
+    double doubleValue;
+    Jim_Obj *exprResultPtr;
+
+    retcode = Jim_EvalExpression(interp, exprObjPtr, &exprResultPtr);
+    if (retcode != JIM_OK)
+        return retcode;
+    if (JimGetWideNoErr(interp, exprResultPtr, &wideValue) != JIM_OK) {
+        if (Jim_GetDouble(interp, exprResultPtr, &doubleValue) != JIM_OK)
+        {
+            Jim_DecrRefCount(interp, exprResultPtr);
+            return JIM_ERR;
+        } else {
+            Jim_DecrRefCount(interp, exprResultPtr);
+            *boolPtr = doubleValue != 0;
+            return JIM_OK;
+        }
+    }
+    Jim_DecrRefCount(interp, exprResultPtr);
+    *boolPtr = wideValue != 0;
+    return JIM_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * ScanFormat String Object
+ * ---------------------------------------------------------------------------*/
+
+/* This Jim_Obj will held a parsed representation of a format string passed to
+ * the Jim_ScanString command. For error diagnostics, the scanformat string has
+ * to be parsed in its entirely first and then, if correct, can be used for
+ * scanning. To avoid endless re-parsing, the parsed representation will be
+ * stored in an internal representation and re-used for performance reason. */
+/* A ScanFmtPartDescr will held the information of /one/ part of the whole
+ * scanformat string. This part will later be used to extract information
+ * out from the string to be parsed by Jim_ScanString */
+typedef struct ScanFmtPartDescr {
+    char type;         /* Type of conversion (e.g. c, d, f) */
+    char modifier;     /* Modify type (e.g. l - long, h - short */
+    size_t  width;     /* Maximal width of input to be converted */
+    int  pos;          /* -1 - no assign, 0 - natural pos, >0 - XPG3 pos */ 
+    char *arg;         /* Specification of a CHARSET conversion */
+    char *prefix;      /* Prefix to be scanned literally before conversion */
+} ScanFmtPartDescr;
+
+/* The ScanFmtStringObj will held the internal representation of a scanformat
+ * string parsed and separated in part descriptions. Furthermore it contains
+ * the original string representation of the scanformat string to allow for
+ * fast update of the Jim_Obj's string representation part.
+ *
+ * As add-on the internal object representation add some scratch pad area
+ * for usage by Jim_ScanString to avoid endless allocating and freeing of
+ * memory for purpose of string scanning.
+ *
+ * The error member points to a static allocated string in case of a mal-
+ * formed scanformat string or it contains '0' (NULL) in case of a valid
+ * parse representation.
+ *
+ * The whole memory of the internal representation is allocated as a single
+ * area of memory that will be internally separated. So freeing and duplicating
+ * of such an object is cheap */
+
+typedef struct ScanFmtStringObj {
+    jim_wide        size;         /* Size of internal repr in bytes */
+    char            *stringRep;   /* Original string representation */
+    size_t          count;        /* Number of ScanFmtPartDescr contained */
+    size_t          convCount;    /* Number of conversions that will assign */
+    size_t          maxPos;       /* Max position index if XPG3 is used */
+    const char      *error;       /* Ptr to error text (NULL if no error */
+    char            *scratch;     /* Some scratch pad used by Jim_ScanString */
+    ScanFmtPartDescr descr[1];    /* The vector of partial descriptions */
+} ScanFmtStringObj;
+
+
+static void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr);
+static void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr);
+static void UpdateStringOfScanFmt(Jim_Obj *objPtr);
+
+static Jim_ObjType scanFmtStringObjType = {
+    "scanformatstring",
+    FreeScanFmtInternalRep,
+    DupScanFmtInternalRep,
+    UpdateStringOfScanFmt,
+    JIM_TYPE_NONE,
+};
+
+void FreeScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    JIM_NOTUSED(interp);
+    Jim_Free((char*)objPtr->internalRep.ptr);
+    objPtr->internalRep.ptr = 0;
+}
+
+void DupScanFmtInternalRep(Jim_Interp *interp, Jim_Obj *srcPtr, Jim_Obj *dupPtr)
+{
+    size_t size = (size_t)((ScanFmtStringObj*)srcPtr->internalRep.ptr)->size;
+    ScanFmtStringObj *newVec = (ScanFmtStringObj*)Jim_Alloc(size);
+
+    JIM_NOTUSED(interp);
+    memcpy(newVec, srcPtr->internalRep.ptr, size);
+    dupPtr->internalRep.ptr = newVec;
+    dupPtr->typePtr = &scanFmtStringObjType;
+}
+
+void UpdateStringOfScanFmt(Jim_Obj *objPtr)
+{
+    char *bytes = ((ScanFmtStringObj*)objPtr->internalRep.ptr)->stringRep;
+
+    objPtr->bytes = Jim_StrDup(bytes);
+    objPtr->length = strlen(bytes);
+}
+
+/* SetScanFmtFromAny will parse a given string and create the internal
+ * representation of the format specification. In case of an error
+ * the error data member of the internal representation will be set
+ * to an descriptive error text and the function will be left with
+ * JIM_ERR to indicate unsucessful parsing (aka. malformed scanformat
+ * specification */
+
+static int SetScanFmtFromAny(Jim_Interp *interp, Jim_Obj *objPtr)
+{
+    ScanFmtStringObj *fmtObj;
+    char *buffer;
+    int maxCount, i, approxSize, lastPos = -1;
+    const char *fmt = objPtr->bytes;
+    int maxFmtLen = objPtr->length;
+    const char *fmtEnd = fmt + maxFmtLen;
+    int curr;
+
+    Jim_FreeIntRep(interp, objPtr);
+    /* Count how many conversions could take place maximally */
+    for (i=0, maxCount=0; i < maxFmtLen; ++i)
+        if (fmt[i] == '%')
+            ++maxCount;
+    /* Calculate an approximation of the memory necessary */
+    approxSize = sizeof(ScanFmtStringObj)           /* Size of the container */
+        + (maxCount + 1) * sizeof(ScanFmtPartDescr) /* Size of all partials */
+        + maxFmtLen * sizeof(char) + 3 + 1          /* Scratch + "%n" + '\0' */
+        + maxFmtLen * sizeof(char) + 1              /* Original stringrep */
+        + maxFmtLen * sizeof(char)                  /* Arg for CHARSETs */
+        + (maxCount +1) * sizeof(char)              /* '\0' for every partial */
+        + 1;                                        /* safety byte */
+    fmtObj = (ScanFmtStringObj*)Jim_Alloc(approxSize);
+    memset(fmtObj, 0, approxSize);
+    fmtObj->size = approxSize;
+    fmtObj->maxPos = 0;
+    fmtObj->scratch = (char*)&fmtObj->descr[maxCount+1];
+    fmtObj->stringRep = fmtObj->scratch + maxFmtLen + 3 + 1;
+    memcpy(fmtObj->stringRep, fmt, maxFmtLen);
+    buffer = fmtObj->stringRep + maxFmtLen + 1;
+    objPtr->internalRep.ptr = fmtObj;
+    objPtr->typePtr = &scanFmtStringObjType;
+    for (i=0, curr=0; fmt < fmtEnd; ++fmt) {
+        int width=0, skip;
+        ScanFmtPartDescr *descr = &fmtObj->descr[curr];
+        fmtObj->count++;
+        descr->width = 0;                   /* Assume width unspecified */ 
+        /* Overread and store any "literal" prefix */
+        if (*fmt != '%' || fmt[1] == '%') {
+            descr->type = 0;
+            descr->prefix = &buffer[i];
+            for (; fmt < fmtEnd; ++fmt) {
+                if (*fmt == '%') {
+                    if (fmt[1] != '%') break;
+                    ++fmt;
+                }
+                buffer[i++] = *fmt;
+            }
+            buffer[i++] = 0;
+        } 
+        /* Skip the conversion introducing '%' sign */
+        ++fmt;      
+        /* End reached due to non-conversion literal only? */
+        if (fmt >= fmtEnd)
+            goto done;
+        descr->pos = 0;                     /* Assume "natural" positioning */
+        if (*fmt == '*') {
+            descr->pos = -1;       /* Okay, conversion will not be assigned */
+            ++fmt;
+        } else
+            fmtObj->convCount++;    /* Otherwise count as assign-conversion */
+        /* Check if next token is a number (could be width or pos */
+        if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
+            fmt += skip;
+            /* Was the number a XPG3 position specifier? */
+            if (descr->pos != -1 && *fmt == '$') {
+                int prev;
+                ++fmt;
+                descr->pos = width;
+                width = 0;
+                /* Look if "natural" postioning and XPG3 one was mixed */
+                if ((lastPos == 0 && descr->pos > 0)
+                        || (lastPos > 0 && descr->pos == 0)) {
+                    fmtObj->error = "cannot mix \"%\" and \"%n$\" conversion specifiers";
+                    return JIM_ERR;
+                }
+                /* Look if this position was already used */
+                for (prev=0; prev < curr; ++prev) {
+                    if (fmtObj->descr[prev].pos == -1) continue;
+                    if (fmtObj->descr[prev].pos == descr->pos) {
+                        fmtObj->error = "same \"%n$\" conversion specifier "
+                            "used more than once";
+                        return JIM_ERR;
+                    }
+                }
+                /* Try to find a width after the XPG3 specifier */
+                if (sscanf(fmt, "%d%n", &width, &skip) == 1) {
+                    descr->width = width;
+                    fmt += skip;
+                }
+                if (descr->pos > 0 && (size_t)descr->pos > fmtObj->maxPos)
+                    fmtObj->maxPos = descr->pos;
+            } else {
+                /* Number was not a XPG3, so it has to be a width */
+                descr->width = width;
+            }
+        }
+        /* If positioning mode was undetermined yet, fix this */
+        if (lastPos == -1)
+            lastPos = descr->pos;
+        /* Handle CHARSET conversion type ... */
+        if (*fmt == '[') {
+            int swapped = 1, beg = i, end, j;
+            descr->type = '[';
+            descr->arg = &buffer[i];
+            ++fmt;
+            if (*fmt == '^') buffer[i++] = *fmt++;
+            if (*fmt == ']') buffer[i++] = *fmt++;
+            while (*fmt && *fmt != ']') buffer[i++] = *fmt++;
+            if (*fmt != ']') {
+                fmtObj->error = "unmatched [ in format string";
+                return JIM_ERR;
+            } 
+            end = i;
+            buffer[i++] = 0;
+            /* In case a range fence was given "backwards", swap it */
+            while (swapped) {
+                swapped = 0;
+                for (j=beg+1; j < end-1; ++j) {
+                    if (buffer[j] == '-' && buffer[j-1] > buffer[j+1]) {
+                        char tmp = buffer[j-1];
+                        buffer[j-1] = buffer[j+1];
+                        buffer[j+1] = tmp;
+                        swapped = 1;
+                    }
+                }
+            }
+        } else {
+            /* Remember any valid modifier if given */
+            if (strchr("hlL", *fmt) != 0)
+                descr->modifier = tolower((int)*fmt++);
+            
+            descr->type = *fmt;
+            if (strchr("efgcsndoxui", *fmt) == 0) {
+                fmtObj->error = "bad scan conversion character";
+                return JIM_ERR;
+            } else if (*fmt == 'c' && descr->width != 0) {
+                fmtObj->error = "field width may not be specified in %c "
+                    "conversion";
+                return JIM_ERR;
+            } else if (*fmt == 'u' && descr->modifier == 'l') {
+                fmtObj->error = "unsigned wide not supported";
+                return JIM_ERR;
+            }
+        }
+        curr++;
+    }
+done:
+    if (fmtObj->convCount == 0) {
+        fmtObj->error = "no any conversion specifier given";
+        return JIM_ERR;
+    }
+    return JIM_OK;
+}
+
+/* Some accessor macros to allow lowlevel access to fields of internal repr */
+
+#define FormatGetCnvCount(_fo_) \
+    ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->convCount
+#define FormatGetMaxPos(_fo_) \
+    ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->maxPos
+#define FormatGetError(_fo_) \
+    ((ScanFmtStringObj*)((_fo_)->internalRep.ptr))->error
+
+/* Some Bit testing/setting/cleaning routines. For now only used in handling
+ * charsets ([a-z123]) within scanning. Later on perhaps a base for a 
+ * bitvector implementation in Jim? */ 
+
+static int JimTestBit(const char *bitvec, char ch)
+{
+    div_t pos = div(ch-1, 8);
+    return bitvec[pos.quot] & (1 << pos.rem);
+}
+
+static void JimSetBit(char *bitvec, char ch)
+{
+    div_t pos = div(ch-1, 8);
+    bitvec[pos.quot] |= (1 << pos.rem);
+}
+
+#if 0 /* currently not used */
+static void JimClearBit(char *bitvec, char ch)
+{
+    div_t pos = div(ch-1, 8);
+    bitvec[pos.quot] &= ~(1 << pos.rem);
+}
+#endif
+
+/* JimScanAString is used to scan an unspecified string that ends with
+ * next WS, or a string that is specified via a charset. The charset
+ * is currently implemented in a way to only allow for usage with
+ * ASCII. Whenever we will switch to UNICODE, another idea has to
+ * be born :-/
+ *
+ * FIXME: Works only with ASCII */
+
+static Jim_Obj *
+JimScanAString(Jim_Interp *interp, const char *sdescr, const char *str)
+{
+    size_t i;
+    Jim_Obj *result;
+    char charset[256/8+1];  /* A Charset may contain max 256 chars */
+    char *buffer = Jim_Alloc(strlen(str)+1), *anchor = buffer;
+
+    /* First init charset to nothing or all, depending if a specified
+     * or an unspecified string has to be parsed */
+    memset(charset, (sdescr ? 0 : 255), sizeof(charset));
+    if (sdescr) {
+        /* There was a set description given, that means we are parsing
+         * a specified string. So we have to build a corresponding 
+         * charset reflecting the description */
+        int notFlag = 0;
+        /* Should the set be negated at the end? */
+        if (*sdescr == '^') {
+            notFlag = 1;
+            ++sdescr;
+        }
+        /* Here '-' is meant literally and not to define a range */
+        if (*sdescr == '-') {
+            JimSetBit(charset, '-');
+            ++sdescr;
+        }
+        while (*sdescr) {
+            if (sdescr[1] == '-' && sdescr[2] != 0) {
+                /* Handle range definitions */
+                int i;
+                for (i=sdescr[0]; i <= sdescr[2]; ++i)
+                    JimSetBit(charset, i);
+                sdescr += 3;
+            } else {
+                /* Handle verbatim character definitions */
+                JimSetBit(charset, *sdescr++);
+            }
+        }
+        /* Negate the charset if there was a NOT given */
+        for (i=0; notFlag && i < sizeof(charset); ++i)
+            charset[i] = ~charset[i];
+    } 
+    /* And after all the mess above, the real work begin ... */
+    while (str && *str) {
+        if (!sdescr && isspace((int)*str))
+            break; /* EOS via WS if unspecified */
+        if (JimTestBit(charset, *str)) *buffer++ = *str++;
+        else break;             /* EOS via mismatch if specified scanning */
+    }
+    *buffer = 0;                /* Close the string properly ... */
+    result = Jim_NewStringObj(interp, anchor, -1);
+    Jim_Free(anchor);           /* ... and free it afer usage */
+    return result;
+}
+
+/* ScanOneEntry will scan one entry out of the string passed as argument.
+ * It use the sscanf() function for this task. After extracting and
+ * converting of the value, the count of scanned characters will be
+ * returned of -1 in case of no conversion tool place and string was
+ * already scanned thru */
+
+static int ScanOneEntry(Jim_Interp *interp, const char *str, long pos,
+        ScanFmtStringObj *fmtObj, long index, Jim_Obj **valObjPtr)
+{
+#   define MAX_SIZE (sizeof(jim_wide) > sizeof(double) \
+        ? sizeof(jim_wide)                             \
+        : sizeof(double))
+    char buffer[MAX_SIZE];
+    char *value = buffer;
+    const char *tok;
+    const ScanFmtPartDescr *descr = &fmtObj->descr[index];
+    size_t sLen = strlen(&str[pos]), scanned = 0;
+    size_t anchor = pos;
+    int i;
+
+    /* First pessimiticly assume, we will not scan anything :-) */
+    *valObjPtr = 0;
+    if (descr->prefix) {
+        /* There was a prefix given before the conversion, skip it and adjust
+         * the string-to-be-parsed accordingly */
+        for (i=0; str[pos] && descr->prefix[i]; ++i) {
+            /* If prefix require, skip WS */
+            if (isspace((int)descr->prefix[i]))
+                while (str[pos] && isspace((int)str[pos])) ++pos;
+            else if (descr->prefix[i] != str[pos]) 
+                break;  /* Prefix do not match here, leave the loop */
+            else
+                ++pos;  /* Prefix matched so far, next round */
+        }
+        if (str[pos] == 0)
+            return -1;  /* All of str consumed: EOF condition */
+        else if (descr->prefix[i] != 0)
+            return 0;   /* Not whole prefix consumed, no conversion possible */
+    }
+    /* For all but following conversion, skip leading WS */
+    if (descr->type != 'c' && descr->type != '[' && descr->type != 'n')
+        while (isspace((int)str[pos])) ++pos;
+    /* Determine how much skipped/scanned so far */
+    scanned = pos - anchor;
+    if (descr->type == 'n') {
+        /* Return pseudo conversion means: how much scanned so far? */
+        *valObjPtr = Jim_NewIntObj(interp, anchor + scanned);
+    } else if (str[pos] == 0) {
+        /* Cannot scan anything, as str is totally consumed */
+        return -1;
+    } else {
+        /* Processing of conversions follows ... */
+        if (descr->width > 0) {
+            /* Do not try to scan as fas as possible but only the given width.
+             * To ensure this, we copy the part that should be scanned. */
+            size_t tLen = descr->width > sLen ? sLen : descr->width;
+            tok = Jim_StrDupLen(&str[pos], tLen);
+        } else {
+            /* As no width was given, simply refer to the original string */
+            tok = &str[pos];
+        }
+        switch (descr->type) {
+            case 'c':
+                *valObjPtr = Jim_NewIntObj(interp, *tok);
+                scanned += 1;
+                break;
+            case 'd': case 'o': case 'x': case 'u': case 'i': {
+                char *endp;  /* Position where the number finished */
+                int base = descr->type == 'o' ? 8
+                    : descr->type == 'x' ? 16
+                    : descr->type == 'i' ? 0
+                    : 10;
+                    
+                do {
+                    /* Try to scan a number with the given base */
+                    if (descr->modifier == 'l')
+#ifdef HAVE_LONG_LONG
+                      *(jim_wide*)value = JimStrtoll(tok, &endp, base);
+#else
+                      *(jim_wide*)value = strtol(tok, &endp, base);
+#endif
+                    else
+                      if (descr->type == 'u')
+                        *(long*)value = strtoul(tok, &endp, base);
+                      else
+                        *(long*)value = strtol(tok, &endp, base);
+                    /* If scanning failed, and base was undetermined, simply
+                     * put it to 10 and try once more. This should catch the
+                     * case where %i begin to parse a number prefix (e.g. 
+                     * '0x' but no further digits follows. This will be
+                     * handled as a ZERO followed by a char 'x' by Tcl */
+                    if (endp == tok && base == 0) base = 10;
+                    else break;
+                } while (1);
+                if (endp != tok) {
+                    /* There was some number sucessfully scanned! */
+                    if (descr->modifier == 'l')
+                        *valObjPtr = Jim_NewIntObj(interp, *(jim_wide*)value);
+                    else
+                        *valObjPtr = Jim_NewIntObj(interp, *(long*)value);
+                    /* Adjust the number-of-chars scanned so far */
+                    scanned += endp - tok;
+                } else {
+                    /* Nothing was scanned. We have to determine if this
+                     * happened due to e.g. prefix mismatch or input str
+                     * exhausted */
+                    scanned = *tok ? 0 : -1;
+                }
+                break;
+            }
+            case 's': case '[': {
+                *valObjPtr = JimScanAString(interp, descr->arg, tok);
+                scanned += Jim_Length(*valObjPtr);
+                break;
+            }
+            case 'e': case 'f': case 'g': {
+                char *endp;
+
+                *(double*)value = strtod(tok, &endp);
+                if (endp != tok) {
+                    /* There was some number sucessfully scanned! */
+                    *valObjPtr = Jim_NewDoubleObj(interp, *(double*)value);
+                    /* Adjust the number-of-chars scanned so far */
+                    scanned += endp - tok;
+                } else {
+                    /* Nothing was scanned. We have to determine if this
+                     * happened due to e.g. prefix mismatch or input str
+                     * exhausted */
+                    scanned = *tok ? 0 : -1;
+                }
+                break;
+            }
+        }
+        /* If a substring was allocated (due to pre-defined width) do not
+         * forget to free it */
+        if (tok != &str[pos])
+            Jim_Free((char*)tok);
+    }
+    return scanned;
+}
+
+/* Jim_ScanString is the workhorse of string scanning. It will scan a given
+ * string and returns all converted (and not ignored) values in a list back
+ * to the caller. If an error occured, a NULL pointer will be returned */
+
+Jim_Obj *Jim_ScanString(Jim_Interp *interp, Jim_Obj *strObjPtr,
+        Jim_Obj *fmtObjPtr, int flags)
+{
+    size_t i, pos;
+    int scanned = 1;
+    const char *str = Jim_GetString(strObjPtr, 0);
+    Jim_Obj *resultList = 0;
+    Jim_Obj **resultVec;
+    int resultc;
+    Jim_Obj *emptyStr = 0;
+    ScanFmtStringObj *fmtObj;
+
+    /* If format specification is not an object, convert it! */
+    if (fmtObjPtr->typePtr != &scanFmtStringObjType)
+        SetScanFmtFromAny(interp, fmtObjPtr);
+    fmtObj = (ScanFmtStringObj*)fmtObjPtr->internalRep.ptr;
+    /* Check if format specification was valid */
+    if (fmtObj->error != 0) {
+        if (flags & JIM_ERRMSG)
+            Jim_SetResultString(interp, fmtObj->error, -1);
+        return 0;
+    }
+    /* Allocate a new "shared" empty string for all unassigned conversions */
+    emptyStr = Jim_NewEmptyStringObj(interp);
+    Jim_IncrRefCount(emptyStr);
+    /* Create a list and fill it with empty strings up to max specified XPG3 */
+    resultList = Jim_NewListObj(interp, 0, 0);
+    if (fmtObj->maxPos > 0) {
+        for (i=0; i < fmtObj->maxPos; ++i)
+            Jim_ListAppendElement(interp, resultList, emptyStr);
+        JimListGetElements(interp, resultList, &resultc, &resultVec);
+    }
+    /* Now handle every partial format description */
+    for (i=0, pos=0; i < fmtObj->count; ++i) {
+        ScanFmtPartDescr *descr = &(fmtObj->descr[i]);
+        Jim_Obj *value = 0;
+        /* Only last type may be "literal" w/o conversion - skip it! */
+        if (descr->type == 0) continue;
+        /* As long as any conversion could be done, we will proceed */
+        if (scanned > 0)
+            scanned = ScanOneEntry(interp, str, pos, fmtObj, i, &value);
+        /* In case our first try results in EOF, we will leave */
+        if (scanned == -1 && i == 0)
+            goto eof;
+        /* Advance next pos-to-be-scanned for the amount scanned already */
+        pos += scanned;
+        /* value == 0 means no conversion took place so take empty string */
+        if (value == 0)
+            value = Jim_NewEmptyStringObj(interp);
+        /* If value is a non-assignable one, skip it */
+        if (descr->pos == -1) {
+            Jim_FreeNewObj(interp, value);
+        } else if (descr->pos == 0)
+            /* Otherwise append it to the result list if no XPG3 was given */
+            Jim_ListAppendElement(interp, resultList, value);
+        else if (resultVec[descr->pos-1] == emptyStr) {
+            /* But due to given XPG3, put the value into the corr. slot */
+            Jim_DecrRefCount(interp, resultVec[descr->pos-1]);
+            Jim_IncrRefCount(value);
+            resultVec[descr->pos-1] = value;
+        } else {
+            /* Otherwise, the slot was already used - free obj and ERROR */
+            Jim_FreeNewObj(interp, value);
+            goto err;
+        }
+    }
+    Jim_DecrRefCount(interp, emptyStr);
+    return resultList;
+eof:
+    Jim_DecrRefCount(interp, emptyStr);
+    Jim_FreeNewObj(interp, resultList);
+    return (Jim_Obj*)EOF;
+err:
+    Jim_DecrRefCount(interp, emptyStr);
+    Jim_FreeNewObj(interp, resultList);
+    return 0;
+}
+
+/* -----------------------------------------------------------------------------
+ * Pseudo Random Number Generation
+ * ---------------------------------------------------------------------------*/
+static void JimPrngSeed(Jim_Interp *interp, const unsigned char *seed,
+        int seedLen);
+
+/* Initialize the sbox with the numbers from 0 to 255 */
+static void JimPrngInit(Jim_Interp *interp)
+{
+    int i;
+    unsigned int seed[256];
+
+    interp->prngState = Jim_Alloc(sizeof(Jim_PrngState));
+    for (i = 0; i < 256; i++)
+        seed[i] = (rand() ^ time(NULL) ^ clock());
+    JimPrngSeed(interp, (unsigned char*) seed, sizeof(int)*256);
+}
+
+/* Generates N bytes of random data */
+static void JimRandomBytes(Jim_Interp *interp, void *dest, unsigned int len)
+{
+    Jim_PrngState *prng;
+    unsigned char *destByte = (unsigned char*) dest;
+    unsigned int si, sj, x;
+
+    /* initialization, only needed the first time */
+    if (interp->prngState == NULL)
+        JimPrngInit(interp);
+    prng = interp->prngState;
+    /* generates 'len' bytes of pseudo-random numbers */
+    for (x = 0; x < len; x++) {
+        prng->i = (prng->i+1) & 0xff;
+        si = prng->sbox[prng->i];
+        prng->j = (prng->j + si) & 0xff;
+        sj = prng->sbox[prng->j];
+        prng->sbox[prng->i] = sj;
+        prng->sbox[prng->j] = si;
+        *destByte++ = prng->sbox[(si+sj)&0xff];
+    }
+}
+
+/* Re-seed the generator with user-provided bytes */
+static void JimPrngSeed(Jim_Interp *interp, const unsigned char *seed,
+        int seedLen)
+{
+    int i;
+    unsigned char buf[256];
+    Jim_PrngState *prng;
+
+    /* initialization, only needed the first time */
+    if (interp->prngState == NULL)
+        JimPrngInit(interp);
+    prng = interp->prngState;
+
+    /* Set the sbox[i] with i */
+    for (i = 0; i < 256; i++)
+        prng->sbox[i] = i;
+    /* Now use the seed to perform a random permutation of the sbox */
+    for (i = 0; i < seedLen; i++) {
+        unsigned char t;
+
+        t = prng->sbox[i&0xFF];
+        prng->sbox[i&0xFF] = prng->sbox[seed[i]];
+        prng->sbox[seed[i]] = t;
+    }
+    prng->i = prng->j = 0;
+    /* discard the first 256 bytes of stream. */
+    JimRandomBytes(interp, buf, 256);
+}
+
+/* -----------------------------------------------------------------------------
+ * Dynamic libraries support (WIN32 not supported)
+ * ---------------------------------------------------------------------------*/
+
+#ifdef JIM_DYNLIB
+#ifdef WIN32
+#define RTLD_LAZY 0
+void * dlopen(const char *path, int mode) 
+{
+    JIM_NOTUSED(mode);
+
+    return (void *)LoadLibraryA(path);
+}
+int dlclose(void *handle)
+{
+    FreeLibrary((HANDLE)handle);
+    return 0;
+}
+void *dlsym(void *handle, const char *symbol)
+{
+    return GetProcAddress((HMODULE)handle, symbol);
+}
+static char win32_dlerror_string[121];
+const char *dlerror()
+{
+    FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(),
+                   LANG_NEUTRAL, win32_dlerror_string, 120, NULL);
+    return win32_dlerror_string;
+}
+#endif /* WIN32 */
+
+int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName)
+{
+    Jim_Obj *libPathObjPtr;
+    int prefixc, i;
+    void *handle;
+    int (*onload)(Jim_Interp *interp);
+
+    libPathObjPtr = Jim_GetGlobalVariableStr(interp, "jim_libpath", JIM_NONE);
+    if (libPathObjPtr == NULL) {
+        prefixc = 0;
+        libPathObjPtr = NULL;
+    } else {
+        Jim_IncrRefCount(libPathObjPtr);
+        Jim_ListLength(interp, libPathObjPtr, &prefixc);
+    }
+
+    for (i = -1; i < prefixc; i++) {
+        if (i < 0) {
+            handle = dlopen(pathName, RTLD_LAZY);
+        } else {
+            FILE *fp;
+            char buf[JIM_PATH_LEN];
+            const char *prefix;
+            int prefixlen;
+            Jim_Obj *prefixObjPtr;
+            
+            buf[0] = '\0';
+            if (Jim_ListIndex(interp, libPathObjPtr, i,
+                    &prefixObjPtr, JIM_NONE) != JIM_OK)
+                continue;
+            prefix = Jim_GetString(prefixObjPtr, NULL);
+            prefixlen = strlen(prefix);
+            if (prefixlen+strlen(pathName)+1 >= JIM_PATH_LEN)
+                continue;
+            if (prefixlen && prefix[prefixlen-1] == '/')
+                sprintf(buf, "%s%s", prefix, pathName);
+            else
+                sprintf(buf, "%s/%s", prefix, pathName);
+            fp = fopen(buf, "r");
+            if (fp == NULL)
+                continue;
+            fclose(fp);
+            handle = dlopen(buf, RTLD_LAZY);
+        }
+        if (handle == NULL) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "error loading extension \"", pathName,
+                "\": ", dlerror(), NULL);
+            if (i < 0)
+                continue;
+            goto err;
+        }
+        if ((onload = dlsym(handle, "Jim_OnLoad")) == NULL) {
+            Jim_SetResultString(interp,
+                    "No Jim_OnLoad symbol found on extension", -1);
+            goto err;
+        }
+        if (onload(interp) == JIM_ERR) {
+            dlclose(handle);
+            goto err;
+        }
+        Jim_SetEmptyResult(interp);
+        if (libPathObjPtr != NULL)
+            Jim_DecrRefCount(interp, libPathObjPtr);
+        return JIM_OK;
+    }
+err:
+    if (libPathObjPtr != NULL)
+        Jim_DecrRefCount(interp, libPathObjPtr);
+    return JIM_ERR;
+}
+#else /* JIM_DYNLIB */
+int Jim_LoadLibrary(Jim_Interp *interp, const char *pathName)
+{
+    JIM_NOTUSED(interp);
+    JIM_NOTUSED(pathName);
+
+    Jim_SetResultString(interp, "the Jim binary has no support for [load]", -1);
+    return JIM_ERR;
+}
+#endif/* JIM_DYNLIB */
+
+/* -----------------------------------------------------------------------------
+ * Packages handling
+ * ---------------------------------------------------------------------------*/
+
+#define JIM_PKG_ANY_VERSION -1
+
+/* Convert a string of the type "1.2" into an integer.
+ * MAJOR.MINOR is converted as MAJOR*100+MINOR, so "1.2" is converted 
+ * to the integer with value 102 */
+static int JimPackageVersionToInt(Jim_Interp *interp, const char *v,
+        int *intPtr, int flags)
+{
+    char *copy;
+    jim_wide major, minor;
+    char *majorStr, *minorStr, *p;
+
+    if (v[0] == '\0') {
+        *intPtr = JIM_PKG_ANY_VERSION;
+        return JIM_OK;
+    }
+
+    copy = Jim_StrDup(v);
+    p = strchr(copy, '.');
+    if (p == NULL) goto badfmt;
+    *p = '\0';
+    majorStr = copy;
+    minorStr = p+1;
+
+    if (Jim_StringToWide(majorStr, &major, 10) != JIM_OK ||
+        Jim_StringToWide(minorStr, &minor, 10) != JIM_OK)
+        goto badfmt;
+    *intPtr = (int)(major*100+minor);
+    Jim_Free(copy);
+    return JIM_OK;
+
+badfmt:
+    Jim_Free(copy);
+    if (flags & JIM_ERRMSG) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "invalid package version '", v, "'", NULL);
+    }
+    return JIM_ERR;
+}
+
+#define JIM_MATCHVER_EXACT (1<<JIM_PRIV_FLAG_SHIFT)
+static int JimPackageMatchVersion(int needed, int actual, int flags)
+{
+    if (needed == JIM_PKG_ANY_VERSION) return 1;
+    if (flags & JIM_MATCHVER_EXACT) {
+        return needed == actual;
+    } else {
+        return needed/100 == actual/100 && (needed <= actual);
+    }
+}
+
+int Jim_PackageProvide(Jim_Interp *interp, const char *name, const char *ver,
+        int flags)
+{
+    int intVersion;
+    /* Check if the version format is ok */
+    if (JimPackageVersionToInt(interp, ver, &intVersion, JIM_ERRMSG) != JIM_OK)
+        return JIM_ERR;
+    /* If the package was already provided returns an error. */
+    if (Jim_FindHashEntry(&interp->packages, name) != NULL) {
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                    "package '", name, "' was already provided", NULL);
+        }
+        return JIM_ERR;
+    }
+    Jim_AddHashEntry(&interp->packages, name, (char*) ver);
+    return JIM_OK;
+}
+
+#ifndef JIM_ANSIC
+
+#ifndef WIN32
+# include <sys/types.h>
+# include <dirent.h>
+#else
+# include <io.h>
+/* Posix dirent.h compatiblity layer for WIN32.
+ * Copyright Kevlin Henney, 1997, 2003. All rights reserved.
+ * Copyright Salvatore Sanfilippo ,2005.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose is hereby granted without fee, provided
+ * that this copyright and permissions notice appear in all copies and
+ * derivatives.
+ *
+ * This software is supplied "as is" without express or implied warranty.
+ * This software was modified by Salvatore Sanfilippo for the Jim Interpreter.
+ */
+
+struct dirent {
+    char *d_name;
+};
+
+typedef struct DIR {
+    long                handle; /* -1 for failed rewind */
+    struct _finddata_t  info;
+    struct dirent       result; /* d_name null iff first time */
+    char                *name;  /* null-terminated char string */
+} DIR;
+
+DIR *opendir(const char *name)
+{
+    DIR *dir = 0;
+
+    if(name && name[0]) {
+        size_t base_length = strlen(name);
+        const char *all = /* search pattern must end with suitable wildcard */
+            strchr("/\\", name[base_length - 1]) ? "*" : "/*";
+
+        if((dir = (DIR *) Jim_Alloc(sizeof *dir)) != 0 &&
+           (dir->name = (char *) Jim_Alloc(base_length + strlen(all) + 1)) != 0)
+        {
+            strcat(strcpy(dir->name, name), all);
+
+            if((dir->handle = (long) _findfirst(dir->name, &dir->info)) != -1)
+                dir->result.d_name = 0;
+            else { /* rollback */
+                Jim_Free(dir->name);
+                Jim_Free(dir);
+                dir = 0;
+            }
+        } else { /* rollback */
+            Jim_Free(dir);
+            dir   = 0;
+            errno = ENOMEM;
+        }
+    } else {
+        errno = EINVAL;
+    }
+    return dir;
+}
+
+int closedir(DIR *dir)
+{
+    int result = -1;
+
+    if(dir) {
+        if(dir->handle != -1)
+            result = _findclose(dir->handle);
+        Jim_Free(dir->name);
+        Jim_Free(dir);
+    }
+    if(result == -1) /* map all errors to EBADF */
+        errno = EBADF;
+    return result;
+}
+
+struct dirent *readdir(DIR *dir)
+{
+    struct dirent *result = 0;
+
+    if(dir && dir->handle != -1) {
+        if(!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1) {
+            result         = &dir->result;
+            result->d_name = dir->info.name;
+        }
+    } else {
+        errno = EBADF;
+    }
+    return result;
+}
+
+#endif /* WIN32 */
+
+static char *JimFindBestPackage(Jim_Interp *interp, char **prefixes,
+        int prefixc, const char *pkgName, int pkgVer, int flags)
+{
+    int bestVer = -1, i;
+    int pkgNameLen = strlen(pkgName);
+    char *bestPackage = NULL;
+    struct dirent *de;
+
+    for (i = 0; i < prefixc; i++) {
+        DIR *dir;
+        char buf[JIM_PATH_LEN];
+        int prefixLen;
+
+        if (prefixes[i] == NULL) continue;
+        strncpy(buf, prefixes[i], JIM_PATH_LEN);
+        buf[JIM_PATH_LEN-1] = '\0';
+        prefixLen = strlen(buf);
+        if (prefixLen && buf[prefixLen-1] == '/')
+            buf[prefixLen-1] = '\0';
+
+        if ((dir = opendir(buf)) == NULL) continue;
+        while ((de = readdir(dir)) != NULL) {
+            char *fileName = de->d_name;
+            int fileNameLen = strlen(fileName);
+
+            if (strncmp(fileName, "jim-", 4) == 0 &&
+                strncmp(fileName+4, pkgName, pkgNameLen) == 0 &&
+                *(fileName+4+pkgNameLen) == '-' &&
+                fileNameLen > 4 && /* note that this is not really useful */
+                (strncmp(fileName+fileNameLen-4, ".tcl", 4) == 0 ||
+                 strncmp(fileName+fileNameLen-4, ".dll", 4) == 0 ||
+                 strncmp(fileName+fileNameLen-3, ".so", 3) == 0))
+            {
+                char ver[6]; /* xx.yy<nulterm> */
+                char *p = strrchr(fileName, '.');
+                int verLen, fileVer;
+
+                verLen = p - (fileName+4+pkgNameLen+1);
+                if (verLen < 3 || verLen > 5) continue;
+                memcpy(ver, fileName+4+pkgNameLen+1, verLen);
+                ver[verLen] = '\0';
+                if (JimPackageVersionToInt(interp, ver, &fileVer, JIM_NONE)
+                        != JIM_OK) continue;
+                if (JimPackageMatchVersion(pkgVer, fileVer, flags) &&
+                    (bestVer == -1 || bestVer < fileVer))
+                {
+                    bestVer = fileVer;
+                    Jim_Free(bestPackage);
+                    bestPackage = Jim_Alloc(strlen(buf)+strlen(fileName)+2);
+                    sprintf(bestPackage, "%s/%s", buf, fileName);
+                }
+            }
+        }
+        closedir(dir);
+    }
+    return bestPackage;
+}
+
+#else /* JIM_ANSIC */
+
+static char *JimFindBestPackage(Jim_Interp *interp, char **prefixes,
+        int prefixc, const char *pkgName, int pkgVer, int flags)
+{
+    JIM_NOTUSED(interp);
+    JIM_NOTUSED(prefixes);
+    JIM_NOTUSED(prefixc);
+    JIM_NOTUSED(pkgName);
+    JIM_NOTUSED(pkgVer);
+    JIM_NOTUSED(flags);
+    return NULL;
+}
+
+#endif /* JIM_ANSIC */
+
+/* Search for a suitable package under every dir specified by jim_libpath
+ * and load it if possible. If a suitable package was loaded with success
+ * JIM_OK is returned, otherwise JIM_ERR is returned. */
+static int JimLoadPackage(Jim_Interp *interp, const char *name, int ver,
+        int flags)
+{
+    Jim_Obj *libPathObjPtr;
+    char **prefixes, *best;
+    int prefixc, i, retCode = JIM_OK;
+
+    libPathObjPtr = Jim_GetGlobalVariableStr(interp, "jim_libpath", JIM_NONE);
+    if (libPathObjPtr == NULL) {
+        prefixc = 0;
+        libPathObjPtr = NULL;
+    } else {
+        Jim_IncrRefCount(libPathObjPtr);
+        Jim_ListLength(interp, libPathObjPtr, &prefixc);
+    }
+
+    prefixes = Jim_Alloc(sizeof(char*)*prefixc);
+    for (i = 0; i < prefixc; i++) {
+            Jim_Obj *prefixObjPtr;
+            if (Jim_ListIndex(interp, libPathObjPtr, i,
+                    &prefixObjPtr, JIM_NONE) != JIM_OK)
+            {
+                prefixes[i] = NULL;
+                continue;
+            }
+            prefixes[i] = Jim_StrDup(Jim_GetString(prefixObjPtr, NULL));
+    }
+    /* Scan every directory to find the "best" package. */
+    best = JimFindBestPackage(interp, prefixes, prefixc, name, ver, flags);
+    if (best != NULL) {
+        char *p = strrchr(best, '.');
+        /* Try to load/source it */
+        if (p && strcmp(p, ".tcl") == 0) {
+            retCode = Jim_EvalFile(interp, best);
+        } else {
+            retCode = Jim_LoadLibrary(interp, best);
+        }
+    } else {
+        retCode = JIM_ERR;
+    }
+    Jim_Free(best);
+    for (i = 0; i < prefixc; i++)
+        Jim_Free(prefixes[i]);
+    Jim_Free(prefixes);
+    if (libPathObjPtr)
+        Jim_DecrRefCount(interp, libPathObjPtr);
+    return retCode;
+}
+
+const char *Jim_PackageRequire(Jim_Interp *interp, const char *name,
+        const char *ver, int flags)
+{
+    Jim_HashEntry *he;
+    int requiredVer;
+
+    if (JimPackageVersionToInt(interp, ver, &requiredVer, JIM_ERRMSG) != JIM_OK)
+        return NULL;
+    he = Jim_FindHashEntry(&interp->packages, name);
+    if (he == NULL) {
+        /* Try to load the package. */
+        if (JimLoadPackage(interp, name, requiredVer, flags) == JIM_OK) {
+            he = Jim_FindHashEntry(&interp->packages, name);
+            if (he == NULL) {
+                return "?";
+            }
+            return he->val;
+        }
+        /* No way... return an error. */
+        if (flags & JIM_ERRMSG) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                    "Can't find package '", name, "'", NULL);
+        }
+        return NULL;
+    } else {
+        int actualVer;
+        if (JimPackageVersionToInt(interp, he->val, &actualVer, JIM_ERRMSG)
+                != JIM_OK)
+        {
+            return NULL;
+        }
+        /* Check if version matches. */
+        if (JimPackageMatchVersion(requiredVer, actualVer, flags) == 0) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                    "Package '", name, "' already loaded, but with version ",
+                    he->val, NULL);
+            return NULL;
+        }
+        return he->val;
+    }
+}
+
+/* -----------------------------------------------------------------------------
+ * Eval
+ * ---------------------------------------------------------------------------*/
+#define JIM_EVAL_SARGV_LEN 8 /* static arguments vector length */
+#define JIM_EVAL_SINTV_LEN 8 /* static interpolation vector length */
+
+static int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc,
+        Jim_Obj *const *argv);
+
+/* Handle calls to the [unknown] command */
+static int JimUnknown(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
+{
+    Jim_Obj **v, *sv[JIM_EVAL_SARGV_LEN];
+    int retCode;
+
+    /* If the [unknown] command does not exists returns
+     * just now */
+    if (Jim_GetCommand(interp, interp->unknown, JIM_NONE) == NULL)
+        return JIM_ERR;
+
+    /* The object interp->unknown just contains
+     * the "unknown" string, it is used in order to
+     * avoid to lookup the unknown command every time
+     * but instread to cache the result. */
+    if (argc+1 <= JIM_EVAL_SARGV_LEN)
+        v = sv;
+    else
+        v = Jim_Alloc(sizeof(Jim_Obj*)*(argc+1));
+    /* Make a copy of the arguments vector, but shifted on
+     * the right of one position. The command name of the
+     * command will be instead the first argument of the
+     * [unknonw] call. */
+    memcpy(v+1, argv, sizeof(Jim_Obj*)*argc);
+    v[0] = interp->unknown;
+    /* Call it */
+    retCode = Jim_EvalObjVector(interp, argc+1, v);
+    /* Clean up */
+    if (v != sv)
+        Jim_Free(v);
+    return retCode;
+}
+
+/* Eval the object vector 'objv' composed of 'objc' elements.
+ * Every element is used as single argument.
+ * Jim_EvalObj() will call this function every time its object
+ * argument is of "list" type, with no string representation.
+ *
+ * This is possible because the string representation of a
+ * list object generated by the UpdateStringOfList is made
+ * in a way that ensures that every list element is a different
+ * command argument. */
+int Jim_EvalObjVector(Jim_Interp *interp, int objc, Jim_Obj *const *objv)
+{
+    int i, retcode;
+    Jim_Cmd *cmdPtr;
+
+    /* Incr refcount of arguments. */
+    for (i = 0; i < objc; i++)
+        Jim_IncrRefCount(objv[i]);
+    /* Command lookup */
+    cmdPtr = Jim_GetCommand(interp, objv[0], JIM_ERRMSG);
+    if (cmdPtr == NULL) {
+        retcode = JimUnknown(interp, objc, objv);
+    } else {
+        /* Call it -- Make sure result is an empty object. */
+        Jim_SetEmptyResult(interp);
+        if (cmdPtr->cmdProc) {
+            interp->cmdPrivData = cmdPtr->privData;
+            retcode = cmdPtr->cmdProc(interp, objc, objv);
+        } else {
+            retcode = JimCallProcedure(interp, cmdPtr, objc, objv);
+            if (retcode == JIM_ERR) {
+                JimAppendStackTrace(interp,
+                    Jim_GetString(objv[0], NULL), "?", 1);
+            }
+        }
+    }
+    /* Decr refcount of arguments and return the retcode */
+    for (i = 0; i < objc; i++)
+        Jim_DecrRefCount(interp, objv[i]);
+    return retcode;
+}
+
+/* Interpolate the given tokens into a unique Jim_Obj returned by reference
+ * via *objPtrPtr. This function is only called by Jim_EvalObj().
+ * The returned object has refcount = 0. */
+int Jim_InterpolateTokens(Jim_Interp *interp, ScriptToken *token,
+        int tokens, Jim_Obj **objPtrPtr)
+{
+    int totlen = 0, i, retcode;
+    Jim_Obj **intv;
+    Jim_Obj *sintv[JIM_EVAL_SINTV_LEN];
+    Jim_Obj *objPtr;
+    char *s;
+
+    if (tokens <= JIM_EVAL_SINTV_LEN)
+        intv = sintv;
+    else
+        intv = Jim_Alloc(sizeof(Jim_Obj*)*
+                tokens);
+    /* Compute every token forming the argument
+     * in the intv objects vector. */
+    for (i = 0; i < tokens; i++) {
+        switch(token[i].type) {
+        case JIM_TT_ESC:
+        case JIM_TT_STR:
+            intv[i] = token[i].objPtr;
+            break;
+        case JIM_TT_VAR:
+            intv[i] = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
+            if (!intv[i]) {
+                retcode = JIM_ERR;
+                goto err;
+            }
+            break;
+        case JIM_TT_DICTSUGAR:
+            intv[i] = Jim_ExpandDictSugar(interp, token[i].objPtr);
+            if (!intv[i]) {
+                retcode = JIM_ERR;
+                goto err;
+            }
+            break;
+        case JIM_TT_CMD:
+            retcode = Jim_EvalObj(interp, token[i].objPtr);
+            if (retcode != JIM_OK)
+                goto err;
+            intv[i] = Jim_GetResult(interp);
+            break;
+        default:
+            Jim_Panic(interp,
+              "default token type reached "
+              "in Jim_InterpolateTokens().");
+            break;
+        }
+        Jim_IncrRefCount(intv[i]);
+        /* Make sure there is a valid
+         * string rep, and add the string
+         * length to the total legnth. */
+        Jim_GetString(intv[i], NULL);
+        totlen += intv[i]->length;
+    }
+    /* Concatenate every token in an unique
+     * object. */
+    objPtr = Jim_NewStringObjNoAlloc(interp,
+            NULL, 0);
+    s = objPtr->bytes = Jim_Alloc(totlen+1);
+    objPtr->length = totlen;
+    for (i = 0; i < tokens; i++) {
+        memcpy(s, intv[i]->bytes, intv[i]->length);
+        s += intv[i]->length;
+        Jim_DecrRefCount(interp, intv[i]);
+    }
+    objPtr->bytes[totlen] = '\0';
+    /* Free the intv vector if not static. */
+    if (tokens > JIM_EVAL_SINTV_LEN)
+        Jim_Free(intv);
+    *objPtrPtr = objPtr;
+    return JIM_OK;
+err:
+    i--;
+    for (; i >= 0; i--)
+        Jim_DecrRefCount(interp, intv[i]);
+    if (tokens > JIM_EVAL_SINTV_LEN)
+        Jim_Free(intv);
+    return retcode;
+}
+
+/* Helper of Jim_EvalObj() to perform argument expansion.
+ * Basically this function append an argument to 'argv'
+ * (and increments argc by reference accordingly), performing
+ * expansion of the list object if 'expand' is non-zero, or
+ * just adding objPtr to argv if 'expand' is zero. */
+void Jim_ExpandArgument(Jim_Interp *interp, Jim_Obj ***argv,
+        int *argcPtr, int expand, Jim_Obj *objPtr)
+{
+    if (!expand) {
+        (*argv) = Jim_Realloc(*argv, sizeof(Jim_Obj*)*((*argcPtr)+1));
+        /* refcount of objPtr not incremented because
+         * we are actually transfering a reference from
+         * the old 'argv' to the expanded one. */
+        (*argv)[*argcPtr] = objPtr;
+        (*argcPtr)++;
+    } else {
+        int len, i;
+
+        Jim_ListLength(interp, objPtr, &len);
+        (*argv) = Jim_Realloc(*argv, sizeof(Jim_Obj*)*((*argcPtr)+len));
+        for (i = 0; i < len; i++) {
+            (*argv)[*argcPtr] = objPtr->internalRep.listValue.ele[i];
+            Jim_IncrRefCount(objPtr->internalRep.listValue.ele[i]);
+            (*argcPtr)++;
+        }
+        /* The original object reference is no longer needed,
+         * after the expansion it is no longer present on
+         * the argument vector, but the single elements are
+         * in its place. */
+        Jim_DecrRefCount(interp, objPtr);
+    }
+}
+
+int Jim_EvalObj(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
+{
+    int i, j = 0, len;
+    ScriptObj *script;
+    ScriptToken *token;
+    int *cs; /* command structure array */
+    int retcode = JIM_OK;
+    Jim_Obj *sargv[JIM_EVAL_SARGV_LEN], **argv = NULL, *tmpObjPtr;
+
+    interp->errorFlag = 0;
+
+    /* If the object is of type "list" and there is no
+     * string representation for this object, we can call
+     * a specialized version of Jim_EvalObj() */
+    if (scriptObjPtr->typePtr == &listObjType &&
+        scriptObjPtr->internalRep.listValue.len &&
+        scriptObjPtr->bytes == NULL) {
+        Jim_IncrRefCount(scriptObjPtr);
+        retcode = Jim_EvalObjVector(interp,
+                scriptObjPtr->internalRep.listValue.len,
+                scriptObjPtr->internalRep.listValue.ele);
+        Jim_DecrRefCount(interp, scriptObjPtr);
+        return retcode;
+    }
+
+    Jim_IncrRefCount(scriptObjPtr); /* Make sure it's shared. */
+    script = Jim_GetScript(interp, scriptObjPtr);
+    /* Now we have to make sure the internal repr will not be
+     * freed on shimmering.
+     *
+     * Think for example to this:
+     *
+     * set x {llength $x; ... some more code ...}; eval $x
+     *
+     * In order to preserve the internal rep, we increment the
+     * inUse field of the script internal rep structure. */
+    script->inUse++;
+
+    token = script->token;
+    len = script->len;
+    cs = script->cmdStruct;
+    i = 0; /* 'i' is the current token index. */
+
+    /* Reset the interpreter result. This is useful to
+     * return the emtpy result in the case of empty program. */
+    Jim_SetEmptyResult(interp);
+
+    /* Execute every command sequentially, returns on
+     * error (i.e. if a command does not return JIM_OK) */
+    while (i < len) {
+        int expand = 0;
+        int argc = *cs++; /* Get the number of arguments */
+        Jim_Cmd *cmd;
+
+        /* Set the expand flag if needed. */
+        if (argc == -1) {
+            expand++;
+            argc = *cs++;
+        }
+        /* Allocate the arguments vector */
+        if (argc <= JIM_EVAL_SARGV_LEN)
+            argv = sargv;
+        else
+            argv = Jim_Alloc(sizeof(Jim_Obj*)*argc);
+        /* Populate the arguments objects. */
+        for (j = 0; j < argc; j++) {
+            int tokens = *cs++;
+
+            /* tokens is negative if expansion is needed.
+             * for this argument. */
+            if (tokens < 0) {
+                tokens = (-tokens)-1;
+                i++;
+            }
+            if (tokens == 1) {
+                /* Fast path if the token does not
+                 * need interpolation */
+                switch(token[i].type) {
+                case JIM_TT_ESC:
+                case JIM_TT_STR:
+                    argv[j] = token[i].objPtr;
+                    break;
+                case JIM_TT_VAR:
+                    tmpObjPtr = Jim_GetVariable(interp, token[i].objPtr,
+                            JIM_ERRMSG);
+                    if (!tmpObjPtr) {
+                        retcode = JIM_ERR;
+                        goto err;
+                    }
+                    argv[j] = tmpObjPtr;
+                    break;
+                case JIM_TT_DICTSUGAR:
+                    tmpObjPtr = Jim_ExpandDictSugar(interp, token[i].objPtr);
+                    if (!tmpObjPtr) {
+                        retcode = JIM_ERR;
+                        goto err;
+                    }
+                    argv[j] = tmpObjPtr;
+                    break;
+                case JIM_TT_CMD:
+                    retcode = Jim_EvalObj(interp, token[i].objPtr);
+                    if (retcode != JIM_OK)
+                        goto err;
+                    argv[j] = Jim_GetResult(interp);
+                    break;
+                default:
+                    Jim_Panic(interp,
+                      "default token type reached "
+                      "in Jim_EvalObj().");
+                    break;
+                }
+                Jim_IncrRefCount(argv[j]);
+                i += 2;
+            } else {
+                /* For interpolation we call an helper
+                 * function doing the work for us. */
+                if ((retcode = Jim_InterpolateTokens(interp,
+                        token+i, tokens, &tmpObjPtr)) != JIM_OK)
+                {
+                    goto err;
+                }
+                argv[j] = tmpObjPtr;
+                Jim_IncrRefCount(argv[j]);
+                i += tokens+1;
+            }
+        }
+        /* Handle {expand} expansion */
+        if (expand) {
+            int *ecs = cs - argc;
+            int eargc = 0;
+            Jim_Obj **eargv = NULL;
+
+            for (j = 0; j < argc; j++) {
+                Jim_ExpandArgument( interp, &eargv, &eargc,
+                        ecs[j] < 0, argv[j]);
+            }
+            if (argv != sargv)
+                Jim_Free(argv);
+            argc = eargc;
+            argv = eargv;
+            j = argc;
+            if (argc == 0) {
+                /* Nothing to do with zero args. */
+                Jim_Free(eargv);
+                continue;
+            }
+        }
+        /* Lookup the command to call */
+        cmd = Jim_GetCommand(interp, argv[0], JIM_ERRMSG);
+        if (cmd != NULL) {
+            /* Call it -- Make sure result is an empty object. */
+            Jim_SetEmptyResult(interp);
+            if (cmd->cmdProc) {
+                interp->cmdPrivData = cmd->privData;
+                retcode = cmd->cmdProc(interp, argc, argv);
+            } else {
+                retcode = JimCallProcedure(interp, cmd, argc, argv);
+                if (retcode == JIM_ERR) {
+                    JimAppendStackTrace(interp,
+                        Jim_GetString(argv[0], NULL), script->fileName,
+                        token[i-argc*2].linenr);
+                }
+            }
+        } else {
+            /* Call [unknown] */
+            retcode = JimUnknown(interp, argc, argv);
+        }
+        if (retcode != JIM_OK) {
+            i -= argc*2; /* point to the command name. */
+            goto err;
+        }
+        /* Decrement the arguments count */
+        for (j = 0; j < argc; j++) {
+            Jim_DecrRefCount(interp, argv[j]);
+        }
+
+        if (argv != sargv) {
+            Jim_Free(argv);
+            argv = NULL;
+        }
+    }
+    /* Note that we don't have to decrement inUse, because the
+     * following code transfers our use of the reference again to
+     * the script object. */
+    j = 0; /* on normal termination, the argv array is already
+          Jim_DecrRefCount-ed. */
+err:
+    /* Handle errors. */
+    if (retcode == JIM_ERR && !interp->errorFlag) {
+        interp->errorFlag = 1;
+        JimSetErrorFileName(interp, script->fileName);
+        JimSetErrorLineNumber(interp, token[i].linenr);
+        JimResetStackTrace(interp);
+    }
+    Jim_FreeIntRep(interp, scriptObjPtr);
+    scriptObjPtr->typePtr = &scriptObjType;
+    Jim_SetIntRepPtr(scriptObjPtr, script);
+    Jim_DecrRefCount(interp, scriptObjPtr);
+    for (i = 0; i < j; i++) {
+        Jim_DecrRefCount(interp, argv[i]);
+    }
+    if (argv != sargv)
+        Jim_Free(argv);
+    return retcode;
+}
+
+/* Call a procedure implemented in Tcl.
+ * It's possible to speed-up a lot this function, currently
+ * the callframes are not cached, but allocated and
+ * destroied every time. What is expecially costly is
+ * to create/destroy the local vars hash table every time.
+ *
+ * This can be fixed just implementing callframes caching
+ * in JimCreateCallFrame() and JimFreeCallFrame(). */
+int JimCallProcedure(Jim_Interp *interp, Jim_Cmd *cmd, int argc,
+        Jim_Obj *const *argv)
+{
+    int i, retcode;
+    Jim_CallFrame *callFramePtr;
+
+    /* Check arity */
+    if (argc < cmd->arityMin || (cmd->arityMax != -1 &&
+        argc > cmd->arityMax)) {
+        Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);
+        Jim_AppendStrings(interp, objPtr,
+            "wrong # args: should be \"", Jim_GetString(argv[0], NULL),
+            (cmd->arityMin > 1) ? " " : "",
+            Jim_GetString(cmd->argListObjPtr, NULL), "\"", NULL);
+        Jim_SetResult(interp, objPtr);
+        return JIM_ERR;
+    }
+    /* Check if there are too nested calls */
+    if (interp->numLevels == interp->maxNestingDepth) {
+        Jim_SetResultString(interp,
+            "Too many nested calls. Infinite recursion?", -1);
+        return JIM_ERR;
+    }
+    /* Create a new callframe */
+    callFramePtr = JimCreateCallFrame(interp);
+    callFramePtr->parentCallFrame = interp->framePtr;
+    callFramePtr->argv = argv;
+    callFramePtr->argc = argc;
+    callFramePtr->procArgsObjPtr = cmd->argListObjPtr;
+    callFramePtr->procBodyObjPtr = cmd->bodyObjPtr;
+    callFramePtr->staticVars = cmd->staticVars;
+    Jim_IncrRefCount(cmd->argListObjPtr);
+    Jim_IncrRefCount(cmd->bodyObjPtr);
+    interp->framePtr = callFramePtr;
+    interp->numLevels ++;
+    /* Set arguments */
+    for (i = 0; i < cmd->arityMin-1; i++) {
+        Jim_Obj *objPtr;
+
+        Jim_ListIndex(interp, cmd->argListObjPtr, i, &objPtr, JIM_NONE);
+        Jim_SetVariable(interp, objPtr, argv[i+1]);
+    }
+    if (cmd->arityMax == -1) {
+        Jim_Obj *listObjPtr, *objPtr;
+
+        listObjPtr = Jim_NewListObj(interp, argv+cmd->arityMin,
+                argc-cmd->arityMin);
+        Jim_ListIndex(interp, cmd->argListObjPtr, i, &objPtr, JIM_NONE);
+        Jim_SetVariable(interp, objPtr, listObjPtr);
+    }
+    /* Eval the body */
+    retcode = Jim_EvalObj(interp, cmd->bodyObjPtr);
+
+    /* Destroy the callframe */
+    interp->numLevels --;
+    interp->framePtr = interp->framePtr->parentCallFrame;
+    if (callFramePtr->vars.size != JIM_HT_INITIAL_SIZE) {
+        JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NONE);
+    } else {
+        JimFreeCallFrame(interp, callFramePtr, JIM_FCF_NOHT);
+    }
+    /* Handle the JIM_EVAL return code */
+    if (retcode == JIM_EVAL && interp->evalRetcodeLevel != interp->numLevels) {
+        int savedLevel = interp->evalRetcodeLevel;
+
+        interp->evalRetcodeLevel = interp->numLevels;
+        while (retcode == JIM_EVAL) {
+            Jim_Obj *resultScriptObjPtr = Jim_GetResult(interp);
+            Jim_IncrRefCount(resultScriptObjPtr);
+            retcode = Jim_EvalObj(interp, resultScriptObjPtr);
+            Jim_DecrRefCount(interp, resultScriptObjPtr);
+        }
+        interp->evalRetcodeLevel = savedLevel;
+    }
+    /* Handle the JIM_RETURN return code */
+    if (retcode == JIM_RETURN) {
+        retcode = interp->returnCode;
+        interp->returnCode = JIM_OK;
+    }
+    return retcode;
+}
+
+int Jim_Eval(Jim_Interp *interp, const char *script)
+{
+    Jim_Obj *scriptObjPtr = Jim_NewStringObj(interp, script, -1);
+    int retval;
+
+    Jim_IncrRefCount(scriptObjPtr);
+    retval = Jim_EvalObj(interp, scriptObjPtr);
+    Jim_DecrRefCount(interp, scriptObjPtr);
+    return retval;
+}
+
+/* Execute script in the scope of the global level */
+int Jim_EvalGlobal(Jim_Interp *interp, const char *script)
+{
+    Jim_CallFrame *savedFramePtr;
+    int retval;
+
+    savedFramePtr = interp->framePtr;
+    interp->framePtr = interp->topFramePtr;
+    retval = Jim_Eval(interp, script);
+    interp->framePtr = savedFramePtr;
+    return retval;
+}
+
+int Jim_EvalObjBackground(Jim_Interp *interp, Jim_Obj *scriptObjPtr)
+{
+    Jim_CallFrame *savedFramePtr;
+    int retval;
+
+    savedFramePtr = interp->framePtr;
+    interp->framePtr = interp->topFramePtr;
+    retval = Jim_EvalObj(interp, scriptObjPtr);
+    interp->framePtr = savedFramePtr;
+    /* Try to report the error (if any) via the bgerror proc */
+    if (retval != JIM_OK) {
+        Jim_Obj *objv[2];
+
+        objv[0] = Jim_NewStringObj(interp, "bgerror", -1);
+        objv[1] = Jim_GetResult(interp);
+        Jim_IncrRefCount(objv[0]);
+        Jim_IncrRefCount(objv[1]);
+        if (Jim_EvalObjVector(interp, 2, objv) != JIM_OK) {
+            /* Report the error to stderr. */
+            fprintf(interp->stderr, "Background error:" JIM_NL);
+            Jim_PrintErrorMessage(interp);
+        }
+        Jim_DecrRefCount(interp, objv[0]);
+        Jim_DecrRefCount(interp, objv[1]);
+    }
+    return retval;
+}
+
+int Jim_EvalFile(Jim_Interp *interp, const char *filename)
+{
+    char *prg = NULL;
+    FILE *fp;
+    int nread, totread, maxlen, buflen;
+    int retval;
+    Jim_Obj *scriptObjPtr;
+    
+    if ((fp = fopen(filename, "r")) == NULL) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "Error loading script \"", filename, "\": ",
+            strerror(errno), NULL);
+        return JIM_ERR;
+    }
+    buflen = 1024;
+    maxlen = totread = 0;
+    while (1) {
+        if (maxlen < totread+buflen+1) {
+            maxlen = totread+buflen+1;
+            prg = Jim_Realloc(prg, maxlen);
+        }
+        if ((nread = fread(prg+totread, 1, buflen, fp)) == 0) break;
+        totread += nread;
+    }
+    prg[totread] = '\0';
+    fclose(fp);
+
+    scriptObjPtr = Jim_NewStringObjNoAlloc(interp, prg, totread);
+    JimSetSourceInfo(interp, scriptObjPtr, filename, 1);
+    Jim_IncrRefCount(scriptObjPtr);
+    retval = Jim_EvalObj(interp, scriptObjPtr);
+    Jim_DecrRefCount(interp, scriptObjPtr);
+    return retval;
+}
+
+/* -----------------------------------------------------------------------------
+ * Subst
+ * ---------------------------------------------------------------------------*/
+static int JimParseSubstStr(struct JimParserCtx *pc)
+{
+    pc->tstart = pc->p;
+    pc->tline = pc->linenr;
+    while (*pc->p && *pc->p != '$' && *pc->p != '[') {
+        pc->p++; pc->len--;
+    }
+    pc->tend = pc->p-1;
+    pc->tt = JIM_TT_ESC;
+    return JIM_OK;
+}
+
+static int JimParseSubst(struct JimParserCtx *pc, int flags)
+{
+    int retval;
+
+    if (pc->len == 0) {
+        pc->tstart = pc->tend = pc->p;
+        pc->tline = pc->linenr;
+        pc->tt = JIM_TT_EOL;
+        pc->eof = 1;
+        return JIM_OK;
+    }
+    switch(*pc->p) {
+    case '[':
+        retval = JimParseCmd(pc);
+        if (flags & JIM_SUBST_NOCMD) {
+            pc->tstart--;
+            pc->tend++;
+            pc->tt = (flags & JIM_SUBST_NOESC) ?
+                JIM_TT_STR : JIM_TT_ESC;
+        }
+        return retval;
+        break;
+    case '$':
+        if (JimParseVar(pc) == JIM_ERR) {
+            pc->tstart = pc->tend = pc->p++; pc->len--;
+            pc->tline = pc->linenr;
+            pc->tt = JIM_TT_STR;
+        } else {
+            if (flags & JIM_SUBST_NOVAR) {
+                pc->tstart--;
+                if (flags & JIM_SUBST_NOESC)
+                    pc->tt = JIM_TT_STR;
+                else
+                    pc->tt = JIM_TT_ESC;
+                if (*pc->tstart == '{') {
+                    pc->tstart--;
+                    if (*(pc->tend+1))
+                        pc->tend++;
+                }
+            }
+        }
+        break;
+    default:
+        retval = JimParseSubstStr(pc);
+        if (flags & JIM_SUBST_NOESC)
+            pc->tt = JIM_TT_STR;
+        return retval;
+        break;
+    }
+    return JIM_OK;
+}
+
+/* The subst object type reuses most of the data structures and functions
+ * of the script object. Script's data structures are a bit more complex
+ * for what is needed for [subst]itution tasks, but the reuse helps to
+ * deal with a single data structure at the cost of some more memory
+ * usage for substitutions. */
+static Jim_ObjType substObjType = {
+    "subst",
+    FreeScriptInternalRep,
+    DupScriptInternalRep,
+    NULL,
+    JIM_TYPE_REFERENCES,
+};
+
+/* This method takes the string representation of an object
+ * as a Tcl string where to perform [subst]itution, and generates
+ * the pre-parsed internal representation. */
+int SetSubstFromAny(Jim_Interp *interp, struct Jim_Obj *objPtr, int flags)
+{
+    int scriptTextLen;
+    const char *scriptText = Jim_GetString(objPtr, &scriptTextLen);
+    struct JimParserCtx parser;
+    struct ScriptObj *script = Jim_Alloc(sizeof(*script));
+
+    script->len = 0;
+    script->csLen = 0;
+    script->commands = 0;
+    script->token = NULL;
+    script->cmdStruct = NULL;
+    script->inUse = 1;
+    script->substFlags = flags;
+    script->fileName = NULL;
+
+    JimParserInit(&parser, scriptText, scriptTextLen, 1);
+    while(1) {
+        char *token;
+        int len, type, linenr;
+
+        JimParseSubst(&parser, flags);
+        if (JimParserEof(&parser)) break;
+        token = JimParserGetToken(&parser, &len, &type, &linenr);
+        ScriptObjAddToken(interp, script, token, len, type,
+                NULL, linenr);
+    }
+    /* Free the old internal rep and set the new one. */
+    Jim_FreeIntRep(interp, objPtr);
+    Jim_SetIntRepPtr(objPtr, script);
+    objPtr->typePtr = &scriptObjType;
+    return JIM_OK;
+}
+
+ScriptObj *Jim_GetSubst(Jim_Interp *interp, Jim_Obj *objPtr, int flags)
+{
+    struct ScriptObj *script = Jim_GetIntRepPtr(objPtr);
+
+    if (objPtr->typePtr != &substObjType || script->substFlags != flags)
+        SetSubstFromAny(interp, objPtr, flags);
+    return (ScriptObj*) Jim_GetIntRepPtr(objPtr);
+}
+
+/* Performs commands,variables,blackslashes substitution,
+ * storing the result object (with refcount 0) into
+ * resObjPtrPtr. */
+int Jim_SubstObj(Jim_Interp *interp, Jim_Obj *substObjPtr,
+        Jim_Obj **resObjPtrPtr, int flags)
+{
+    ScriptObj *script;
+    ScriptToken *token;
+    int i, len, retcode = JIM_OK;
+    Jim_Obj *resObjPtr, *savedResultObjPtr;
+
+    script = Jim_GetSubst(interp, substObjPtr, flags);
+#ifdef JIM_OPTIMIZATION
+    /* Fast path for a very common case with array-alike syntax,
+     * that's: $foo($bar) */
+    if (script->len == 1 && script->token[0].type == JIM_TT_VAR) {
+        Jim_Obj *varObjPtr = script->token[0].objPtr;
+        
+        Jim_IncrRefCount(varObjPtr);
+        resObjPtr = Jim_GetVariable(interp, varObjPtr, JIM_ERRMSG);
+        if (resObjPtr == NULL) {
+            Jim_DecrRefCount(interp, varObjPtr);
+            return JIM_ERR;
+        }
+        Jim_DecrRefCount(interp, varObjPtr);
+        *resObjPtrPtr = resObjPtr;
+        return JIM_OK;
+    }
+#endif
+
+    Jim_IncrRefCount(substObjPtr); /* Make sure it's shared. */
+    /* In order to preserve the internal rep, we increment the
+     * inUse field of the script internal rep structure. */
+    script->inUse++;
+
+    token = script->token;
+    len = script->len;
+
+    /* Save the interp old result, to set it again before
+     * to return. */
+    savedResultObjPtr = interp->result;
+    Jim_IncrRefCount(savedResultObjPtr);
+    
+    /* Perform the substitution. Starts with an empty object
+     * and adds every token (performing the appropriate
+     * var/command/escape substitution). */
+    resObjPtr = Jim_NewStringObj(interp, "", 0);
+    for (i = 0; i < len; i++) {
+        Jim_Obj *objPtr;
+
+        switch(token[i].type) {
+        case JIM_TT_STR:
+        case JIM_TT_ESC:
+            Jim_AppendObj(interp, resObjPtr, token[i].objPtr);
+            break;
+        case JIM_TT_VAR:
+            objPtr = Jim_GetVariable(interp, token[i].objPtr, JIM_ERRMSG);
+            if (objPtr == NULL) goto err;
+            Jim_IncrRefCount(objPtr);
+            Jim_AppendObj(interp, resObjPtr, objPtr);
+            Jim_DecrRefCount(interp, objPtr);
+            break;
+        case JIM_TT_CMD:
+            if (Jim_EvalObj(interp, token[i].objPtr) != JIM_OK)
+                goto err;
+            Jim_AppendObj(interp, resObjPtr, interp->result);
+            break;
+        default:
+            Jim_Panic(interp,
+              "default token type (%d) reached "
+              "in Jim_SubstObj().", token[i].type);
+            break;
+        }
+    }
+ok:
+    if (retcode == JIM_OK)
+        Jim_SetResult(interp, savedResultObjPtr);
+    Jim_DecrRefCount(interp, savedResultObjPtr);
+    /* Note that we don't have to decrement inUse, because the
+     * following code transfers our use of the reference again to
+     * the script object. */
+    Jim_FreeIntRep(interp, substObjPtr);
+    substObjPtr->typePtr = &scriptObjType;
+    Jim_SetIntRepPtr(substObjPtr, script);
+    Jim_DecrRefCount(interp, substObjPtr);
+    *resObjPtrPtr = resObjPtr;
+    return retcode;
+err:
+    Jim_FreeNewObj(interp, resObjPtr);
+    retcode = JIM_ERR;
+    goto ok;
+}
+
+/* -----------------------------------------------------------------------------
+ * API Input/Export functions
+ * ---------------------------------------------------------------------------*/
+
+int Jim_GetApi(Jim_Interp *interp, const char *funcname, void *targetPtrPtr)
+{
+    Jim_HashEntry *he;
+
+    he = Jim_FindHashEntry(&interp->stub, funcname);
+    if (!he)
+        return JIM_ERR;
+    memcpy(targetPtrPtr, &he->val, sizeof(void*));
+    return JIM_OK;
+}
+
+int Jim_RegisterApi(Jim_Interp *interp, const char *funcname, void *funcptr)
+{
+    return Jim_AddHashEntry(&interp->stub, funcname, funcptr);
+}
+
+#define JIM_REGISTER_API(name) \
+    Jim_RegisterApi(interp, "Jim_" #name, (void *)Jim_ ## name)
+
+void JimRegisterCoreApi(Jim_Interp *interp)
+{
+  interp->getApiFuncPtr = Jim_GetApi;
+  JIM_REGISTER_API(Alloc);
+  JIM_REGISTER_API(Free);
+  JIM_REGISTER_API(Eval);
+  JIM_REGISTER_API(EvalGlobal);
+  JIM_REGISTER_API(EvalFile);
+  JIM_REGISTER_API(EvalObj);
+  JIM_REGISTER_API(EvalObjBackground);
+  JIM_REGISTER_API(EvalObjVector);
+  JIM_REGISTER_API(InitHashTable);
+  JIM_REGISTER_API(ExpandHashTable);
+  JIM_REGISTER_API(AddHashEntry);
+  JIM_REGISTER_API(ReplaceHashEntry);
+  JIM_REGISTER_API(DeleteHashEntry);
+  JIM_REGISTER_API(FreeHashTable);
+  JIM_REGISTER_API(FindHashEntry);
+  JIM_REGISTER_API(ResizeHashTable);
+  JIM_REGISTER_API(GetHashTableIterator);
+  JIM_REGISTER_API(NextHashEntry);
+  JIM_REGISTER_API(NewObj);
+  JIM_REGISTER_API(FreeObj);
+  JIM_REGISTER_API(InvalidateStringRep);
+  JIM_REGISTER_API(InitStringRep);
+  JIM_REGISTER_API(DuplicateObj);
+  JIM_REGISTER_API(GetString);
+  JIM_REGISTER_API(Length);
+  JIM_REGISTER_API(InvalidateStringRep);
+  JIM_REGISTER_API(NewStringObj);
+  JIM_REGISTER_API(NewStringObjNoAlloc);
+  JIM_REGISTER_API(AppendString);
+  JIM_REGISTER_API(AppendObj);
+  JIM_REGISTER_API(AppendStrings);
+  JIM_REGISTER_API(StringEqObj);
+  JIM_REGISTER_API(StringMatchObj);
+  JIM_REGISTER_API(StringRangeObj);
+  JIM_REGISTER_API(FormatString);
+  JIM_REGISTER_API(CompareStringImmediate);
+  JIM_REGISTER_API(NewReference);
+  JIM_REGISTER_API(GetReference);
+  JIM_REGISTER_API(SetFinalizer);
+  JIM_REGISTER_API(GetFinalizer);
+  JIM_REGISTER_API(CreateInterp);
+  JIM_REGISTER_API(FreeInterp);
+  JIM_REGISTER_API(GetExitCode);
+  JIM_REGISTER_API(SetStdin);
+  JIM_REGISTER_API(SetStdout);
+  JIM_REGISTER_API(SetStderr);
+  JIM_REGISTER_API(CreateCommand);
+  JIM_REGISTER_API(CreateProcedure);
+  JIM_REGISTER_API(DeleteCommand);
+  JIM_REGISTER_API(RenameCommand);
+  JIM_REGISTER_API(GetCommand);
+  JIM_REGISTER_API(SetVariable);
+  JIM_REGISTER_API(SetVariableStr);
+  JIM_REGISTER_API(SetGlobalVariableStr);
+  JIM_REGISTER_API(SetVariableStrWithStr);
+  JIM_REGISTER_API(SetVariableLink);
+  JIM_REGISTER_API(GetVariable);
+  JIM_REGISTER_API(GetCallFrameByLevel);
+  JIM_REGISTER_API(Collect);
+  JIM_REGISTER_API(CollectIfNeeded);
+  JIM_REGISTER_API(GetIndex);
+  JIM_REGISTER_API(NewListObj);
+  JIM_REGISTER_API(ListAppendElement);
+  JIM_REGISTER_API(ListAppendList);
+  JIM_REGISTER_API(ListLength);
+  JIM_REGISTER_API(ListIndex);
+  JIM_REGISTER_API(SetListIndex);
+  JIM_REGISTER_API(ConcatObj);
+  JIM_REGISTER_API(NewDictObj);
+  JIM_REGISTER_API(DictKey);
+  JIM_REGISTER_API(DictKeysVector);
+  JIM_REGISTER_API(GetIndex);
+  JIM_REGISTER_API(GetReturnCode);
+  JIM_REGISTER_API(EvalExpression);
+  JIM_REGISTER_API(GetBoolFromExpr);
+  JIM_REGISTER_API(GetWide);
+  JIM_REGISTER_API(GetLong);
+  JIM_REGISTER_API(SetWide);
+  JIM_REGISTER_API(NewIntObj);
+  JIM_REGISTER_API(GetDouble);
+  JIM_REGISTER_API(SetDouble);
+  JIM_REGISTER_API(NewDoubleObj);
+  JIM_REGISTER_API(WrongNumArgs);
+  JIM_REGISTER_API(SetDictKeysVector);
+  JIM_REGISTER_API(SubstObj);
+  JIM_REGISTER_API(RegisterApi);
+  JIM_REGISTER_API(PrintErrorMessage);
+  JIM_REGISTER_API(InteractivePrompt);
+  JIM_REGISTER_API(RegisterCoreCommands);
+  JIM_REGISTER_API(GetSharedString);
+  JIM_REGISTER_API(ReleaseSharedString);
+  JIM_REGISTER_API(Panic);
+  JIM_REGISTER_API(StrDup);
+  JIM_REGISTER_API(UnsetVariable);
+  JIM_REGISTER_API(GetVariableStr);
+  JIM_REGISTER_API(GetGlobalVariable);
+  JIM_REGISTER_API(GetGlobalVariableStr);
+  JIM_REGISTER_API(GetAssocData);
+  JIM_REGISTER_API(SetAssocData);
+  JIM_REGISTER_API(DeleteAssocData);
+  JIM_REGISTER_API(GetEnum);
+  JIM_REGISTER_API(ScriptIsComplete);
+  JIM_REGISTER_API(PackageRequire);
+  JIM_REGISTER_API(PackageProvide);
+  JIM_REGISTER_API(InitStack);
+  JIM_REGISTER_API(FreeStack);
+  JIM_REGISTER_API(StackLen);
+  JIM_REGISTER_API(StackPush);
+  JIM_REGISTER_API(StackPop);
+  JIM_REGISTER_API(StackPeek);
+  JIM_REGISTER_API(FreeStackElements);
+}
+
+/* -----------------------------------------------------------------------------
+ * Core commands utility functions
+ * ---------------------------------------------------------------------------*/
+void Jim_WrongNumArgs(Jim_Interp *interp, int argc, Jim_Obj *const *argv, 
+        const char *msg)
+{
+    int i;
+    Jim_Obj *objPtr = Jim_NewEmptyStringObj(interp);
+
+    Jim_AppendString(interp, objPtr, "wrong # args: should be \"", -1);
+    for (i = 0; i < argc; i++) {
+        Jim_AppendObj(interp, objPtr, argv[i]);
+        if (!(i+1 == argc && msg[0] == '\0'))
+            Jim_AppendString(interp, objPtr, " ", 1);
+    }
+    Jim_AppendString(interp, objPtr, msg, -1);
+    Jim_AppendString(interp, objPtr, "\"", 1);
+    Jim_SetResult(interp, objPtr);
+}
+
+static Jim_Obj *JimCommandsList(Jim_Interp *interp, Jim_Obj *patternObjPtr)
+{
+    Jim_HashTableIterator *htiter;
+    Jim_HashEntry *he;
+    Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+    const char *pattern;
+    int patternLen;
+    
+    pattern = patternObjPtr ? Jim_GetString(patternObjPtr, &patternLen) : NULL;
+    htiter = Jim_GetHashTableIterator(&interp->commands);
+    while ((he = Jim_NextHashEntry(htiter)) != NULL) {
+        if (pattern && !JimStringMatch(pattern, patternLen, he->key, 
+                    strlen((const char*)he->key), 0))
+            continue;
+        Jim_ListAppendElement(interp, listObjPtr,
+                Jim_NewStringObj(interp, he->key, -1));
+    }
+    Jim_FreeHashTableIterator(htiter);
+    return listObjPtr;
+}
+
+#define JIM_VARLIST_GLOBALS 0
+#define JIM_VARLIST_LOCALS 1
+#define JIM_VARLIST_VARS 2
+
+static Jim_Obj *JimVariablesList(Jim_Interp *interp, Jim_Obj *patternObjPtr,
+        int mode)
+{
+    Jim_HashTableIterator *htiter;
+    Jim_HashEntry *he;
+    Jim_Obj *listObjPtr = Jim_NewListObj(interp, NULL, 0);
+    const char *pattern;
+    int patternLen;
+    
+    pattern = patternObjPtr ? Jim_GetString(patternObjPtr, &patternLen) : NULL;
+    if (mode == JIM_VARLIST_GLOBALS) {
+        htiter = Jim_GetHashTableIterator(&interp->topFramePtr->vars);
+    } else {
+        /* For [info locals], if we are at top level an emtpy list
+         * is returned. I don't agree, but we aim at compatibility (SS) */
+        if (mode == JIM_VARLIST_LOCALS &&
+            interp->framePtr == interp->topFramePtr)
+            return listObjPtr;
+        htiter = Jim_GetHashTableIterator(&interp->framePtr->vars);
+    }
+    while ((he = Jim_NextHashEntry(htiter)) != NULL) {
+        Jim_Var *varPtr = (Jim_Var*) he->val;
+        if (mode == JIM_VARLIST_LOCALS) {
+            if (varPtr->linkFramePtr != NULL)
+                continue;
+        }
+        if (pattern && !JimStringMatch(pattern, patternLen, he->key, 
+                    strlen((const char*)he->key), 0))
+            continue;
+        Jim_ListAppendElement(interp, listObjPtr,
+                Jim_NewStringObj(interp, he->key, -1));
+    }
+    Jim_FreeHashTableIterator(htiter);
+    return listObjPtr;
+}
+
+static int JimInfoLevel(Jim_Interp *interp, Jim_Obj *levelObjPtr,
+        Jim_Obj **objPtrPtr)
+{
+    Jim_CallFrame *targetCallFrame;
+
+    if (JimGetCallFrameByInteger(interp, levelObjPtr, &targetCallFrame)
+            != JIM_OK)
+        return JIM_ERR;
+    /* No proc call at toplevel callframe */
+    if (targetCallFrame == interp->topFramePtr) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "bad level \"",
+                Jim_GetString(levelObjPtr, NULL), "\"", NULL);
+        return JIM_ERR;
+    }
+    *objPtrPtr = Jim_NewListObj(interp,
+            targetCallFrame->argv,
+            targetCallFrame->argc);
+    return JIM_OK;
+}
+
+/* -----------------------------------------------------------------------------
+ * Core commands
+ * ---------------------------------------------------------------------------*/
+
+/* fake [puts] -- not the real puts, just for debugging. */
+static int Jim_PutsCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    const char *str;
+    int len, nonewline = 0;
+    
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "-nonewline string");
+        return JIM_ERR;
+    }
+    if (argc == 3) {
+        if (!Jim_CompareStringImmediate(interp, argv[1], "-nonewline"))
+        {
+            Jim_SetResultString(interp, "The second argument must "
+                    "be -nonewline", -1);
+            return JIM_OK;
+        } else {
+            nonewline = 1;
+            argv++;
+        }
+    }
+    str = Jim_GetString(argv[1], &len);
+    fwrite(str, 1, len, interp->stdout);
+    if (!nonewline) fprintf(interp->stdout, JIM_NL);
+    return JIM_OK;
+}
+
+/* Helper for [+] and [*] */
+static int Jim_AddMulHelper(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv, int op)
+{
+    jim_wide wideValue, res;
+    double doubleValue, doubleRes;
+    int i;
+
+    res = (op == JIM_EXPROP_ADD) ? 0 : 1;
+    
+    for (i = 1; i < argc; i++) {
+        if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK)
+            goto trydouble;
+        if (op == JIM_EXPROP_ADD)
+            res += wideValue;
+        else
+            res *= wideValue;
+    }
+    Jim_SetResult(interp, Jim_NewIntObj(interp, res));
+    return JIM_OK;
+trydouble:
+    doubleRes = (double) res;
+    for (;i < argc; i++) {
+        if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
+            return JIM_ERR;
+        if (op == JIM_EXPROP_ADD)
+            doubleRes += doubleValue;
+        else
+            doubleRes *= doubleValue;
+    }
+    Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+    return JIM_OK;
+}
+
+/* Helper for [-] and [/] */
+static int Jim_SubDivHelper(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv, int op)
+{
+    jim_wide wideValue, res = 0;
+    double doubleValue, doubleRes = 0;
+    int i = 2;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "number ?number ... number?");
+        return JIM_ERR;
+    } else if (argc == 2) {
+        /* The arity = 2 case is different. For [- x] returns -x,
+         * while [/ x] returns 1/x. */
+        if (Jim_GetWide(interp, argv[1], &wideValue) != JIM_OK) {
+            if (Jim_GetDouble(interp, argv[1], &doubleValue) !=
+                    JIM_OK)
+            {
+                return JIM_ERR;
+            } else {
+                if (op == JIM_EXPROP_SUB)
+                    doubleRes = -doubleValue;
+                else
+                    doubleRes = 1.0/doubleValue;
+                Jim_SetResult(interp, Jim_NewDoubleObj(interp,
+                            doubleRes));
+                return JIM_OK;
+            }
+        }
+        if (op == JIM_EXPROP_SUB) {
+            res = -wideValue;
+            Jim_SetResult(interp, Jim_NewIntObj(interp, res));
+        } else {
+            doubleRes = 1.0/wideValue;
+            Jim_SetResult(interp, Jim_NewDoubleObj(interp,
+                        doubleRes));
+        }
+        return JIM_OK;
+    } else {
+        if (Jim_GetWide(interp, argv[1], &res) != JIM_OK) {
+            if (Jim_GetDouble(interp, argv[1], &doubleRes)
+                    != JIM_OK) {
+                return JIM_ERR;
+            } else {
+                goto trydouble;
+            }
+        }
+    }
+    for (i = 2; i < argc; i++) {
+        if (Jim_GetWide(interp, argv[i], &wideValue) != JIM_OK) {
+            doubleRes = (double) res;
+            goto trydouble;
+        }
+        if (op == JIM_EXPROP_SUB)
+            res -= wideValue;
+        else
+            res /= wideValue;
+    }
+    Jim_SetResult(interp, Jim_NewIntObj(interp, res));
+    return JIM_OK;
+trydouble:
+    for (;i < argc; i++) {
+        if (Jim_GetDouble(interp, argv[i], &doubleValue) != JIM_OK)
+            return JIM_ERR;
+        if (op == JIM_EXPROP_SUB)
+            doubleRes -= doubleValue;
+        else
+            doubleRes /= doubleValue;
+    }
+    Jim_SetResult(interp, Jim_NewDoubleObj(interp, doubleRes));
+    return JIM_OK;
+}
+
+
+/* [+] */
+static int Jim_AddCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    return Jim_AddMulHelper(interp, argc, argv, JIM_EXPROP_ADD);
+}
+
+/* [*] */
+static int Jim_MulCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    return Jim_AddMulHelper(interp, argc, argv, JIM_EXPROP_MUL);
+}
+
+/* [-] */
+static int Jim_SubCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    return Jim_SubDivHelper(interp, argc, argv, JIM_EXPROP_SUB);
+}
+
+/* [/] */
+static int Jim_DivCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    return Jim_SubDivHelper(interp, argc, argv, JIM_EXPROP_DIV);
+}
+
+/* [set] */
+static int Jim_SetCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "varName ?newValue?");
+        return JIM_ERR;
+    }
+    if (argc == 2) {
+        Jim_Obj *objPtr;
+        objPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+        if (!objPtr)
+            return JIM_ERR;
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    }
+    /* argc == 3 case. */
+    if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
+        return JIM_ERR;
+    Jim_SetResult(interp, argv[2]);
+    return JIM_OK;
+}
+
+/* [unset] */
+static int Jim_UnsetCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int i;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
+        return JIM_ERR;
+    }
+    for (i = 1; i < argc; i++) {
+        if (Jim_UnsetVariable(interp, argv[i], JIM_ERRMSG) != JIM_OK)
+            return JIM_ERR;
+    }
+    return JIM_OK;
+}
+
+/* [incr] */
+static int Jim_IncrCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    jim_wide wideValue, increment = 1;
+    Jim_Obj *intObjPtr;
+
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "varName ?increment?");
+        return JIM_ERR;
+    }
+    if (argc == 3) {
+        if (Jim_GetWide(interp, argv[2], &increment) != JIM_OK)
+            return JIM_ERR;
+    }
+    intObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+    if (!intObjPtr) return JIM_ERR;
+    if (Jim_GetWide(interp, intObjPtr, &wideValue) != JIM_OK)
+        return JIM_ERR;
+    if (Jim_IsShared(intObjPtr)) {
+        intObjPtr = Jim_NewIntObj(interp, wideValue+increment);
+        if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
+            Jim_FreeNewObj(interp, intObjPtr);
+            return JIM_ERR;
+        }
+    } else {
+        Jim_SetWide(interp, intObjPtr, wideValue+increment);
+        /* The following step is required in order to invalidate the
+         * string repr of "FOO" if the var name is on the form of "FOO(IDX)" */
+        if (Jim_SetVariable(interp, argv[1], intObjPtr) != JIM_OK) {
+            return JIM_ERR;
+        }
+    }
+    Jim_SetResult(interp, intObjPtr);
+    return JIM_OK;
+}
+
+/* [while] */
+static int Jim_WhileCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "condition body");
+        return JIM_ERR;
+    }
+    /* Try to run a specialized version of while if the expression
+     * is in one of the following forms:
+     *
+     *   $a < CONST, $a < $b
+     *   $a <= CONST, $a <= $b
+     *   $a > CONST, $a > $b
+     *   $a >= CONST, $a >= $b
+     *   $a != CONST, $a != $b
+     *   $a == CONST, $a == $b
+     *   $a
+     *   !$a
+     *   CONST
+     */
+
+#ifdef JIM_OPTIMIZATION
+    {
+        ExprByteCode *expr;
+        Jim_Obj *varAObjPtr = NULL, *varBObjPtr = NULL, *objPtr;
+        int exprLen, retval;
+
+        /* STEP 1 -- Check if there are the conditions to run the specialized
+         * version of while */
+        
+        if ((expr = Jim_GetExpression(interp, argv[1])) == NULL) goto noopt;
+        if (expr->len <= 0 || expr->len > 3) goto noopt;
+        switch(expr->len) {
+        case 1:
+            if (expr->opcode[0] != JIM_EXPROP_VARIABLE &&
+                expr->opcode[0] != JIM_EXPROP_NUMBER)
+                goto noopt;
+            break;
+        case 2:
+            if (expr->opcode[1] != JIM_EXPROP_NOT ||
+                expr->opcode[0] != JIM_EXPROP_VARIABLE)
+                goto noopt;
+            break;
+        case 3:
+            if (expr->opcode[0] != JIM_EXPROP_VARIABLE ||
+                (expr->opcode[1] != JIM_EXPROP_NUMBER &&
+                 expr->opcode[1] != JIM_EXPROP_VARIABLE))
+                goto noopt;
+            switch(expr->opcode[2]) {
+            case JIM_EXPROP_LT:
+            case JIM_EXPROP_LTE:
+            case JIM_EXPROP_GT:
+            case JIM_EXPROP_GTE:
+            case JIM_EXPROP_NUMEQ:
+            case JIM_EXPROP_NUMNE:
+                /* nothing to do */
+                break;
+            default:
+                goto noopt;
+            }
+            break;
+        default:
+            Jim_Panic(interp,
+                "Unexpected default reached in Jim_WhileCoreCommand()");
+            break;
+        }
+
+        /* STEP 2 -- conditions meet. Initialization. Take different
+         * branches for different expression lengths. */
+        exprLen = expr->len;
+
+        if (exprLen == 1) {
+            jim_wide wideValue;
+
+            if (expr->opcode[0] == JIM_EXPROP_VARIABLE) {
+                varAObjPtr = expr->obj[0];
+                Jim_IncrRefCount(varAObjPtr);
+            } else {
+                if (Jim_GetWide(interp, expr->obj[0], &wideValue) != JIM_OK)
+                    goto noopt;
+            }
+            while (1) {
+                if (varAObjPtr) {
+                    if (!(objPtr =
+                               Jim_GetVariable(interp, varAObjPtr, JIM_NONE)) ||
+                        Jim_GetWide(interp, objPtr, &wideValue) != JIM_OK)
+                    {
+                        Jim_DecrRefCount(interp, varAObjPtr);
+                        goto noopt;
+                    }
+                }
+                if (!wideValue) break;
+                if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
+                    switch(retval) {
+                    case JIM_BREAK:
+                        if (varAObjPtr)
+                            Jim_DecrRefCount(interp, varAObjPtr);
+                        goto out;
+                        break;
+                    case JIM_CONTINUE:
+                        continue;
+                        break;
+                    default:
+                        if (varAObjPtr)
+                            Jim_DecrRefCount(interp, varAObjPtr);
+                        return retval;
+                    }
+                }
+            }
+            if (varAObjPtr)
+                Jim_DecrRefCount(interp, varAObjPtr);
+        } else if (exprLen == 3) {
+            jim_wide wideValueA, wideValueB, cmpRes = 0;
+            int cmpType = expr->opcode[2];
+
+            varAObjPtr = expr->obj[0];
+            Jim_IncrRefCount(varAObjPtr);
+            if (expr->opcode[1] == JIM_EXPROP_VARIABLE) {
+                varBObjPtr = expr->obj[1];
+                Jim_IncrRefCount(varBObjPtr);
+            } else {
+                if (Jim_GetWide(interp, expr->obj[1], &wideValueB) != JIM_OK)
+                    goto noopt;
+            }
+            while (1) {
+                if (!(objPtr = Jim_GetVariable(interp, varAObjPtr, JIM_NONE)) ||
+                    Jim_GetWide(interp, objPtr, &wideValueA) != JIM_OK)
+                {
+                    Jim_DecrRefCount(interp, varAObjPtr);
+                    if (varBObjPtr)
+                        Jim_DecrRefCount(interp, varBObjPtr);
+                    goto noopt;
+                }
+                if (varBObjPtr) {
+                    if (!(objPtr =
+                               Jim_GetVariable(interp, varBObjPtr, JIM_NONE)) ||
+                        Jim_GetWide(interp, objPtr, &wideValueB) != JIM_OK)
+                    {
+                        Jim_DecrRefCount(interp, varAObjPtr);
+                        if (varBObjPtr)
+                            Jim_DecrRefCount(interp, varBObjPtr);
+                        goto noopt;
+                    }
+                }
+                switch(cmpType) {
+                case JIM_EXPROP_LT:
+                    cmpRes = wideValueA < wideValueB; break;
+                case JIM_EXPROP_LTE:
+                    cmpRes = wideValueA <= wideValueB; break;
+                case JIM_EXPROP_GT:
+                    cmpRes = wideValueA > wideValueB; break;
+                case JIM_EXPROP_GTE:
+                    cmpRes = wideValueA >= wideValueB; break;
+                case JIM_EXPROP_NUMEQ:
+                    cmpRes = wideValueA == wideValueB; break;
+                case JIM_EXPROP_NUMNE:
+                    cmpRes = wideValueA != wideValueB; break;
+                }
+                if (!cmpRes) break;
+                if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
+                    switch(retval) {
+                    case JIM_BREAK:
+                        Jim_DecrRefCount(interp, varAObjPtr);
+                        if (varBObjPtr)
+                            Jim_DecrRefCount(interp, varBObjPtr);
+                        goto out;
+                        break;
+                    case JIM_CONTINUE:
+                        continue;
+                        break;
+                    default:
+                        Jim_DecrRefCount(interp, varAObjPtr);
+                        if (varBObjPtr)
+                            Jim_DecrRefCount(interp, varBObjPtr);
+                        return retval;
+                    }
+                }
+            }
+            Jim_DecrRefCount(interp, varAObjPtr);
+            if (varBObjPtr)
+                Jim_DecrRefCount(interp, varBObjPtr);
+        } else {
+            /* TODO: case for len == 2 */
+            goto noopt;
+        }
+        Jim_SetEmptyResult(interp);
+        return JIM_OK;
+    }
+noopt:
+#endif
+
+    /* The general purpose implementation of while starts here */
+    while (1) {
+        int boolean, retval;
+
+        if ((retval = Jim_GetBoolFromExpr(interp, argv[1],
+                        &boolean)) != JIM_OK)
+            return retval;
+        if (!boolean) break;
+        if ((retval = Jim_EvalObj(interp, argv[2])) != JIM_OK) {
+            switch(retval) {
+            case JIM_BREAK:
+                goto out;
+                break;
+            case JIM_CONTINUE:
+                continue;
+                break;
+            default:
+                return retval;
+            }
+        }
+    }
+out:
+    Jim_SetEmptyResult(interp);
+    return JIM_OK;
+}
+
+/* [for] */
+static int Jim_ForCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int retval;
+
+    if (argc != 5) {
+        Jim_WrongNumArgs(interp, 1, argv, "start test next body");
+        return JIM_ERR;
+    }
+    /* Check if the for is on the form:
+     *      for {set i CONST} {$i < CONST} {incr i}
+     *      for {set i CONST} {$i < $j} {incr i}
+     *      for {set i CONST} {$i <= CONST} {incr i}
+     *      for {set i CONST} {$i <= $j} {incr i}
+     * XXX: NOTE: if variable traces are implemented, this optimization
+     * need to be modified to check for the proc epoch at every variable
+     * update. */
+#ifdef JIM_OPTIMIZATION
+    {
+        ScriptObj *initScript, *incrScript;
+        ExprByteCode *expr;
+        jim_wide start, stop, currentVal;
+        unsigned jim_wide procEpoch = interp->procEpoch;
+        Jim_Obj *varNamePtr, *stopVarNamePtr = NULL, *objPtr;
+        int cmpType;
+        struct Jim_Cmd *cmdPtr;
+
+        /* Do it only if there aren't shared arguments */
+        if (argv[1] == argv[2] || argv[2] == argv[3] || argv[1] == argv[3])
+            goto evalstart;
+        initScript = Jim_GetScript(interp, argv[1]);
+        expr = Jim_GetExpression(interp, argv[2]);
+        incrScript = Jim_GetScript(interp, argv[3]);
+
+        /* Ensure proper lengths to start */
+        if (initScript->len != 6) goto evalstart;
+        if (incrScript->len != 4) goto evalstart;
+        if (expr->len != 3) goto evalstart;
+        /* Ensure proper token types. */
+        if (initScript->token[2].type != JIM_TT_ESC ||
+            initScript->token[4].type != JIM_TT_ESC ||
+            incrScript->token[2].type != JIM_TT_ESC ||
+            expr->opcode[0] != JIM_EXPROP_VARIABLE ||
+            (expr->opcode[1] != JIM_EXPROP_NUMBER &&
+             expr->opcode[1] != JIM_EXPROP_VARIABLE) ||
+            (expr->opcode[2] != JIM_EXPROP_LT &&
+             expr->opcode[2] != JIM_EXPROP_LTE))
+            goto evalstart;
+        cmpType = expr->opcode[2];
+        /* Initialization command must be [set] */
+        cmdPtr = Jim_GetCommand(interp, initScript->token[0].objPtr, JIM_NONE);
+        if (cmdPtr == NULL || cmdPtr->cmdProc != Jim_SetCoreCommand)
+            goto evalstart;
+        /* Update command must be incr */
+        cmdPtr = Jim_GetCommand(interp, incrScript->token[0].objPtr, JIM_NONE);
+        if (cmdPtr == NULL || cmdPtr->cmdProc != Jim_IncrCoreCommand)
+            goto evalstart;
+        /* set, incr, expression must be about the same variable */
+        if (!Jim_StringEqObj(initScript->token[2].objPtr,
+                            incrScript->token[2].objPtr, 0))
+            goto evalstart;
+        if (!Jim_StringEqObj(initScript->token[2].objPtr,
+                            expr->obj[0], 0))
+            goto evalstart;
+        /* Check that the initialization and comparison are valid integers */
+        if (Jim_GetWide(interp, initScript->token[4].objPtr, &start) == JIM_ERR)
+            goto evalstart;
+        if (expr->opcode[1] == JIM_EXPROP_NUMBER &&
+            Jim_GetWide(interp, expr->obj[1], &stop) == JIM_ERR)
+        {
+            goto evalstart;
+        }
+
+        /* Initialization */
+        varNamePtr = expr->obj[0];
+        if (expr->opcode[1] == JIM_EXPROP_VARIABLE) {
+            stopVarNamePtr = expr->obj[1];
+            Jim_IncrRefCount(stopVarNamePtr);
+        }
+        Jim_IncrRefCount(varNamePtr);
+
+        /* --- OPTIMIZED FOR --- */
+        /* Start to loop */
+        objPtr = Jim_NewIntObj(interp, start);
+        if (Jim_SetVariable(interp, varNamePtr, objPtr) != JIM_OK) {
+            Jim_DecrRefCount(interp, varNamePtr);
+            if (stopVarNamePtr) Jim_DecrRefCount(interp, stopVarNamePtr);
+            Jim_FreeNewObj(interp, objPtr);
+            goto evalstart;
+        }
+        while (1) {
+            /* === Check condition === */
+            /* Common code: */
+            objPtr = Jim_GetVariable(interp, varNamePtr, JIM_NONE);
+            if (objPtr == NULL ||
+                Jim_GetWide(interp, objPtr, &currentVal) != JIM_OK)
+            {
+                Jim_DecrRefCount(interp, varNamePtr);
+                if (stopVarNamePtr) Jim_DecrRefCount(interp, stopVarNamePtr);
+                goto testcond;
+            }
+            /* Immediate or Variable? get the 'stop' value if the latter. */
+            if (stopVarNamePtr) {
+                objPtr = Jim_GetVariable(interp, stopVarNamePtr, JIM_NONE);
+                if (objPtr == NULL ||
+                    Jim_GetWide(interp, objPtr, &stop) != JIM_OK)
+                {
+                    Jim_DecrRefCount(interp, varNamePtr);
+                    Jim_DecrRefCount(interp, stopVarNamePtr);
+                    goto testcond;
+                }
+            }
+            if (cmpType == JIM_EXPROP_LT) {
+                if (currentVal >= stop) break;
+            } else {
+                if (currentVal > stop) break;
+            }
+            /* Eval body */
+            if ((retval = Jim_EvalObj(interp, argv[4])) != JIM_OK) {
+                switch(retval) {
+                case JIM_BREAK:
+                    if (stopVarNamePtr)
+                        Jim_DecrRefCount(interp, stopVarNamePtr);
+                    Jim_DecrRefCount(interp, varNamePtr);
+                    goto out;
+                case JIM_CONTINUE:
+                    /* nothing to do */
+                    break;
+                default:
+                    if (stopVarNamePtr)
+                        Jim_DecrRefCount(interp, stopVarNamePtr);
+                    Jim_DecrRefCount(interp, varNamePtr);
+                    return retval;
+                }
+            }
+            /* If there was a change in procedures/command continue
+             * with the usual [for] command implementation */
+            if (procEpoch != interp->procEpoch) {
+                if (stopVarNamePtr)
+                    Jim_DecrRefCount(interp, stopVarNamePtr);
+                Jim_DecrRefCount(interp, varNamePtr);
+                goto evalnext;
+            }
+            /* Increment */
+            objPtr = Jim_GetVariable(interp, varNamePtr, JIM_ERRMSG);
+            if (objPtr->refCount == 1 && objPtr->typePtr == &intObjType) {
+                objPtr->internalRep.wideValue ++;
+                Jim_InvalidateStringRep(objPtr);
+            } else {
+                Jim_Obj *auxObjPtr;
+
+                if (Jim_GetWide(interp, objPtr, &currentVal) == JIM_ERR) {
+                    if (stopVarNamePtr)
+                        Jim_DecrRefCount(interp, stopVarNamePtr);
+                    Jim_DecrRefCount(interp, varNamePtr);
+                    goto evalnext;
+                }
+                auxObjPtr = Jim_NewIntObj(interp, currentVal+1);
+                if (Jim_SetVariable(interp, varNamePtr, auxObjPtr) == JIM_ERR) {
+                    if (stopVarNamePtr)
+                        Jim_DecrRefCount(interp, stopVarNamePtr);
+                    Jim_DecrRefCount(interp, varNamePtr);
+                    Jim_FreeNewObj(interp, auxObjPtr);
+                    goto evalnext;
+                }
+            }
+        }
+        if (stopVarNamePtr)
+            Jim_DecrRefCount(interp, stopVarNamePtr);
+        Jim_DecrRefCount(interp, varNamePtr);
+        Jim_SetEmptyResult(interp);
+        return JIM_OK;
+    }
+#endif
+evalstart:
+    /* Eval start */
+    if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK)
+        return retval;
+    while (1) {
+        int boolean;
+testcond:
+        /* Test the condition */
+        if ((retval = Jim_GetBoolFromExpr(interp, argv[2], &boolean))
+                != JIM_OK)
+            return retval;
+        if (!boolean) break;
+        /* Eval body */
+        if ((retval = Jim_EvalObj(interp, argv[4])) != JIM_OK) {
+            switch(retval) {
+            case JIM_BREAK:
+                goto out;
+                break;
+            case JIM_CONTINUE:
+                /* Nothing to do */
+                break;
+            default:
+                return retval;
+            }
+        }
+evalnext:
+        /* Eval next */
+        if ((retval = Jim_EvalObj(interp, argv[3])) != JIM_OK) {
+            switch(retval) {
+            case JIM_BREAK:
+                goto out;
+                break;
+            case JIM_CONTINUE:
+                continue;
+                break;
+            default:
+                return retval;
+            }
+        }
+    }
+out:
+    Jim_SetEmptyResult(interp);
+    return JIM_OK;
+}
+
+/* foreach + lmap implementation. */
+static int JimForeachMapHelper(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv, int doMap)
+{
+    int result = JIM_ERR, i, nbrOfLists, *listsIdx, *listsEnd;
+    int nbrOfLoops = 0;
+    Jim_Obj *emptyStr, *script, *mapRes = NULL;
+
+    if (argc < 4 || argc % 2 != 0) {
+        Jim_WrongNumArgs(interp, 1, argv, "varList list ?varList list ...? script");
+        return JIM_ERR;
+    }
+    if (doMap) {
+        mapRes = Jim_NewListObj(interp, NULL, 0);
+        Jim_IncrRefCount(mapRes);
+    }
+    emptyStr = Jim_NewEmptyStringObj(interp);
+    Jim_IncrRefCount(emptyStr);
+    script = argv[argc-1];            /* Last argument is a script */
+    nbrOfLists = (argc - 1 - 1) / 2;  /* argc - 'foreach' - script */
+    listsIdx = (int*)Jim_Alloc(nbrOfLists * sizeof(int));
+    listsEnd = (int*)Jim_Alloc(nbrOfLists*2 * sizeof(int));
+    /* Initialize iterators and remember max nbr elements each list */
+    memset(listsIdx, 0, nbrOfLists * sizeof(int));
+    /* Remember lengths of all lists and calculate how much rounds to loop */
+    for (i=0; i < nbrOfLists*2; i += 2) {
+        div_t cnt;
+        int count;
+        Jim_ListLength(interp, argv[i+1], &listsEnd[i]);
+        Jim_ListLength(interp, argv[i+2], &listsEnd[i+1]);
+        if (listsEnd[i] == 0) {
+            Jim_SetResultString(interp, "foreach varlist is empty", -1);
+            goto err;
+        }
+        cnt = div(listsEnd[i+1], listsEnd[i]);
+        count = cnt.quot + (cnt.rem ? 1 : 0);
+        if (count > nbrOfLoops)
+            nbrOfLoops = count;
+    }
+    for (; nbrOfLoops-- > 0; ) {
+        for (i=0; i < nbrOfLists; ++i) {
+            int varIdx = 0, var = i * 2;
+            while (varIdx < listsEnd[var]) {
+                Jim_Obj *varName, *ele;
+                int lst = i * 2 + 1;
+                if (Jim_ListIndex(interp, argv[var+1], varIdx, &varName, JIM_ERRMSG)
+                        != JIM_OK)
+                        goto err;
+                if (listsIdx[i] < listsEnd[lst]) {
+                    if (Jim_ListIndex(interp, argv[lst+1], listsIdx[i], &ele, JIM_ERRMSG)
+                        != JIM_OK)
+                        goto err;
+                    if (Jim_SetVariable(interp, varName, ele) != JIM_OK) {
+                        Jim_SetResultString(interp, "couldn't set loop variable: ", -1);
+                        goto err;
+                    }
+                    ++listsIdx[i];  /* Remember next iterator of current list */ 
+                } else if (Jim_SetVariable(interp, varName, emptyStr) != JIM_OK) {
+                    Jim_SetResultString(interp, "couldn't set loop variable: ", -1);
+                    goto err;
+                }
+                ++varIdx;  /* Next variable */
+            }
+        }
+        switch (result = Jim_EvalObj(interp, script)) {
+            case JIM_OK:
+                if (doMap)
+                    Jim_ListAppendElement(interp, mapRes, interp->result);
+                break;
+            case JIM_CONTINUE:
+                break;
+            case JIM_BREAK:
+                goto out;
+                break;
+            default:
+                goto err;
+        }
+    }
+out:
+    result = JIM_OK;
+    if (doMap)
+        Jim_SetResult(interp, mapRes);
+    else
+        Jim_SetEmptyResult(interp);
+err:
+    if (doMap)
+        Jim_DecrRefCount(interp, mapRes);
+    Jim_DecrRefCount(interp, emptyStr);
+    Jim_Free(listsIdx);
+    Jim_Free(listsEnd);
+    return result;
+}
+
+/* [foreach] */
+static int Jim_ForeachCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    return JimForeachMapHelper(interp, argc, argv, 0);
+}
+
+/* [lmap] */
+static int Jim_LmapCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    return JimForeachMapHelper(interp, argc, argv, 1);
+}
+
+/* [if] */
+static int Jim_IfCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int boolean, retval, current = 1, falsebody = 0;
+    if (argc >= 3) {
+        while (1) {
+            /* Far not enough arguments given! */
+            if (current >= argc) goto err;
+            if ((retval = Jim_GetBoolFromExpr(interp,
+                        argv[current++], &boolean))
+                    != JIM_OK)
+                return retval;
+            /* There lacks something, isn't it? */
+            if (current >= argc) goto err;
+            if (Jim_CompareStringImmediate(interp, argv[current],
+                        "then")) current++;
+            /* Tsk tsk, no then-clause? */
+            if (current >= argc) goto err;
+            if (boolean)
+                return Jim_EvalObj(interp, argv[current]);
+             /* Ok: no else-clause follows */
+            if (++current >= argc) return JIM_OK;
+            falsebody = current++;
+            if (Jim_CompareStringImmediate(interp, argv[falsebody],
+                        "else")) {
+                /* IIICKS - else-clause isn't last cmd? */
+                if (current != argc-1) goto err;
+                return Jim_EvalObj(interp, argv[current]);
+            } else if (Jim_CompareStringImmediate(interp,
+                        argv[falsebody], "elseif"))
+                /* Ok: elseif follows meaning all the stuff
+                 * again (how boring...) */
+                continue;
+            /* OOPS - else-clause is not last cmd?*/
+            else if (falsebody != argc-1)
+                goto err;
+            return Jim_EvalObj(interp, argv[falsebody]);
+        }
+        return JIM_OK;
+    }
+err:
+    Jim_WrongNumArgs(interp, 1, argv, "condition ?then? trueBody ?elseif ...? ?else? falseBody");
+    return JIM_ERR;
+}
+
+enum {SWITCH_EXACT, SWITCH_GLOB, SWITCH_RE, SWITCH_CMD, SWITCH_UNKNOWN};
+
+/* [switch] */
+static int Jim_SwitchCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int retcode = JIM_ERR, matchOpt = SWITCH_EXACT, opt=1, patCount, i;
+    Jim_Obj *command = 0, *const *caseList = 0, *strObj;
+    Jim_Obj *script = 0;
+    if (argc < 3) goto wrongnumargs;
+    for (opt=1; opt < argc; ++opt) {
+        const char *option = Jim_GetString(argv[opt], 0);
+        if (*option != '-') break;
+        else if (strncmp(option, "--", 2) == 0) { ++opt; break; }
+        else if (strncmp(option, "-exact", 2) == 0) matchOpt = SWITCH_EXACT;
+        else if (strncmp(option, "-glob", 2) == 0) matchOpt = SWITCH_GLOB;
+        else if (strncmp(option, "-regexp", 2) == 0) matchOpt = SWITCH_RE;
+        else if (strncmp(option, "-command", 2) == 0) { matchOpt = SWITCH_CMD;
+            if ((argc - opt) < 2) goto wrongnumargs;
+            command = argv[++opt]; 
+        } else {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "bad option \"", option, "\": must be -exact, -glob, "
+                "-regexp, -command procname or --", 0);
+            goto err;            
+        }
+        if ((argc - opt) < 2) goto wrongnumargs;
+    }
+    strObj = argv[opt++];
+    patCount = argc - opt;
+    if (patCount == 1) {
+        Jim_Obj **vector;
+        JimListGetElements(interp, argv[opt], &patCount, &vector);
+        caseList = vector;
+    } else
+        caseList = &argv[opt];
+    if (patCount == 0 || patCount % 2 != 0) goto wrongnumargs;
+    for (i=0; script == 0 && i < patCount; i += 2) {
+        Jim_Obj *patObj = caseList[i];
+        if (!Jim_CompareStringImmediate(interp, patObj, "default")
+            || i < (patCount-2)) {
+            switch (matchOpt) {
+                case SWITCH_EXACT:
+                    if (Jim_StringEqObj(strObj, patObj, 0))
+                        script = caseList[i+1];
+                    break;
+                case SWITCH_GLOB:
+                    if (Jim_StringMatchObj(patObj, strObj, 0))
+                        script = caseList[i+1];
+                    break;
+                case SWITCH_RE:
+                    command = Jim_NewStringObj(interp, "regexp", -1);
+                    /* Fall thru intentionally */
+                case SWITCH_CMD: {
+                    Jim_Obj *parms[] = {command, patObj, strObj};
+                    int rc = Jim_EvalObjVector(interp, 3, parms);
+                    long matching;
+                    /* After the execution of a command we need to
+                     * make sure to reconvert the object into a list
+                     * again. Only for the single-list style [switch]. */
+                    if (argc-opt == 1) {
+                        Jim_Obj **vector;
+                        JimListGetElements(interp, argv[opt], &patCount,
+                                &vector);
+                        caseList = vector;
+                    }
+                    /* command is here already decref'd */
+                    if (rc != JIM_OK) {
+                        retcode = rc;
+                        goto err;
+                    }
+                    rc = Jim_GetLong(interp, Jim_GetResult(interp), &matching);
+                    if (rc != JIM_OK) {
+                        retcode = rc;
+                        goto err;
+                    }
+                    if (matching)
+                        script = caseList[i+1];
+                    break;
+                }
+                default:
+                    Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+                    Jim_AppendStrings(interp, Jim_GetResult(interp),
+                        "internal error: no such option implemented", 0);
+                    goto err;
+            }
+        } else {
+          script = caseList[i+1];
+        }
+    }
+    for(; i < patCount && Jim_CompareStringImmediate(interp, script, "-");
+        i += 2)
+        script = caseList[i+1];
+    if (script && Jim_CompareStringImmediate(interp, script, "-")) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "no body specified for pattern \"",
+            Jim_GetString(caseList[i-2], 0), "\"", 0);
+        goto err;
+    }
+    retcode = JIM_OK;
+    Jim_SetEmptyResult(interp);
+    if (script != 0)
+        retcode = Jim_EvalObj(interp, script);
+    return retcode;
+wrongnumargs:
+    Jim_WrongNumArgs(interp, 1, argv, "?options? string "
+        "pattern body ... ?default body?   or   "
+        "{pattern body ?pattern body ...?}");
+err:
+    return retcode;        
+}
+
+/* [list] */
+static int Jim_ListCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *listObjPtr;
+
+    listObjPtr = Jim_NewListObj(interp, argv+1, argc-1);
+    Jim_SetResult(interp, listObjPtr);
+    return JIM_OK;
+}
+
+/* [lindex] */
+static int Jim_LindexCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *objPtr, *listObjPtr;
+    int i;
+    int index;
+
+    if (argc < 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "list index ?...?");
+        return JIM_ERR;
+    }
+    objPtr = argv[1];
+    Jim_IncrRefCount(objPtr);
+    for (i = 2; i < argc; i++) {
+        listObjPtr = objPtr;
+        if (Jim_GetIndex(interp, argv[i], &index) != JIM_OK) {
+            Jim_DecrRefCount(interp, listObjPtr);
+            return JIM_ERR;
+        }
+        if (Jim_ListIndex(interp, listObjPtr, index, &objPtr,
+                    JIM_NONE) != JIM_OK) {
+            /* Returns an empty object if the index
+             * is out of range. */
+            Jim_DecrRefCount(interp, listObjPtr);
+            Jim_SetEmptyResult(interp);
+            return JIM_OK;
+        }
+        Jim_IncrRefCount(objPtr);
+        Jim_DecrRefCount(interp, listObjPtr);
+    }
+    Jim_SetResult(interp, objPtr);
+    Jim_DecrRefCount(interp, objPtr);
+    return JIM_OK;
+}
+
+/* [llength] */
+static int Jim_LlengthCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int len;
+
+    if (argc != 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "list");
+        return JIM_ERR;
+    }
+    Jim_ListLength(interp, argv[1], &len);
+    Jim_SetResult(interp, Jim_NewIntObj(interp, len));
+    return JIM_OK;
+}
+
+/* [lappend] */
+static int Jim_LappendCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *listObjPtr;
+    int shared, i;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
+        return JIM_ERR;
+    }
+    listObjPtr = Jim_GetVariable(interp, argv[1], JIM_NONE);
+    if (!listObjPtr) {
+        /* Create the list if it does not exists */
+        listObjPtr = Jim_NewListObj(interp, NULL, 0);
+        if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
+            Jim_FreeNewObj(interp, listObjPtr);
+            return JIM_ERR;
+        }
+    }
+    shared = Jim_IsShared(listObjPtr);
+    if (shared)
+        listObjPtr = Jim_DuplicateObj(interp, listObjPtr);
+    for (i = 2; i < argc; i++)
+        Jim_ListAppendElement(interp, listObjPtr, argv[i]);
+    if (Jim_SetVariable(interp, argv[1], listObjPtr) != JIM_OK) {
+        if (shared)
+            Jim_FreeNewObj(interp, listObjPtr);
+        return JIM_ERR;
+    }
+    Jim_SetResult(interp, listObjPtr);
+    return JIM_OK;
+}
+
+/* [linsert] */
+static int Jim_LinsertCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int index, len;
+    Jim_Obj *listPtr;
+
+    if (argc < 4) {
+        Jim_WrongNumArgs(interp, 1, argv, "list index element "
+            "?element ...?");
+        return JIM_ERR;
+    }
+    listPtr = argv[1];
+    if (Jim_IsShared(listPtr))
+        listPtr = Jim_DuplicateObj(interp, listPtr);
+    if (Jim_GetIndex(interp, argv[2], &index) != JIM_OK)
+        goto err;
+    Jim_ListLength(interp, listPtr, &len);
+    if (index >= len)
+        index = len;
+    else if (index < 0)
+        index = len + index + 1;
+    Jim_ListInsertElements(interp, listPtr, index, argc-3, &argv[3]);
+    Jim_SetResult(interp, listPtr);
+    return JIM_OK;
+err:
+    if (listPtr != argv[1]) {
+        Jim_FreeNewObj(interp, listPtr);
+    }
+    return JIM_ERR;
+}
+
+/* [lset] */
+static int Jim_LsetCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc < 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "listVar ?index...? newVal");
+        return JIM_ERR;
+    } else if (argc == 3) {
+        if (Jim_SetVariable(interp, argv[1], argv[2]) != JIM_OK)
+            return JIM_ERR;
+        Jim_SetResult(interp, argv[2]);
+        return JIM_OK;
+    }
+    if (Jim_SetListIndex(interp, argv[1], argv+2, argc-3, argv[argc-1])
+            == JIM_ERR) return JIM_ERR;
+    return JIM_OK;
+}
+
+/* [lsort] */
+static int Jim_LsortCoreCommand(Jim_Interp *interp, int argc, Jim_Obj *const argv[])
+{
+    const char *options[] = {
+        "-ascii", "-nocase", "-increasing", "-decreasing", NULL
+    };
+    enum {OPT_ASCII, OPT_NOCASE, OPT_INCREASING, OPT_DECREASING};
+    Jim_Obj *resObj;
+    int i, lsortType = JIM_LSORT_ASCII; /* default sort type */
+    int decreasing = 0;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "?options? list");
+        return JIM_ERR;
+    }
+    for (i = 1; i < (argc-1); i++) {
+        int option;
+
+        if (Jim_GetEnum(interp, argv[i], options, &option, "option", JIM_ERRMSG)
+                != JIM_OK)
+            return JIM_ERR;
+        switch(option) {
+        case OPT_ASCII: lsortType = JIM_LSORT_ASCII; break;
+        case OPT_NOCASE: lsortType = JIM_LSORT_NOCASE; break;
+        case OPT_INCREASING: decreasing = 0; break;
+        case OPT_DECREASING: decreasing = 1; break;
+        }
+    }
+    if (decreasing) {
+        switch(lsortType) {
+        case JIM_LSORT_ASCII: lsortType = JIM_LSORT_ASCII_DECR; break;
+        case JIM_LSORT_NOCASE: lsortType = JIM_LSORT_NOCASE_DECR; break;
+        }
+    }
+    resObj = Jim_DuplicateObj(interp, argv[argc-1]);
+    ListSortElements(interp, resObj, lsortType);
+    Jim_SetResult(interp, resObj);
+    return JIM_OK;
+}
+
+/* [append] */
+static int Jim_AppendCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *stringObjPtr;
+    int shared, i;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "varName ?value value ...?");
+        return JIM_ERR;
+    }
+    if (argc == 2) {
+        stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_ERRMSG);
+        if (!stringObjPtr) return JIM_ERR;
+    } else {
+        stringObjPtr = Jim_GetVariable(interp, argv[1], JIM_NONE);
+        if (!stringObjPtr) {
+            /* Create the string if it does not exists */
+            stringObjPtr = Jim_NewEmptyStringObj(interp);
+            if (Jim_SetVariable(interp, argv[1], stringObjPtr)
+                    != JIM_OK) {
+                Jim_FreeNewObj(interp, stringObjPtr);
+                return JIM_ERR;
+            }
+        }
+    }
+    shared = Jim_IsShared(stringObjPtr);
+    if (shared)
+        stringObjPtr = Jim_DuplicateObj(interp, stringObjPtr);
+    for (i = 2; i < argc; i++)
+        Jim_AppendObj(interp, stringObjPtr, argv[i]);
+    if (Jim_SetVariable(interp, argv[1], stringObjPtr) != JIM_OK) {
+        if (shared)
+            Jim_FreeNewObj(interp, stringObjPtr);
+        return JIM_ERR;
+    }
+    Jim_SetResult(interp, stringObjPtr);
+    return JIM_OK;
+}
+
+/* [debug] */
+static int Jim_DebugCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    const char *options[] = {
+        "refcount", "objcount", "objects", "invstr", "scriptlen", "exprlen",
+        "exprbc",
+        NULL
+    };
+    enum {
+        OPT_REFCOUNT, OPT_OBJCOUNT, OPT_OBJECTS, OPT_INVSTR, OPT_SCRIPTLEN,
+        OPT_EXPRLEN, OPT_EXPRBC
+    };
+    int option;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "option ?...?");
+        return JIM_ERR;
+    }
+    if (Jim_GetEnum(interp, argv[1], options, &option, "option",
+                JIM_ERRMSG) != JIM_OK)
+        return JIM_ERR;
+    if (option == OPT_REFCOUNT) {
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "object");
+            return JIM_ERR;
+        }
+        Jim_SetResult(interp, Jim_NewIntObj(interp, argv[2]->refCount));
+        return JIM_OK;
+    } else if (option == OPT_OBJCOUNT) {
+        int freeobj = 0, liveobj = 0;
+        char buf[256];
+        Jim_Obj *objPtr;
+
+        if (argc != 2) {
+            Jim_WrongNumArgs(interp, 2, argv, "");
+            return JIM_ERR;
+        }
+        /* Count the number of free objects. */
+        objPtr = interp->freeList;
+        while (objPtr) {
+            freeobj++;
+            objPtr = objPtr->nextObjPtr;
+        }
+        /* Count the number of live objects. */
+        objPtr = interp->liveList;
+        while (objPtr) {
+            liveobj++;
+            objPtr = objPtr->nextObjPtr;
+        }
+        /* Set the result string and return. */
+        sprintf(buf, "free %d used %d", freeobj, liveobj);
+        Jim_SetResultString(interp, buf, -1);
+        return JIM_OK;
+    } else if (option == OPT_OBJECTS) {
+        Jim_Obj *objPtr, *listObjPtr, *subListObjPtr;
+        /* Count the number of live objects. */
+        objPtr = interp->liveList;
+        listObjPtr = Jim_NewListObj(interp, NULL, 0);
+        while (objPtr) {
+            char buf[128];
+            const char *type = objPtr->typePtr ?
+                objPtr->typePtr->name : "";
+            subListObjPtr = Jim_NewListObj(interp, NULL, 0);
+            sprintf(buf, "%p", objPtr);
+            Jim_ListAppendElement(interp, subListObjPtr,
+                Jim_NewStringObj(interp, buf, -1));
+            Jim_ListAppendElement(interp, subListObjPtr,
+                Jim_NewStringObj(interp, type, -1));
+            Jim_ListAppendElement(interp, subListObjPtr,
+                Jim_NewIntObj(interp, objPtr->refCount));
+            Jim_ListAppendElement(interp, subListObjPtr, objPtr);
+            Jim_ListAppendElement(interp, listObjPtr, subListObjPtr);
+            objPtr = objPtr->nextObjPtr;
+        }
+        Jim_SetResult(interp, listObjPtr);
+        return JIM_OK;
+    } else if (option == OPT_INVSTR) {
+        Jim_Obj *objPtr;
+
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "object");
+            return JIM_ERR;
+        }
+        objPtr = argv[2];
+        if (objPtr->typePtr != NULL)
+            Jim_InvalidateStringRep(objPtr);
+        Jim_SetEmptyResult(interp);
+        return JIM_OK;
+    } else if (option == OPT_SCRIPTLEN) {
+        ScriptObj *script;
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "script");
+            return JIM_ERR;
+        }
+        script = Jim_GetScript(interp, argv[2]);
+        Jim_SetResult(interp, Jim_NewIntObj(interp, script->len));
+        return JIM_OK;
+    } else if (option == OPT_EXPRLEN) {
+        ExprByteCode *expr;
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "expression");
+            return JIM_ERR;
+        }
+        expr = Jim_GetExpression(interp, argv[2]);
+        if (expr == NULL)
+            return JIM_ERR;
+        Jim_SetResult(interp, Jim_NewIntObj(interp, expr->len));
+        return JIM_OK;
+    } else if (option == OPT_EXPRBC) {
+        Jim_Obj *objPtr;
+        ExprByteCode *expr;
+        int i;
+
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "expression");
+            return JIM_ERR;
+        }
+        expr = Jim_GetExpression(interp, argv[2]);
+        if (expr == NULL)
+            return JIM_ERR;
+        objPtr = Jim_NewListObj(interp, NULL, 0);
+        for (i = 0; i < expr->len; i++) {
+            const char *type;
+            Jim_ExprOperator *op;
+
+            switch(expr->opcode[i]) {
+            case JIM_EXPROP_NUMBER: type = "number"; break;
+            case JIM_EXPROP_COMMAND: type = "command"; break;
+            case JIM_EXPROP_VARIABLE: type = "variable"; break;
+            case JIM_EXPROP_DICTSUGAR: type = "dictsugar"; break;
+            case JIM_EXPROP_SUBST: type = "subst"; break;
+            case JIM_EXPROP_STRING: type = "string"; break;
+            default:
+                op = JimExprOperatorInfo(Jim_GetString(expr->obj[i], NULL));
+                if (op == NULL) {
+                    type = "private";
+                } else {
+                    type = "operator";
+                }
+                break;
+            }
+            Jim_ListAppendElement(interp, objPtr,
+                    Jim_NewStringObj(interp, type, -1));
+            Jim_ListAppendElement(interp, objPtr, expr->obj[i]);
+        }
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    } else {
+        Jim_SetResultString(interp,
+            "bad option. Valid options are refcount, "
+            "objcount, objects, invstr", -1);
+        return JIM_ERR;
+    }
+    return JIM_OK; /* unreached */
+}
+
+/* [eval] */
+static int Jim_EvalCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc == 2) {
+        return Jim_EvalObj(interp, argv[1]);
+    } else if (argc > 2) {
+        Jim_Obj *objPtr;
+        int retcode;
+
+        objPtr = Jim_ConcatObj(interp, argc-1, argv+1);
+        Jim_IncrRefCount(objPtr);
+        retcode = Jim_EvalObj(interp, objPtr);
+        Jim_DecrRefCount(interp, objPtr);
+        return retcode;
+    } else {
+        Jim_WrongNumArgs(interp, 1, argv, "script ?...?");
+        return JIM_ERR;
+    }
+}
+
+/* [uplevel] */
+static int Jim_UplevelCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc >= 2) {
+        int retcode, newLevel, oldLevel;
+        Jim_CallFrame *savedCallFrame, *targetCallFrame;
+        Jim_Obj *objPtr;
+        const char *str;
+
+        /* Save the old callframe pointer */
+        savedCallFrame = interp->framePtr;
+
+        /* Lookup the target frame pointer */
+        str = Jim_GetString(argv[1], NULL);
+        if ((str[0] >= '0' && str[0] <= '9') || str[0] == '#')
+        {
+            if (Jim_GetCallFrameByLevel(interp, argv[1],
+                        &targetCallFrame,
+                        &newLevel) != JIM_OK)
+                return JIM_ERR;
+            argc--;
+            argv++;
+        } else {
+            if (Jim_GetCallFrameByLevel(interp, NULL,
+                        &targetCallFrame,
+                        &newLevel) != JIM_OK)
+                return JIM_ERR;
+        }
+        if (argc < 2) {
+            argc++;
+            argv--;
+            Jim_WrongNumArgs(interp, 1, argv,
+                    "?level? command ?arg ...?");
+            return JIM_ERR;
+        }
+        /* Eval the code in the target callframe. */
+        interp->framePtr = targetCallFrame;
+        oldLevel = interp->numLevels;
+        interp->numLevels = newLevel;
+        if (argc == 2) {
+            retcode = Jim_EvalObj(interp, argv[1]);
+        } else {
+            objPtr = Jim_ConcatObj(interp, argc-1, argv+1);
+            Jim_IncrRefCount(objPtr);
+            retcode = Jim_EvalObj(interp, objPtr);
+            Jim_DecrRefCount(interp, objPtr);
+        }
+        interp->numLevels = oldLevel;
+        interp->framePtr = savedCallFrame;
+        return retcode;
+    } else {
+        Jim_WrongNumArgs(interp, 1, argv, "?level? command ?arg ...?");
+        return JIM_ERR;
+    }
+}
+
+/* [expr] */
+static int Jim_ExprCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *exprResultPtr;
+    int retcode;
+
+    if (argc == 2) {
+        retcode = Jim_EvalExpression(interp, argv[1], &exprResultPtr);
+    } else if (argc > 2) {
+        Jim_Obj *objPtr;
+
+        objPtr = Jim_ConcatObj(interp, argc-1, argv+1);
+        Jim_IncrRefCount(objPtr);
+        retcode = Jim_EvalExpression(interp, objPtr, &exprResultPtr);
+        Jim_DecrRefCount(interp, objPtr);
+    } else {
+        Jim_WrongNumArgs(interp, 1, argv, "expression ?...?");
+        return JIM_ERR;
+    }
+    if (retcode != JIM_OK) return retcode;
+    Jim_SetResult(interp, exprResultPtr);
+    Jim_DecrRefCount(interp, exprResultPtr);
+    return JIM_OK;
+}
+
+/* [break] */
+static int Jim_BreakCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc != 1) {
+        Jim_WrongNumArgs(interp, 1, argv, "");
+        return JIM_ERR;
+    }
+    return JIM_BREAK;
+}
+
+/* [continue] */
+static int Jim_ContinueCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    if (argc != 1) {
+        Jim_WrongNumArgs(interp, 1, argv, "");
+        return JIM_ERR;
+    }
+    return JIM_CONTINUE;
+}
+
+/* [return] */
+static int Jim_ReturnCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc == 1) {
+        return JIM_RETURN;
+    } else if (argc == 2) {
+        Jim_SetResult(interp, argv[1]);
+        interp->returnCode = JIM_OK;
+        return JIM_RETURN;
+    } else if (argc == 3 || argc == 4) {
+        int returnCode;
+        if (Jim_GetReturnCode(interp, argv[2], &returnCode) == JIM_ERR)
+            return JIM_ERR;
+        interp->returnCode = returnCode;
+        if (argc == 4)
+            Jim_SetResult(interp, argv[3]);
+        return JIM_RETURN;
+    } else {
+        Jim_WrongNumArgs(interp, 1, argv, "?-code code? ?result?");
+        return JIM_ERR;
+    }
+    return JIM_RETURN; /* unreached */
+}
+
+/* [tailcall] */
+static int Jim_TailcallCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *objPtr;
+
+    objPtr = Jim_NewListObj(interp, argv+1, argc-1);
+    Jim_SetResult(interp, objPtr);
+    return JIM_EVAL;
+}
+
+/* [proc] */
+static int Jim_ProcCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int argListLen;
+    int arityMin, arityMax;
+
+    if (argc != 4 && argc != 5) {
+        Jim_WrongNumArgs(interp, 1, argv, "name arglist ?statics? body");
+        return JIM_ERR;
+    }
+    Jim_ListLength(interp, argv[2], &argListLen);
+    arityMin = arityMax = argListLen+1;
+    if (argListLen) {
+        const char *str;
+        int len;
+        Jim_Obj *lastArgPtr;
+        
+        Jim_ListIndex(interp, argv[2], argListLen-1, &lastArgPtr, JIM_NONE);
+        str = Jim_GetString(lastArgPtr, &len);
+        if (len == 4 && memcmp(str, "args", 4) == 0) {
+            arityMin--;
+            arityMax = -1;
+        }
+    }
+    if (argc == 4) {
+        return Jim_CreateProcedure(interp, Jim_GetString(argv[1], NULL),
+                argv[2], NULL, argv[3], arityMin, arityMax);
+    } else {
+        return Jim_CreateProcedure(interp, Jim_GetString(argv[1], NULL),
+                argv[2], argv[3], argv[4], arityMin, arityMax);
+    }
+}
+
+/* [concat] */
+static int Jim_ConcatCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_SetResult(interp, Jim_ConcatObj(interp, argc-1, argv+1));
+    return JIM_OK;
+}
+
+/* [upvar] */
+static int Jim_UpvarCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    const char *str;
+    int i;
+    Jim_CallFrame *targetCallFrame;
+
+    /* Lookup the target frame pointer */
+    str = Jim_GetString(argv[1], NULL);
+    if (argc > 3 && 
+        ((str[0] >= '0' && str[0] <= '9') || str[0] == '#'))
+    {
+        if (Jim_GetCallFrameByLevel(interp, argv[1],
+                    &targetCallFrame, NULL) != JIM_OK)
+            return JIM_ERR;
+        argc--;
+        argv++;
+    } else {
+        if (Jim_GetCallFrameByLevel(interp, NULL,
+                    &targetCallFrame, NULL) != JIM_OK)
+            return JIM_ERR;
+    }
+    /* Check for arity */
+    if (argc < 3 || ((argc-1)%2) != 0) {
+        Jim_WrongNumArgs(interp, 1, argv, "?level? otherVar localVar ?otherVar localVar ...?");
+        return JIM_ERR;
+    }
+    /* Now... for every other/local couple: */
+    for (i = 1; i < argc; i += 2) {
+        if (Jim_SetVariableLink(interp, argv[i+1], argv[i],
+                targetCallFrame) != JIM_OK) return JIM_ERR;
+    }
+    return JIM_OK;
+}
+
+/* [global] */
+static int Jim_GlobalCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int i;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "varName ?varName ...?");
+        return JIM_ERR;
+    }
+    /* Link every var to the toplevel having the same name */
+    if (interp->numLevels == 0) return JIM_OK; /* global at toplevel... */
+    for (i = 1; i < argc; i++) {
+        if (Jim_SetVariableLink(interp, argv[i], argv[i],
+                interp->topFramePtr) != JIM_OK) return JIM_ERR;
+    }
+    return JIM_OK;
+}
+
+/* does the [string map] operation. On error NULL is returned,
+ * otherwise a new string object with the result, having refcount = 0,
+ * is returned. */
+static Jim_Obj *JimStringMap(Jim_Interp *interp, Jim_Obj *mapListObjPtr,
+        Jim_Obj *objPtr, int nocase)
+{
+    int numMaps;
+    const char **key, *str, *noMatchStart = NULL;
+    Jim_Obj **value;
+    int *keyLen, strLen, i;
+    Jim_Obj *resultObjPtr;
+    
+    Jim_ListLength(interp, mapListObjPtr, &numMaps);
+    if (numMaps % 2) {
+        Jim_SetResultString(interp,
+                "list must contain an even number of elements", -1);
+        return NULL;
+    }
+    /* Initialization */
+    numMaps /= 2;
+    key = Jim_Alloc(sizeof(char*)*numMaps);
+    keyLen = Jim_Alloc(sizeof(int)*numMaps);
+    value = Jim_Alloc(sizeof(Jim_Obj*)*numMaps);
+    resultObjPtr = Jim_NewStringObj(interp, "", 0);
+    for (i = 0; i < numMaps; i++) {
+        Jim_Obj *eleObjPtr;
+
+        Jim_ListIndex(interp, mapListObjPtr, i*2, &eleObjPtr, JIM_NONE);
+        key[i] = Jim_GetString(eleObjPtr, &keyLen[i]);
+        Jim_ListIndex(interp, mapListObjPtr, i*2+1, &eleObjPtr, JIM_NONE);
+        value[i] = eleObjPtr;
+    }
+    str = Jim_GetString(objPtr, &strLen);
+    /* Map it */
+    while(strLen) {
+        for (i = 0; i < numMaps; i++) {
+            if (strLen >= keyLen[i] && keyLen[i]) {
+                if (!JimStringCompare(str, keyLen[i], key[i], keyLen[i],
+                            nocase))
+                {
+                    if (noMatchStart) {
+                        Jim_AppendString(interp, resultObjPtr,
+                                noMatchStart, str-noMatchStart);
+                        noMatchStart = NULL;
+                    }
+                    Jim_AppendObj(interp, resultObjPtr, value[i]);
+                    str += keyLen[i];
+                    strLen -= keyLen[i];
+                    break;
+                }
+            }
+        }
+        if (i == numMaps) { /* no match */
+            if (noMatchStart == NULL)
+                noMatchStart = str;
+            str ++;
+            strLen --;
+        }
+    }
+    if (noMatchStart) {
+        Jim_AppendString(interp, resultObjPtr,
+            noMatchStart, str-noMatchStart);
+    }
+    Jim_Free((void*)key);
+    Jim_Free(keyLen);
+    Jim_Free(value);
+    return resultObjPtr;
+}
+
+/* [string] */
+static int Jim_StringCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int option;
+    const char *options[] = {
+        "length", "compare", "match", "equal", "range", "map", "repeat",
+        "index", "first", "tolower", "toupper", NULL
+    };
+    enum {
+        OPT_LENGTH, OPT_COMPARE, OPT_MATCH, OPT_EQUAL, OPT_RANGE,
+        OPT_MAP, OPT_REPEAT, OPT_INDEX, OPT_FIRST, OPT_TOLOWER, OPT_TOUPPER
+    };
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
+        return JIM_ERR;
+    }
+    if (Jim_GetEnum(interp, argv[1], options, &option, "option",
+                JIM_ERRMSG) != JIM_OK)
+        return JIM_ERR;
+
+    if (option == OPT_LENGTH) {
+        int len;
+
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "string");
+            return JIM_ERR;
+        }
+        Jim_GetString(argv[2], &len);
+        Jim_SetResult(interp, Jim_NewIntObj(interp, len));
+        return JIM_OK;
+    } else if (option == OPT_COMPARE) {
+        int nocase = 0;
+        if ((argc != 4 && argc != 5) ||
+            (argc == 5 && Jim_CompareStringImmediate(interp,
+                argv[2], "-nocase") == 0)) {
+            Jim_WrongNumArgs(interp, 2, argv, "string1 string2");
+            return JIM_ERR;
+        }
+        if (argc == 5) {
+            nocase = 1;
+            argv++;
+        }
+        Jim_SetResult(interp, Jim_NewIntObj(interp,
+                    Jim_StringCompareObj(argv[2],
+                            argv[3], nocase)));
+        return JIM_OK;
+    } else if (option == OPT_MATCH) {
+        int nocase = 0;
+        if ((argc != 4 && argc != 5) ||
+            (argc == 5 && Jim_CompareStringImmediate(interp,
+                argv[2], "-nocase") == 0)) {
+            Jim_WrongNumArgs(interp, 2, argv, "?-nocase? pattern "
+                    "string");
+            return JIM_ERR;
+        }
+        if (argc == 5) {
+            nocase = 1;
+            argv++;
+        }
+        Jim_SetResult(interp,
+            Jim_NewIntObj(interp, Jim_StringMatchObj(argv[2],
+                    argv[3], nocase)));
+        return JIM_OK;
+    } else if (option == OPT_EQUAL) {
+        if (argc != 4) {
+            Jim_WrongNumArgs(interp, 2, argv, "string1 string2");
+            return JIM_ERR;
+        }
+        Jim_SetResult(interp,
+            Jim_NewIntObj(interp, Jim_StringEqObj(argv[2],
+                    argv[3], 0)));
+        return JIM_OK;
+    } else if (option == OPT_RANGE) {
+        Jim_Obj *objPtr;
+
+        if (argc != 5) {
+            Jim_WrongNumArgs(interp, 2, argv, "string first last");
+            return JIM_ERR;
+        }
+        objPtr = Jim_StringRangeObj(interp, argv[2], argv[3], argv[4]);
+        if (objPtr == NULL)
+            return JIM_ERR;
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    } else if (option == OPT_MAP) {
+        int nocase = 0;
+        Jim_Obj *objPtr;
+
+        if ((argc != 4 && argc != 5) ||
+            (argc == 5 && Jim_CompareStringImmediate(interp,
+                argv[2], "-nocase") == 0)) {
+            Jim_WrongNumArgs(interp, 2, argv, "?-nocase? mapList "
+                    "string");
+            return JIM_ERR;
+        }
+        if (argc == 5) {
+            nocase = 1;
+            argv++;
+        }
+        objPtr = JimStringMap(interp, argv[2], argv[3], nocase);
+        if (objPtr == NULL)
+            return JIM_ERR;
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    } else if (option == OPT_REPEAT) {
+        Jim_Obj *objPtr;
+        jim_wide count;
+
+        if (argc != 4) {
+            Jim_WrongNumArgs(interp, 2, argv, "string count");
+            return JIM_ERR;
+        }
+        if (Jim_GetWide(interp, argv[3], &count) != JIM_OK)
+            return JIM_ERR;
+        objPtr = Jim_NewStringObj(interp, "", 0);
+        while (count--) {
+            Jim_AppendObj(interp, objPtr, argv[2]);
+        }
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    } else if (option == OPT_INDEX) {
+        int index, len;
+        const char *str;
+
+        if (argc != 4) {
+            Jim_WrongNumArgs(interp, 2, argv, "string index");
+            return JIM_ERR;
+        }
+        if (Jim_GetIndex(interp, argv[3], &index) != JIM_OK)
+            return JIM_ERR;
+        str = Jim_GetString(argv[2], &len);
+        if (index != INT_MIN && index != INT_MAX)
+            index = JimRelToAbsIndex(len, index);
+        if (index < 0 || index >= len) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            return JIM_OK;
+        } else {
+            Jim_SetResult(interp, Jim_NewStringObj(interp, str+index, 1));
+            return JIM_OK;
+        }
+    } else if (option == OPT_FIRST) {
+        int index = 0, l1, l2;
+        const char *s1, *s2;
+
+        if (argc != 4 && argc != 5) {
+            Jim_WrongNumArgs(interp, 2, argv, "subString string ?startIndex?");
+            return JIM_ERR;
+        }
+        s1 = Jim_GetString(argv[2], &l1);
+        s2 = Jim_GetString(argv[3], &l2);
+        if (argc == 5) {
+            if (Jim_GetIndex(interp, argv[4], &index) != JIM_OK)
+                return JIM_ERR;
+            index = JimRelToAbsIndex(l2, index);
+        }
+        Jim_SetResult(interp, Jim_NewIntObj(interp,
+                    JimStringFirst(s1, l1, s2, l2, index)));
+        return JIM_OK;
+    } else if (option == OPT_TOLOWER) {
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "string");
+            return JIM_ERR;
+        }
+        Jim_SetResult(interp, JimStringToLower(interp, argv[2]));
+    } else if (option == OPT_TOUPPER) {
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "string");
+            return JIM_ERR;
+        }
+        Jim_SetResult(interp, JimStringToUpper(interp, argv[2]));
+    }
+    return JIM_OK;
+}
+
+/* [time] */
+static int Jim_TimeCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    long i, count = 1;
+    jim_wide start, elapsed;
+    char buf [256];
+    const char *fmt = "%" JIM_WIDE_MODIFIER " microseconds per iteration";
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "script ?count?");
+        return JIM_ERR;
+    }
+    if (argc == 3) {
+        if (Jim_GetLong(interp, argv[2], &count) != JIM_OK)
+            return JIM_ERR;
+    }
+    if (count < 0)
+        return JIM_OK;
+    i = count;
+    start = JimClock();
+    while (i-- > 0) {
+        int retval;
+
+        if ((retval = Jim_EvalObj(interp, argv[1])) != JIM_OK)
+            return retval;
+    }
+    elapsed = JimClock() - start;
+    sprintf(buf, fmt, elapsed/count);
+    Jim_SetResultString(interp, buf, -1);
+    return JIM_OK;
+}
+
+/* [exit] */
+static int Jim_ExitCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    long exitCode = 0;
+
+    if (argc > 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "?exitCode?");
+        return JIM_ERR;
+    }
+    if (argc == 2) {
+        if (Jim_GetLong(interp, argv[1], &exitCode) != JIM_OK)
+            return JIM_ERR;
+    }
+    interp->exitCode = exitCode;
+    return JIM_EXIT;
+}
+
+/* [catch] */
+static int Jim_CatchCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int exitCode = 0;
+
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "script ?varName?");
+        return JIM_ERR;
+    }
+    exitCode = Jim_EvalObj(interp, argv[1]);
+    if (argc == 3) {
+        if (Jim_SetVariable(interp, argv[2], Jim_GetResult(interp))
+                != JIM_OK)
+            return JIM_ERR;
+    }
+    Jim_SetResult(interp, Jim_NewIntObj(interp, exitCode));
+    return JIM_OK;
+}
+
+/* [ref] */
+static int Jim_RefCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc != 3 && argc != 4) {
+        Jim_WrongNumArgs(interp, 1, argv, "string tag ?finalizer?");
+        return JIM_ERR;
+    }
+    if (argc == 3) {
+        Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2], NULL));
+    } else {
+        Jim_SetResult(interp, Jim_NewReference(interp, argv[1], argv[2],
+                    argv[3]));
+    }
+    return JIM_OK;
+}
+
+/* [getref] */
+static int Jim_GetrefCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_Reference *refPtr;
+
+    if (argc != 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "reference");
+        return JIM_ERR;
+    }
+    if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
+        return JIM_ERR;
+    Jim_SetResult(interp, refPtr->objPtr);
+    return JIM_OK;
+}
+
+/* [setref] */
+static int Jim_SetrefCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    Jim_Reference *refPtr;
+
+    if (argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "reference newValue");
+        return JIM_ERR;
+    }
+    if ((refPtr = Jim_GetReference(interp, argv[1])) == NULL)
+        return JIM_ERR;
+    Jim_IncrRefCount(argv[2]);
+    Jim_DecrRefCount(interp, refPtr->objPtr);
+    refPtr->objPtr = argv[2];
+    Jim_SetResult(interp, argv[2]);
+    return JIM_OK;
+}
+
+/* [collect] */
+static int Jim_CollectCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc != 1) {
+        Jim_WrongNumArgs(interp, 1, argv, "");
+        return JIM_ERR;
+    }
+    Jim_SetResult(interp, Jim_NewIntObj(interp, Jim_Collect(interp)));
+    return JIM_OK;
+}
+
+/* [finalize] reference ?newValue? */
+static int Jim_FinalizeCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "reference ?finalizerProc?");
+        return JIM_ERR;
+    }
+    if (argc == 2) {
+        Jim_Obj *cmdNamePtr;
+
+        if (Jim_GetFinalizer(interp, argv[1], &cmdNamePtr) != JIM_OK)
+            return JIM_ERR;
+        if (cmdNamePtr != NULL) /* otherwise the null string is returned. */
+            Jim_SetResult(interp, cmdNamePtr);
+    } else {
+        if (Jim_SetFinalizer(interp, argv[1], argv[2]) != JIM_OK)
+            return JIM_ERR;
+        Jim_SetResult(interp, argv[2]);
+    }
+    return JIM_OK;
+}
+
+/* TODO */
+/* [info references] (list of all the references/finalizers) */
+
+/* [rename] */
+static int Jim_RenameCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    const char *oldName, *newName;
+
+    if (argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "oldName newName");
+        return JIM_ERR;
+    }
+    oldName = Jim_GetString(argv[1], NULL);
+    newName = Jim_GetString(argv[2], NULL);
+    if (Jim_RenameCommand(interp, oldName, newName) != JIM_OK) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "can't rename \"", oldName, "\": ",
+            "command doesn't exist", NULL);
+        return JIM_ERR;
+    }
+    return JIM_OK;
+}
+
+/* [dict] */
+static int Jim_DictCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int option;
+    const char *options[] = {
+        "create", "get", "set", "unset", "exists", NULL
+    };
+    enum {
+        OPT_CREATE, OPT_GET, OPT_SET, OPT_UNSET, OPT_EXIST
+    };
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
+        return JIM_ERR;
+    }
+
+    if (Jim_GetEnum(interp, argv[1], options, &option, "option",
+                JIM_ERRMSG) != JIM_OK)
+        return JIM_ERR;
+
+    if (option == OPT_CREATE) {
+        Jim_Obj *objPtr;
+
+        if (argc % 2) {
+            Jim_WrongNumArgs(interp, 2, argv, "?key value ...?");
+            return JIM_ERR;
+        }
+        objPtr = Jim_NewDictObj(interp, argv+2, argc-2);
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    } else if (option == OPT_GET) {
+        Jim_Obj *objPtr;
+
+        if (Jim_DictKeysVector(interp, argv[2], argv+3, argc-3, &objPtr,
+                JIM_ERRMSG) != JIM_OK)
+            return JIM_ERR;
+        Jim_SetResult(interp, objPtr);
+        return JIM_OK;
+    } else if (option == OPT_SET) {
+        if (argc < 5) {
+            Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...? value");
+            return JIM_ERR;
+        }
+        return Jim_SetDictKeysVector(interp, argv[2], argv+3, argc-4,
+                    argv[argc-1]);
+    } else if (option == OPT_UNSET) {
+        if (argc < 4) {
+            Jim_WrongNumArgs(interp, 2, argv, "varName key ?key ...?");
+            return JIM_ERR;
+        }
+        return Jim_SetDictKeysVector(interp, argv[2], argv+3, argc-3,
+                    NULL);
+    } else if (option == OPT_EXIST) {
+        Jim_Obj *objPtr;
+        int exists;
+
+        if (Jim_DictKeysVector(interp, argv[2], argv+3, argc-3, &objPtr,
+                JIM_ERRMSG) == JIM_OK)
+            exists = 1;
+        else
+            exists = 0;
+        Jim_SetResult(interp, Jim_NewIntObj(interp, exists));
+        return JIM_OK;
+    } else {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+            "bad option \"", Jim_GetString(argv[1], NULL), "\":",
+            " must be create, get, set", NULL);
+        return JIM_ERR;
+    }
+    return JIM_OK;
+}
+
+/* [load] */
+static int Jim_LoadCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "libaryFile");
+        return JIM_ERR;
+    }
+    return Jim_LoadLibrary(interp, Jim_GetString(argv[1], NULL));
+}
+
+/* [subst] */
+static int Jim_SubstCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int i, flags = 0;
+    Jim_Obj *objPtr;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv,
+            "?-nobackslashes? ?-nocommands? ?-novariables? string");
+        return JIM_ERR;
+    }
+    i = argc-2;
+    while(i--) {
+        if (Jim_CompareStringImmediate(interp, argv[i+1],
+                    "-nobackslashes"))
+            flags |= JIM_SUBST_NOESC;
+        else if (Jim_CompareStringImmediate(interp, argv[i+1],
+                    "-novariables"))
+            flags |= JIM_SUBST_NOVAR;
+        else if (Jim_CompareStringImmediate(interp, argv[i+1],
+                    "-nocommands"))
+            flags |= JIM_SUBST_NOCMD;
+        else {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "bad option \"", Jim_GetString(argv[i+1], NULL),
+                "\": must be -nobackslashes, -nocommands, or "
+                "-novariables", NULL);
+            return JIM_ERR;
+        }
+    }
+    if (Jim_SubstObj(interp, argv[argc-1], &objPtr, flags) != JIM_OK)
+        return JIM_ERR;
+    Jim_SetResult(interp, objPtr);
+    return JIM_OK;
+}
+
+/* [info] */
+static int Jim_InfoCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int cmd, result = JIM_OK;
+    static const char *commands[] = {
+        "body", "commands", "exists", "globals", "level", "locals",
+        "vars", "version", "complete", "args", NULL
+    };
+    enum {INFO_BODY, INFO_COMMANDS, INFO_EXISTS, INFO_GLOBALS, INFO_LEVEL,
+          INFO_LOCALS, INFO_VARS, INFO_VERSION, INFO_COMPLETE, INFO_ARGS};
+    
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "command ?args ...?");
+        return JIM_ERR;
+    }
+    if (Jim_GetEnum(interp, argv[1], commands, &cmd, "command", JIM_ERRMSG)
+        != JIM_OK) {
+        return JIM_ERR;
+    }
+    
+    if (cmd == INFO_COMMANDS) {
+        if (argc != 2 && argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
+            return JIM_ERR;
+        }
+        if (argc == 3)
+            Jim_SetResult(interp,JimCommandsList(interp, argv[2]));
+        else
+            Jim_SetResult(interp, JimCommandsList(interp, NULL));
+    } else if (cmd == INFO_EXISTS) {
+        Jim_Obj *exists;
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "varName");
+            return JIM_ERR;
+        }
+        exists = Jim_GetVariable(interp, argv[2], 0);
+        Jim_SetResult(interp, Jim_NewIntObj(interp, exists != 0));
+    } else if (cmd == INFO_GLOBALS || cmd == INFO_LOCALS || cmd == INFO_VARS) {
+        int mode;
+        switch (cmd) {
+            case INFO_GLOBALS: mode = JIM_VARLIST_GLOBALS; break;
+            case INFO_LOCALS:  mode = JIM_VARLIST_LOCALS; break;
+            case INFO_VARS:    mode = JIM_VARLIST_VARS; break;
+            default: mode = 0; /* avoid warning */; break;
+        }
+        if (argc != 2 && argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "?pattern?");
+            return JIM_ERR;
+        }
+        if (argc == 3)
+            Jim_SetResult(interp,JimVariablesList(interp, argv[2], mode));
+        else
+            Jim_SetResult(interp, JimVariablesList(interp, NULL, mode));
+    } else if (cmd == INFO_LEVEL) {
+        Jim_Obj *objPtr;
+        switch (argc) {
+            case 2:
+                Jim_SetResult(interp,
+                              Jim_NewIntObj(interp, interp->numLevels));
+                break;
+            case 3:
+                if (JimInfoLevel(interp, argv[2], &objPtr) != JIM_OK)
+                    return JIM_ERR;
+                Jim_SetResult(interp, objPtr);
+                break;
+            default:
+                Jim_WrongNumArgs(interp, 2, argv, "?levelNum?");
+                return JIM_ERR;
+        }
+    } else if (cmd == INFO_BODY || cmd == INFO_ARGS) {
+        Jim_Cmd *cmdPtr;
+
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "procname");
+            return JIM_ERR;
+        }
+        if ((cmdPtr = Jim_GetCommand(interp, argv[2], JIM_ERRMSG)) == NULL)
+            return JIM_ERR;
+        if (cmdPtr->cmdProc != NULL) {
+            Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+            Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "command \"", Jim_GetString(argv[2], NULL),
+                "\" is not a procedure", NULL);
+            return JIM_ERR;
+        }
+        if (cmd == INFO_BODY)
+            Jim_SetResult(interp, cmdPtr->bodyObjPtr);
+        else
+            Jim_SetResult(interp, cmdPtr->argListObjPtr);
+    } else if (cmd == INFO_VERSION) {
+        char buf[(JIM_INTEGER_SPACE * 2) + 1];
+        sprintf(buf, "%d.%d", 
+                JIM_VERSION / 100, JIM_VERSION % 100);
+        Jim_SetResultString(interp, buf, -1);
+    } else if (cmd == INFO_COMPLETE) {
+        const char *s;
+        int len;
+
+        if (argc != 3) {
+            Jim_WrongNumArgs(interp, 2, argv, "script");
+            return JIM_ERR;
+        }
+        s = Jim_GetString(argv[2], &len);
+        Jim_SetResult(interp,
+                Jim_NewIntObj(interp, Jim_ScriptIsComplete(s, len, NULL)));
+    }
+    return result;
+}
+
+/* [split] */
+static int Jim_SplitCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    const char *str, *splitChars, *noMatchStart;
+    int splitLen, strLen, i;
+    Jim_Obj *resObjPtr;
+
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "string ?splitChars?");
+        return JIM_ERR;
+    }
+    /* Init */
+    if (argc == 2) {
+        splitChars = " \n\t\r";
+        splitLen = 4;
+    } else {
+        splitChars = Jim_GetString(argv[2], &splitLen);
+    }
+    str = Jim_GetString(argv[1], &strLen);
+    if (!strLen) return JIM_OK;
+    noMatchStart = str;
+    resObjPtr = Jim_NewListObj(interp, NULL, 0);
+    /* Split */
+    if (splitLen) {
+        while (strLen) {
+            for (i = 0; i < splitLen; i++) {
+                if (*str == splitChars[i]) {
+                    Jim_Obj *objPtr;
+
+                    objPtr = Jim_NewStringObj(interp, noMatchStart,
+                            (str-noMatchStart));
+                    Jim_ListAppendElement(interp, resObjPtr, objPtr);
+                    noMatchStart = str+1;
+                    break;
+                }
+            }
+            str ++;
+            strLen --;
+        }
+        Jim_ListAppendElement(interp, resObjPtr,
+                Jim_NewStringObj(interp, noMatchStart, (str-noMatchStart)));
+    } else {
+        /* This handles the special case of splitchars eq {}. This
+         * is trivial but we want to perform object sharing as Tcl does. */
+        Jim_Obj *objCache[256];
+        const unsigned char *u = (unsigned char*) str;
+        memset(objCache, 0, sizeof(objCache));
+        for (i = 0; i < strLen; i++) {
+            int c = u[i];
+            
+            if (objCache[c] == NULL)
+                objCache[c] = Jim_NewStringObj(interp, (char*)u+i, 1);
+            Jim_ListAppendElement(interp, resObjPtr, objCache[c]);
+        }
+    }
+    Jim_SetResult(interp, resObjPtr);
+    return JIM_OK;
+}
+
+/* [join] */
+static int Jim_JoinCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    const char *joinStr;
+    int joinStrLen, i, listLen;
+    Jim_Obj *resObjPtr;
+
+    if (argc != 2 && argc != 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "list ?joinString?");
+        return JIM_ERR;
+    }
+    /* Init */
+    if (argc == 2) {
+        joinStr = " ";
+        joinStrLen = 1;
+    } else {
+        joinStr = Jim_GetString(argv[2], &joinStrLen);
+    }
+    Jim_ListLength(interp, argv[1], &listLen);
+    resObjPtr = Jim_NewStringObj(interp, NULL, 0);
+    /* Split */
+    for (i = 0; i < listLen; i++) {
+        Jim_Obj *objPtr;
+
+        Jim_ListIndex(interp, argv[1], i, &objPtr, JIM_NONE);
+        Jim_AppendObj(interp, resObjPtr, objPtr);
+        if (i+1 != listLen) {
+            Jim_AppendString(interp, resObjPtr, joinStr, joinStrLen);
+        }
+    }
+    Jim_SetResult(interp, resObjPtr);
+    return JIM_OK;
+}
+
+/* [format] */
+static int Jim_FormatCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *objPtr;
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "formatString ?arg arg ...?");
+        return JIM_ERR;
+    }
+    objPtr = Jim_FormatString(interp, argv[1], argc-2, argv+2);
+    if (objPtr == NULL)
+        return JIM_ERR;
+    Jim_SetResult(interp, objPtr);
+    return JIM_OK;
+}
+
+/* [scan] */
+static int Jim_ScanCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *listPtr, **outVec;
+    int outc, i, count = 0;
+
+    if (argc < 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "string formatString ?varName ...?");
+        return JIM_ERR;
+    } 
+    if (argv[2]->typePtr != &scanFmtStringObjType)
+        SetScanFmtFromAny(interp, argv[2]);
+    if (FormatGetError(argv[2]) != 0) {
+        Jim_SetResultString(interp, FormatGetError(argv[2]), -1);
+        return JIM_ERR;
+    }
+    if (argc > 3) {
+        int maxPos = FormatGetMaxPos(argv[2]);
+        int count = FormatGetCnvCount(argv[2]);
+        if (maxPos > argc-3) {
+            Jim_SetResultString(interp, "\"%n$\" argument index out of range", -1);
+            return JIM_ERR;
+        } else if (count != 0 && count < argc-3) {
+            Jim_SetResultString(interp, "variable is not assigned by any "
+                "conversion specifiers", -1);
+            return JIM_ERR;
+        } else if (count > argc-3) {
+            Jim_SetResultString(interp, "different numbers of variable names and "
+                "field specifiers", -1);
+            return JIM_ERR;
+        }
+    } 
+    listPtr = Jim_ScanString(interp, argv[1], argv[2], JIM_ERRMSG);
+    if (listPtr == 0)
+        return JIM_ERR;
+    if (argc > 3) {
+        int len = 0;
+        if (listPtr != 0 && listPtr != (Jim_Obj*)EOF)
+            Jim_ListLength(interp, listPtr, &len);
+        if (listPtr == (Jim_Obj*)EOF || len == 0) { // XXX
+            Jim_SetResult(interp, Jim_NewIntObj(interp, -1));
+            return JIM_OK;
+        }
+        JimListGetElements(interp, listPtr, &outc, &outVec);
+        for (i = 0; i < outc; ++i) {
+            if (Jim_Length(outVec[i]) > 0) {
+                ++count;
+                if (Jim_SetVariable(interp, argv[3+i], outVec[i]) != JIM_OK)
+                    goto err;
+            }
+        }
+        Jim_FreeNewObj(interp, listPtr);
+        Jim_SetResult(interp, Jim_NewIntObj(interp, count));
+    } else {
+        if (listPtr == (Jim_Obj*)EOF) {
+            Jim_SetResult(interp, Jim_NewListObj(interp, 0, 0));
+            return JIM_OK;
+        }
+        Jim_SetResult(interp, listPtr);
+    }
+    return JIM_OK;
+err:
+    Jim_FreeNewObj(interp, listPtr);
+    return JIM_ERR;
+}
+
+/* [error] */
+static int Jim_ErrorCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    if (argc != 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "message");
+        return JIM_ERR;
+    }
+    Jim_SetResult(interp, argv[1]);
+    return JIM_ERR;
+}
+
+/* [lrange] */
+static int Jim_LrangeCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *objPtr;
+
+    if (argc != 4) {
+        Jim_WrongNumArgs(interp, 1, argv, "list first last");
+        return JIM_ERR;
+    }
+    if ((objPtr = Jim_ListRange(interp, argv[1], argv[2], argv[3])) == NULL)
+        return JIM_ERR;
+    Jim_SetResult(interp, objPtr);
+    return JIM_OK;
+}
+
+/* [env] */
+static int Jim_EnvCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    const char *key;
+    char *val;
+
+    if (argc != 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "varName");
+        return JIM_ERR;
+    }
+    key = Jim_GetString(argv[1], NULL);
+    val = getenv(key);
+    if (val == NULL) {
+        Jim_SetResult(interp, Jim_NewEmptyStringObj(interp));
+        Jim_AppendStrings(interp, Jim_GetResult(interp),
+                "environment variable \"",
+                key, "\" does not exist", NULL);
+        return JIM_ERR;
+    }
+    Jim_SetResult(interp, Jim_NewStringObj(interp, val, -1));
+    return JIM_OK;
+}
+
+/* [source] */
+static int Jim_SourceCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    int retval;
+
+    if (argc != 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "fileName");
+        return JIM_ERR;
+    }
+    retval = Jim_EvalFile(interp, Jim_GetString(argv[1], NULL));
+    if (retval == JIM_RETURN)
+        return JIM_OK;
+    return retval;
+}
+
+/* [lreverse] */
+static int Jim_LreverseCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    Jim_Obj *revObjPtr, **ele;
+    int len;
+
+    if (argc != 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "list");
+        return JIM_ERR;
+    }
+    JimListGetElements(interp, argv[1], &len, &ele);
+    len--;
+    revObjPtr = Jim_NewListObj(interp, NULL, 0);
+    while (len >= 0)
+        ListAppendElement(revObjPtr, ele[len--]);
+    Jim_SetResult(interp, revObjPtr);
+    return JIM_OK;
+}
+
+static int JimRangeLen(jim_wide start, jim_wide end, jim_wide step)
+{
+    jim_wide len;
+
+    if (step == 0) return -1;
+    if (start == end) return 0;
+    else if (step > 0 && start > end) return -1;
+    else if (step < 0 && end > start) return -1;
+    len = end-start;
+    if (len < 0) len = -len; /* abs(len) */
+    if (step < 0) step = -step; /* abs(step) */
+    len = 1 + ((len-1)/step);
+    /* We can truncate safely to INT_MAX, the range command
+     * will always return an error for a such long range
+     * because Tcl lists can't be so long. */
+    if (len > INT_MAX) len = INT_MAX;
+    return (int)((len < 0) ? -1 : len);
+}
+
+/* [range] */
+static int Jim_RangeCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    jim_wide start = 0, end, step = 1;
+    int len, i;
+    Jim_Obj *objPtr;
+
+    if (argc < 2 || argc > 4) {
+        Jim_WrongNumArgs(interp, 1, argv, "?start? end ?step?");
+        return JIM_ERR;
+    }
+    if (argc == 2) {
+        if (Jim_GetWide(interp, argv[1], &end) != JIM_OK)
+            return JIM_ERR;
+    } else {
+        if (Jim_GetWide(interp, argv[1], &start) != JIM_OK ||
+            Jim_GetWide(interp, argv[2], &end) != JIM_OK)
+            return JIM_ERR;
+        if (argc == 4 && Jim_GetWide(interp, argv[3], &step) != JIM_OK)
+            return JIM_ERR;
+    }
+    if ((len = JimRangeLen(start, end, step)) == -1) {
+        Jim_SetResultString(interp, "Invalid (infinite?) range specified", -1);
+        return JIM_ERR;
+    }
+    objPtr = Jim_NewListObj(interp, NULL, 0);
+    for (i = 0; i < len; i++)
+        ListAppendElement(objPtr, Jim_NewIntObj(interp, start+i*step));
+    Jim_SetResult(interp, objPtr);
+    return JIM_OK;
+}
+
+/* [rand] */
+static int Jim_RandCoreCommand(Jim_Interp *interp, int argc,
+        Jim_Obj *const *argv)
+{
+    jim_wide min = 0, max, len, maxMul;
+
+    if (argc < 1 || argc > 3) {
+        Jim_WrongNumArgs(interp, 1, argv, "?min? max");
+        return JIM_ERR;
+    }
+    if (argc == 1) {
+        max = JIM_WIDE_MAX;
+    } else if (argc == 2) {
+        if (Jim_GetWide(interp, argv[1], &max) != JIM_OK)
+            return JIM_ERR;
+    } else if (argc == 3) {
+        if (Jim_GetWide(interp, argv[1], &min) != JIM_OK ||
+            Jim_GetWide(interp, argv[2], &max) != JIM_OK)
+            return JIM_ERR;
+    }
+    len = max-min;
+    if (len < 0) {
+        Jim_SetResultString(interp, "Invalid arguments (max < min)", -1);
+        return JIM_ERR;
+    }
+    maxMul = JIM_WIDE_MAX - (len ? (JIM_WIDE_MAX%len) : 0);
+    while (1) {
+        jim_wide r;
+
+        JimRandomBytes(interp, &r, sizeof(jim_wide));
+        if (r < 0 || r >= maxMul) continue;
+        r = (len == 0) ? 0 : r%len;
+        Jim_SetResult(interp, Jim_NewIntObj(interp, min+r));
+        return JIM_OK;
+    }
+}
+
+/* [package] */
+static int Jim_PackageCoreCommand(Jim_Interp *interp, int argc, 
+        Jim_Obj *const *argv)
+{
+    int option;
+    const char *options[] = {
+        "require", "provide", NULL
+    };
+    enum {OPT_REQUIRE, OPT_PROVIDE};
+
+    if (argc < 2) {
+        Jim_WrongNumArgs(interp, 1, argv, "option ?arguments ...?");
+        return JIM_ERR;
+    }
+    if (Jim_GetEnum(interp, argv[1], options, &option, "option",
+                JIM_ERRMSG) != JIM_OK)
+        return JIM_ERR;
+
+    if (option == OPT_REQUIRE) {
+        int exact = 0;
+        const char *ver;
+
+        if (Jim_CompareStringImmediate(interp, argv[2], "-exact")) {
+            exact = 1;
+            argv++;
+            argc--;
+        }
+        if (argc != 3 && argc != 4) {
+            Jim_WrongNumArgs(interp, 2, argv, "?-exact? package ?version?");
+            return JIM_ERR;
+        }
+        ver = Jim_PackageRequire(interp, Jim_GetString(argv[2], NULL),
+                argc == 4 ? Jim_GetString(argv[3], NULL) : "",
+                JIM_ERRMSG);
+        if (ver == NULL)
+            return JIM_ERR;
+        Jim_SetResultString(interp, ver, -1);
+    } else if (option == OPT_PROVIDE) {
+        if (argc != 4) {
+            Jim_WrongNumArgs(interp, 2, argv, "package version");
+            return JIM_ERR;
+        }
+        return Jim_PackageProvide(interp, Jim_GetString(argv[2], NULL),
+                    Jim_GetString(argv[3], NULL), JIM_ERRMSG);
+    }
+    return JIM_OK;
+}
+
+static struct {
+    const char *name;
+    Jim_CmdProc cmdProc;
+} Jim_CoreCommandsTable[] = {
+    {"set", Jim_SetCoreCommand},
+    {"unset", Jim_UnsetCoreCommand},
+    {"puts", Jim_PutsCoreCommand},
+    {"+", Jim_AddCoreCommand},
+    {"*", Jim_MulCoreCommand},
+    {"-", Jim_SubCoreCommand},
+    {"/", Jim_DivCoreCommand},
+    {"incr", Jim_IncrCoreCommand},
+    {"while", Jim_WhileCoreCommand},
+    {"for", Jim_ForCoreCommand},
+    {"foreach", Jim_ForeachCoreCommand},
+    {"lmap", Jim_LmapCoreCommand},
+    {"if", Jim_IfCoreCommand},
+    {"switch", Jim_SwitchCoreCommand},
+    {"list", Jim_ListCoreCommand},
+    {"lindex", Jim_LindexCoreCommand},
+    {"lset", Jim_LsetCoreCommand},
+    {"llength", Jim_LlengthCoreCommand},
+    {"lappend", Jim_LappendCoreCommand},
+    {"linsert", Jim_LinsertCoreCommand},
+    {"lsort", Jim_LsortCoreCommand},
+    {"append", Jim_AppendCoreCommand},
+    {"debug", Jim_DebugCoreCommand},
+    {"eval", Jim_EvalCoreCommand},
+    {"uplevel", Jim_UplevelCoreCommand},
+    {"expr", Jim_ExprCoreCommand},
+    {"break", Jim_BreakCoreCommand},
+    {"continue", Jim_ContinueCoreCommand},
+    {"proc", Jim_ProcCoreCommand},
+    {"concat", Jim_ConcatCoreCommand},
+    {"return", Jim_ReturnCoreCommand},
+    {"upvar", Jim_UpvarCoreCommand},
+    {"global", Jim_GlobalCoreCommand},
+    {"string", Jim_StringCoreCommand},
+    {"time", Jim_TimeCoreCommand},
+    {"exit", Jim_ExitCoreCommand},
+    {"catch", Jim_CatchCoreCommand},
+    {"ref", Jim_RefCoreCommand},
+    {"getref", Jim_GetrefCoreCommand},
+    {"setref", Jim_SetrefCoreCommand},
+    {"finalize", Jim_FinalizeCoreCommand},
+    {"collect", Jim_CollectCoreCommand},
+    {"rename", Jim_RenameCoreCommand},
+    {"dict", Jim_DictCoreCommand},
+    {"load", Jim_LoadCoreCommand},
+    {"subst", Jim_SubstCoreCommand},
+    {"info", Jim_InfoCoreCommand},
+    {"split", Jim_SplitCoreCommand},
+    {"join", Jim_JoinCoreCommand},
+    {"format", Jim_FormatCoreCommand},
+    {"scan", Jim_ScanCoreCommand},
+    {"error", Jim_ErrorCoreCommand},
+    {"lrange", Jim_LrangeCoreCommand},
+    {"env", Jim_EnvCoreCommand},
+    {"source", Jim_SourceCoreCommand},
+    {"lreverse", Jim_LreverseCoreCommand},
+    {"range", Jim_RangeCoreCommand},
+    {"rand", Jim_RandCoreCommand},
+    {"package", Jim_PackageCoreCommand},
+    {"tailcall", Jim_TailcallCoreCommand},
+    {NULL, NULL},
+};
+
+/* Some Jim core command is actually a procedure written in Jim itself. */
+static void Jim_RegisterCoreProcedures(Jim_Interp *interp)
+{
+    Jim_Eval(interp, (char*)
+"proc lambda {arglist args} {\n"
+"    set name [ref {} function lambdaFinalizer]\n"
+"    uplevel 1 [list proc $name $arglist {expand}$args]\n"
+"    return $name\n"
+"}\n"
+"proc lambdaFinalizer {name val} {\n"
+"    rename $name {}\n"
+"}\n"
+    );
+}
+
+void Jim_RegisterCoreCommands(Jim_Interp *interp)
+{
+    int i = 0;
+
+    while(Jim_CoreCommandsTable[i].name != NULL) {
+        Jim_CreateCommand(interp, 
+                Jim_CoreCommandsTable[i].name,
+                Jim_CoreCommandsTable[i].cmdProc,
+                NULL, NULL);
+        i++;
+    }
+    Jim_RegisterCoreProcedures(interp);
+}
+
+/* -----------------------------------------------------------------------------
+ * Interactive prompt
+ * ---------------------------------------------------------------------------*/
+void Jim_PrintErrorMessage(Jim_Interp *interp)
+{
+    int len, i;
+
+    fprintf(interp->stderr, "Runtime error, file \"%s\", line %d:" JIM_NL,
+            interp->errorFileName, interp->errorLine);
+    fprintf(interp->stderr, "    %s" JIM_NL,
+            Jim_GetString(interp->result, NULL));
+    Jim_ListLength(interp, interp->stackTrace, &len);
+    for (i = 0; i < len; i+= 3) {
+        Jim_Obj *objPtr;
+        const char *proc, *file, *line;
+
+        Jim_ListIndex(interp, interp->stackTrace, i, &objPtr, JIM_NONE);
+        proc = Jim_GetString(objPtr, NULL);
+        Jim_ListIndex(interp, interp->stackTrace, i+1, &objPtr,
+                JIM_NONE);
+        file = Jim_GetString(objPtr, NULL);
+        Jim_ListIndex(interp, interp->stackTrace, i+2, &objPtr,
+                JIM_NONE);
+        line = Jim_GetString(objPtr, NULL);
+        fprintf(interp->stderr,
+                "In procedure '%s' called at file \"%s\", line %s" JIM_NL,
+                proc, file, line);
+    }
+}
+
+int Jim_InteractivePrompt(Jim_Interp *interp)
+{
+    int retcode = JIM_OK;
+    Jim_Obj *scriptObjPtr;
+
+    fprintf(interp->stdout, "Welcome to Jim version %d.%d, "
+           "Copyright (c) 2005 Salvatore Sanfilippo" JIM_NL,
+           JIM_VERSION / 100, JIM_VERSION % 100);
+    fprintf(interp->stdout,
+            "CVS ID: $Id$"
+            JIM_NL);
+    Jim_SetVariableStrWithStr(interp, "jim_interactive", "1");
+    while (1) {
+        char buf[1024];
+        const char *result;
+        const char *retcodestr[] = {
+            "ok", "error", "return", "break", "continue", "eval", "exit"
+        };
+        int reslen;
+
+        if (retcode != 0) {
+            if (retcode >= 2 && retcode <= 6)
+                fprintf(interp->stdout, "[%s] . ", retcodestr[retcode]);
+            else
+                fprintf(interp->stdout, "[%d] . ", retcode);
+        } else
+            fprintf(interp->stdout, ". ");
+        fflush(interp->stdout);
+        scriptObjPtr = Jim_NewStringObj(interp, "", 0);
+        Jim_IncrRefCount(scriptObjPtr);
+        while(1) {
+            const char *str;
+            char state;
+            int len;
+
+            if (fgets(buf, 1024, interp->stdin) == NULL) {
+                Jim_DecrRefCount(interp, scriptObjPtr);
+                goto out;
+            }
+            Jim_AppendString(interp, scriptObjPtr, buf, -1);
+            str = Jim_GetString(scriptObjPtr, &len);
+            if (Jim_ScriptIsComplete(str, len, &state))
+                break;
+            fprintf(interp->stdout, "%c> ", state);
+            fflush(stdout);
+        }
+        retcode = Jim_EvalObj(interp, scriptObjPtr);
+        Jim_DecrRefCount(interp, scriptObjPtr);
+        result = Jim_GetString(Jim_GetResult(interp), &reslen);
+        if (retcode == JIM_ERR) {
+            Jim_PrintErrorMessage(interp);
+        } else if (retcode == JIM_EXIT) {
+            exit(Jim_GetExitCode(interp));
+        } else {
+            if (reslen) {
+                fwrite(result, 1, reslen, interp->stdout);
+                fprintf(interp->stdout, JIM_NL);
+            }
+        }
+    }
+out:
+    return 0;
+}
diff --git a/packages/net/athttpd/v2_0/src/md5c.c b/packages/net/athttpd/v2_0/src/md5c.c
new file mode 100644 (file)
index 0000000..c5fcbe4
--- /dev/null
@@ -0,0 +1,331 @@
+/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm
+ */
+
+/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
+   rights reserved.
+
+   License to copy and use this software is granted provided that it
+   is identified as the "RSA Data Security, Inc. MD5 Message-Digest
+   Algorithm" in all material mentioning or referencing this software
+   or this function.
+
+   License is also granted to make and use derivative works provided
+   that such works are identified as "derived from the RSA Data
+   Security, Inc. MD5 Message-Digest Algorithm" in all material
+   mentioning or referencing the derived work.  
+                                                                    
+   RSA Data Security, Inc. makes no representations concerning either
+   the merchantability of this software or the suitability of this
+   software for any particular purpose. It is provided "as is"
+   without express or implied warranty of any kind.  
+                                                                    
+   These notices must be retained in any copies of any part of this
+   documentation and/or software.  
+ */
+
+#include <cyg/athttpd/md5.h>
+
+/* Constants for MD5Transform routine.
+ */
+#define S11 7
+#define S12 12
+#define S13 17
+#define S14 22
+#define S21 5
+#define S22 9
+#define S23 14
+#define S24 20
+#define S31 4
+#define S32 11
+#define S33 16
+#define S34 23
+#define S41 6
+#define S42 10
+#define S43 15
+#define S44 21
+
+static void MD5Transform (UINT4 [4], unsigned char [64]);
+static void Encode(unsigned char *, UINT4 *, unsigned int);
+static void Decode(UINT4 *, unsigned char *, unsigned int);
+static void MD5_memcpy(POINTER, POINTER, unsigned int);
+static void MD5_memset(POINTER, int, unsigned int);
+
+static unsigned char PADDING[64] = {
+  0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/* F, G, H and I are basic MD5 functions.
+ */
+#define F(x, y, z) (((x) & (y)) | ((~x) & (z)))
+#define G(x, y, z) (((x) & (z)) | ((y) & (~z)))
+#define H(x, y, z) ((x) ^ (y) ^ (z))
+#define I(x, y, z) ((y) ^ ((x) | (~z)))
+
+/* ROTATE_LEFT rotates x left n bits.
+ */
+#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
+
+/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
+   Rotation is separate from addition to prevent recomputation.
+ */
+#define FF(a, b, c, d, x, s, ac) { \
+    (a) += F ((b), (c), (d)) + (x) + (UINT4)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+#define GG(a, b, c, d, x, s, ac) { \
+    (a) += G ((b), (c), (d)) + (x) + (UINT4)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+#define HH(a, b, c, d, x, s, ac) { \
+    (a) += H ((b), (c), (d)) + (x) + (UINT4)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+#define II(a, b, c, d, x, s, ac) { \
+    (a) += I ((b), (c), (d)) + (x) + (UINT4)(ac); \
+    (a) = ROTATE_LEFT ((a), (s)); \
+    (a) += (b); \
+  }
+
+/* MD5 initialization. Begins an MD5 operation, writing a new context.
+ */
+void MD5Init (context)
+MD5_CTX *context;                                        /* context */
+{
+  context->count[0] = context->count[1] = 0;
+
+  /* Load magic initialization constants.
+   */
+  context->state[0] = 0x67452301;
+  context->state[1] = 0xefcdab89;
+  context->state[2] = 0x98badcfe;
+  context->state[3] = 0x10325476;
+}
+
+/* MD5 block update operation. Continues an MD5 message-digest
+     operation, processing another message block, and updating the
+     context.
+ */
+void MD5Update (context, input, inputLen)
+MD5_CTX *context;                                        /* context */
+unsigned char *input;                                /* input block */
+unsigned int inputLen;                     /* length of input block */
+{
+  unsigned int i, index, partLen;
+
+  /* Compute number of bytes mod 64 */
+  index = (unsigned int)((context->count[0] >> 3) & 0x3F);
+
+  /* Update number of bits */
+  if ((context->count[0] += ((UINT4)inputLen << 3))
+      < ((UINT4)inputLen << 3))
+    context->count[1]++;
+  context->count[1] += ((UINT4)inputLen >> 29);
+  
+  partLen = 64 - index;
+  
+  /* Transform as many times as possible.
+   */
+  if (inputLen >= partLen) {
+    MD5_memcpy
+      ((POINTER)&context->buffer[index], (POINTER)input, partLen);
+    MD5Transform (context->state, context->buffer);
+  
+    for (i = partLen; i + 63 < inputLen; i += 64)
+      MD5Transform (context->state, &input[i]);
+    
+    index = 0;
+  }
+  else
+    i = 0;
+  
+  /* Buffer remaining input */
+  MD5_memcpy 
+    ((POINTER)&context->buffer[index], (POINTER)&input[i],
+     inputLen-i);
+}
+
+/* MD5 finalization. Ends an MD5 message-digest operation, writing the
+     the message digest and zeroizing the context.
+ */
+void MD5Final (digest, context)
+unsigned char digest[16];                         /* message digest */
+MD5_CTX *context;                                       /* context */
+{
+  unsigned char bits[8];
+  unsigned int index, padLen;
+
+  /* Save number of bits */
+  Encode (bits, context->count, 8);
+
+  /* Pad out to 56 mod 64.
+   */
+  index = (unsigned int)((context->count[0] >> 3) & 0x3f);
+  padLen = (index < 56) ? (56 - index) : (120 - index);
+  MD5Update (context, PADDING, padLen);
+  
+  /* Append length (before padding) */
+  MD5Update (context, bits, 8);
+
+  /* Store state in digest */
+  Encode (digest, context->state, 16);
+  
+  /* Zeroize sensitive information.
+   */
+  MD5_memset ((POINTER)context, 0, sizeof (*context));
+}
+
+/* MD5 basic transformation. Transforms state based on block.
+ */
+static void MD5Transform (state, block)
+UINT4 state[4];
+unsigned char block[64];
+{
+  UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
+  
+  Decode (x, block, 64);
+
+  /* Round 1 */
+  FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
+  FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
+  FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
+  FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
+  FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
+  FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
+  FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
+  FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
+  FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
+  FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
+  FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
+  FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
+  FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
+  FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
+  FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
+  FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
+
+  /* Round 2 */
+  GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
+  GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
+  GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
+  GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
+  GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
+  GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */
+  GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
+  GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
+  GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
+  GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
+  GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
+  GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
+  GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
+  GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
+  GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
+  GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
+
+  /* Round 3 */
+  HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
+  HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
+  HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
+  HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
+  HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
+  HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
+  HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
+  HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
+  HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
+  HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
+  HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
+  HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */
+  HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
+  HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
+  HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
+  HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
+
+  /* Round 4 */
+  II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
+  II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
+  II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
+  II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
+  II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
+  II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
+  II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
+  II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
+  II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
+  II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
+  II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
+  II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
+  II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
+  II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
+  II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
+  II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
+
+  state[0] += a;
+  state[1] += b;
+  state[2] += c;
+  state[3] += d;
+  
+  /* Zeroize sensitive information.
+   */
+  MD5_memset ((POINTER)x, 0, sizeof (x));
+}
+
+/* Encodes input (UINT4) into output (unsigned char). Assumes len is
+     a multiple of 4.
+ */
+static void Encode (output, input, len)
+unsigned char *output;
+UINT4 *input;
+unsigned int len;
+{
+  unsigned int i, j;
+
+  for (i = 0, j = 0; j < len; i++, j += 4) {
+    output[j] = (unsigned char)(input[i] & 0xff);
+    output[j+1] = (unsigned char)((input[i] >> 8) & 0xff);
+    output[j+2] = (unsigned char)((input[i] >> 16) & 0xff);
+    output[j+3] = (unsigned char)((input[i] >> 24) & 0xff);
+  }
+}
+
+/* Decodes input (unsigned char) into output (UINT4). Assumes len is
+     a multiple of 4.
+ */
+static void Decode (output, input, len)
+UINT4 *output;
+unsigned char *input;
+unsigned int len;
+{
+  unsigned int i, j;
+
+  for (i = 0, j = 0; j < len; i++, j += 4)
+    output[i] = ((UINT4)input[j]) | (((UINT4)input[j+1]) << 8) |
+      (((UINT4)input[j+2]) << 16) | (((UINT4)input[j+3]) << 24);
+}
+
+/* Note: Replace "for loop" with standard memcpy if possible.
+ */
+static void MD5_memcpy (output, input, len)
+POINTER output;
+POINTER input;
+unsigned int len;
+{
+  unsigned int i;
+  
+  for (i = 0; i < len; i++)
+    output[i] = input[i];
+}
+
+/* Note: Replace "for loop" with standard memset if possible.
+ */
+static void MD5_memset (output, value, len)
+POINTER output;
+int value;
+unsigned int len;
+{
+  unsigned int i;
+  
+  for (i = 0; i < len; i++)
+    ((char *)output)[i] = (char)value;
+}
diff --git a/packages/net/athttpd/v2_0/src/socket.c b/packages/net/athttpd/v2_0/src/socket.c
new file mode 100644 (file)
index 0000000..8e45df7
--- /dev/null
@@ -0,0 +1,520 @@
+/* =================================================================
+ *
+ *      socket.c
+ *
+ *      Opens socket and starts the daemon.
+ *
+ * ================================================================= 
+ * ####ECOSGPLCOPYRIGHTBEGIN####
+ * -------------------------------------------
+ * This file is part of eCos, the Embedded Configurable Operating
+ * System.
+ * Copyright (C) 2005 eCosCentric Ltd.
+ * 
+ * eCos 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.
+ * 
+ * eCos 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 eCos; if not, write to the Free Software Foundation,
+ * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ * 
+ * As a special exception, if other files instantiate templates or
+ * use macros or inline functions from this file, or you compile this
+ * file and link it with other works to produce a work based on this
+ * file, this file does not by itself cause the resulting work to be
+ * covered by the GNU General Public License. However the source code
+ * for this file must still be made available in accordance with
+ * section (3) of the GNU General Public License.
+ * 
+ * This exception does not invalidate any other reasons why a work
+ * based on this file might be covered by the GNU General Public
+ * License.
+ *
+ * -------------------------------------------
+ * ####ECOSGPLCOPYRIGHTEND####
+ * =================================================================
+ * #####DESCRIPTIONBEGIN####
+ * 
+ *  Author(s):    Anthony Tonizzo (atonizzo@gmail.com)
+ *  Contributors: Sergei Gavrikov (w3sg@SoftHome.net), 
+ *                Lars Povlsen    (lpovlsen@vitesse.com)
+ *  Date:         2006-06-12
+ *  Purpose:      
+ *  Description:  
+ *               
+ * ####DESCRIPTIONEND####
+ * 
+ * =================================================================
+ */
+#include <pkgconf/hal.h>
+#include <pkgconf/kernel.h>
+#include <cyg/kernel/kapi.h>           // Kernel API.
+#include <cyg/kernel/ktypes.h>         // base kernel types.
+#include <cyg/infra/diag.h>            // For diagnostic printing.
+#include <network.h>
+#include <sys/uio.h>
+#include <fcntl.h>
+#include <stdio.h>                     // sprintf().
+#include <time.h>                      // sprintf().
+
+#include <cyg/athttpd/http.h>
+#include <cyg/athttpd/socket.h>
+#include <cyg/athttpd/cgi.h>
+
+#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
+#define CYG_HTTPD_DAEMON_STACK_SIZE (CYGNUM_HAL_STACK_SIZE_MINIMUM + \
+                                          CYGNUM_NET_ATHTTPD_THREADOPT_STACKSIZE)
+static cyg_int32 cyg_httpd_initialized = 0;
+cyg_thread   cyg_httpd_thread_object;
+cyg_handle_t cyg_httpd_thread_handle;
+cyg_uint8    cyg_httpd_thread_stack[CYG_HTTPD_DAEMON_STACK_SIZE]     
+                                       __attribute__((__aligned__ (16)));
+CYG_HTTPD_STATE httpstate;
+                                         
+__inline__ ssize_t
+cyg_httpd_write(char* buf, int buf_len)
+{
+    // We are not going to write anything in case
+    ssize_t sent = send(httpstate.sockets[httpstate.client_index].descriptor, 
+                        buf, 
+                        buf_len,
+                        0);
+    return sent;
+}
+
+__inline__ ssize_t
+cyg_httpd_writev(cyg_iovec *iovec_bufs, int count)
+{
+    int i;
+    ssize_t sent = writev(httpstate.sockets[httpstate.client_index].descriptor, 
+                          iovec_bufs, 
+                          count);
+    ssize_t buf_len = 0;
+    for (i = 0; i < count; i++)
+        buf_len += iovec_bufs[i].iov_len;
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 1
+    if (sent != buf_len)
+        diag_printf("writev() did not send out all bytes (%ld of %ld)\n", 
+                    sent,
+                    buf_len);
+#endif    
+    return sent;
+}
+    
+// The need for chunked transfers arises from the fact that with persistent
+//  connections it is not always easy to tell when a packet end. Also, with
+//  dynamic pages it is not always possible to know the packet size upfront,
+//  and thus the value of the 'Content-Length:' field in the header is not
+//  known upfront.
+// Today's web browser use 'Content-Length:' when present in the header and 
+//  when not present they read everything that comes in up to the last 2 \r\n
+//  and then figure it out. The HTTP standard _mandates_ 'Content-Length:' to
+//  be present in the header with a correct value, and whenever that is not
+//  possible, chunked transfers must be used.
+//
+// A chunked transer takes the form of:
+// -----------------------------------------------------------------------------
+//    cyg_httpd_start_chunked("html");
+//    sprintf(phttpstate->payload, ...);             
+//    cyg_httpd_write_chunked(phttpstate->payload, strlen(phttpstate->payload));
+//    ...                         
+//    cyg_httpd_end_chunked();
+// -----------------------------------------------------------------------------
+ssize_t
+cyg_httpd_start_chunked(char *extension)
+{
+    httpstate.status_code = CYG_HTTPD_STATUS_OK;
+
+#if defined(CYGOPT_NET_ATHTTPD_CLOSE_CHUNKED_CONNECTIONS)
+    // I am not really sure that this is necessary, but even if it isn't, the
+    //  added overhead is not such a big deal. In simple terms, I am not sure 
+    //  how much I can rely on the client to understand that the frame has ended 
+    //  with the last 5 bytes sent out. In an ideal world, the data '0\r\n\r\n'
+    //  should be enough, but several posting on the subject I read seem to
+    //  imply otherwise, at least with early generation browsers that supported
+    //  the "Transfer-Encoding: chunked" mechanism. Things might be getting 
+    //  better now but I snooped some sites that use the chunked stuff (Yahoo!
+    //  for one) and all of them with no exception issue a "Connection: close" 
+    //  on chunked frames even if there is nothing in the HTTP 1.1 spec that
+    //  requires it.
+    httpstate.mode |= CYG_HTTPD_MODE_CLOSE_CONN;
+#endif
+    
+    // We do not cache chunked frames. In case they are used to display dynamic
+    //  data we want them to be executed every time they are requested.
+    httpstate.mode |= 
+              (CYG_HTTPD_MODE_TRANSFER_CHUNKED | CYG_HTTPD_MODE_NO_CACHE);
+    
+    httpstate.last_modified = -1;
+    httpstate.mime_type = cyg_httpd_find_mime_string(extension);
+    cyg_int32 header_length = cyg_httpd_format_header();
+    return cyg_httpd_write(httpstate.outbuffer, header_length);
+}
+
+ssize_t
+cyg_httpd_write_chunked(char* buf, int len)
+{
+    if (len == 0)
+         return 0;
+
+    char leader[16], trailer[] = {'\r', '\n'};
+    cyg_iovec iovec_bufs[] = { {leader, 0}, {buf, len}, {trailer, 2} };
+    iovec_bufs[0].iov_len = sprintf(leader, "%x\r\n", len);
+    if (httpstate.mode & CYG_HTTPD_MODE_SEND_HEADER_ONLY)
+        return (iovec_bufs[0].iov_len + len + 2);
+    return cyg_httpd_writev(iovec_bufs, 3);
+}
+
+void
+cyg_httpd_end_chunked(void)
+{
+    httpstate.mode &= ~CYG_HTTPD_MODE_TRANSFER_CHUNKED;
+    if ((httpstate.mode & CYG_HTTPD_MODE_SEND_HEADER_ONLY) != 0)
+        return;
+    strcpy(httpstate.outbuffer, "0\r\n\r\n");
+    cyg_httpd_write(httpstate.outbuffer, 5);
+}    
+
+// This function builds and sends out a standard header. It is likely going to
+//  be used by a c language callback function, and thus followed by one or
+//  more calls to cyg_httpd_write(). Unlike cyg_httpd_start_chunked(), this
+//  call requires prior knowledge of the final size of the frame (browsers
+//  _will_trust_ the "Content-Length:" field when present!), and the user 
+//  is expected to make sure that the total number of bytes (octets) sent out
+//  via 'cyg_httpd_write()' matches the number passed in the len parameter.
+// Its use is thus more limited, and the more flexible chunked frames should 
+//  be used whenever possible.
+void
+cyg_httpd_create_std_header(char *extension, int len)
+{
+    httpstate.status_code = CYG_HTTPD_STATUS_OK;
+    httpstate.mode |= CYG_HTTPD_MODE_NO_CACHE;
+
+    // We do not want to send out a "Last-Modified:" field for c language
+    //  callbacks.
+    httpstate.last_modified = -1;
+    httpstate.mime_type = cyg_httpd_find_mime_string(extension);
+    httpstate.payload_len = len;
+    cyg_int32 header_length = cyg_httpd_format_header();
+    cyg_httpd_write(httpstate.outbuffer, header_length);
+}
+
+void
+cyg_httpd_process_request(cyg_int32 index)
+{
+    httpstate.client_index = index;
+    cyg_int32 descr = httpstate.sockets[index].descriptor;
+
+    // By placing a terminating '\0' not only we have a safe stopper point
+    //  for our parsing, but also we can detect if we have a split header.
+    // Since headers always end with an extra '\r\n', if we find a '\0'
+    //  before the terminator than we can safely assume that the header has
+    //  not been received completely and more is following (i.e. split headers.)
+    httpstate.inbuffer[0] = '\0';
+    httpstate.inbuffer_len = 0;
+
+    cyg_bool done = false;
+    do
+    {   
+        // At this point we know we have data pending because the corresponding
+        //  bit in the fd_set structure was set.
+        int len = recv(descr,
+                       httpstate.inbuffer + httpstate.inbuffer_len,
+                       CYG_HTTPD_MAXINBUFFER - httpstate.inbuffer_len,
+                       0);
+        if (len == 0)
+        {
+            // This is the client that has closed its TX socket, possibly as
+            //  a response from a shutdown() initiated by the server. Another
+            //  possibility is that the client was closed altogether, in
+            //  which case the client sent EOFs on each open sockets before 
+            //  dying.
+            close(descr);
+            FD_CLR(descr, &httpstate.rfds);
+            httpstate.sockets[index].descriptor = 0;
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+            printf("EOF received on descriptor: %d. Closing it.\n", descr);
+#endif    
+            return;
+        }    
+        
+        if (len < 0)
+        {
+            // There was an error reading from this socket. Play it safe and
+            //  close it. This will force the client to generate a shutdown
+            //  and we will read a len = 0 the next time around.
+            shutdown(descr, SHUT_WR);
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+            diag_printf("ERROR reading from socket. read() returned: %d\n", 
+                        httpstate.inbuffer_len);
+#endif    
+            return;
+        }  
+
+        httpstate.inbuffer[httpstate.inbuffer_len + len] = '\0';
+
+        // It is always possible to receive split headers, in which case a
+        //  header is only partially sent on one packet, with the rest on
+        //  following packets. We can tell when a full packet is in the buffer
+        //  by scanning for a header terminator ('\r\n\r\n'). Be smart and
+        //  scan only the data received in the last read() operation, and not
+        //  the full buffer each time.
+        httpstate.request_end = 
+               strstr(&httpstate.inbuffer[httpstate.inbuffer_len], "\r\n\r\n");
+        httpstate.inbuffer_len += len;
+
+        // Go through all the requests that were received in this packet.
+        while (httpstate.request_end != 0)
+        {
+            httpstate.request_end += 4; // Include the terminator.
+            
+            // Timestamp the socket. 
+            httpstate.sockets[index].timestamp = time(NULL);
+                
+            // This is where it all happens.
+            cyg_httpd_process_method();
+                
+            if (httpstate.mode & CYG_HTTPD_MODE_CLOSE_CONN)
+            {
+                // There are 2 cases we can be here:
+                // 1) chunked frames close their connection by default
+                // 2) The client requested the connection be terminated with a
+                //     "Connection: close" in the header
+                // In any case, we close the TX pipe and wait for the client to
+                //  send us an EOF on the receive pipe. This is a more graceful
+                //  way to handle the closing of the socket, compared to just
+                //  calling close() without first asking the opinion of the
+                //  client, and  running the risk of stray data lingering 
+                //  around.
+                shutdown(descr, SHUT_WR);
+            }
+            
+            // Move back the next request (if any) to the beginning of inbuffer.
+            //  This way we avoid inching towards the end of inbuffer with
+            //  consecutive requests.
+            strcpy(httpstate.inbuffer, httpstate.request_end);
+            httpstate.inbuffer_len -= (int)(httpstate.request_end - 
+                                                       httpstate.inbuffer);
+                                                       
+            // If there is no data left over we are done processing all
+            //  requests.
+            if (httpstate.inbuffer_len == 0)
+            {
+                done = true;
+                break;
+            }    
+
+            // Any other fully formed request pending?                                           
+            httpstate.request_end = strstr(httpstate.inbuffer, "\r\n\r\n");
+        }        
+    }
+    while (done == false);
+}
+
+void
+cyg_httpd_handle_new_connection(cyg_int32 listener)
+{
+    cyg_int32 i;
+
+    int fd_client = accept(listener, NULL, NULL);
+    CYG_ASSERT(listener != -1, "accept() failed");
+    if (fd_client == -1) 
+        return;
+    
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+    diag_printf("Opening descriptor: %d\n", fd_client);
+#endif    
+    // Timestamp the socket and process the frame immediately, since the accept
+    //  guarantees the presence of valid data on the newly opened socket.
+    for (i = 0; i < CYGPKG_NET_MAXSOCKETS; i++)
+        if (httpstate.sockets[i].descriptor == 0)
+        {
+            httpstate.sockets[i].descriptor = fd_client;
+            httpstate.sockets[i].timestamp  = time(NULL);
+            cyg_httpd_process_request(i);
+            return;
+        }    
+}
+
+// This is the "garbage collector" (or better, the "garbage disposer") of
+//  the server. It closes any socket that has been idle for a time period
+//  of CYG_HTTPD_SELECT_TIMEOUT seconds.
+void
+cyg_httpd_close_unused_sockets(cyg_int32 listener)
+{
+    cyg_int32 i;
+    
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+    diag_printf("Garbage collector called\r\n");
+#endif    
+    httpstate.fdmax = listener;
+    for (i = 0; i < CYGPKG_NET_MAXSOCKETS; i++)
+    {
+        if (httpstate.sockets[i].descriptor != 0)
+        {
+            if (time(NULL) - httpstate.sockets[i].timestamp > 
+                                          CYG_HTTPD_SOCKET_IDLE_TIMEOUT)
+            {           
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+                diag_printf("Closing descriptor: %d\n", 
+                            httpstate.sockets[i].descriptor);
+#endif    
+                shutdown(httpstate.sockets[i].descriptor, SHUT_WR);
+            }
+            else
+                httpstate.fdmax = MAX(httpstate.fdmax, 
+                                      httpstate.sockets[i].descriptor);
+        }                              
+    }
+}
+
+void
+cyg_httpd_daemon(cyg_addrword_t data)
+{
+    cyg_int32 rc;
+    init_all_network_interfaces();
+
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up)
+    {
+        struct bootp* bps = &eth0_bootp_data;
+        diag_printf("ETH0 is up. IP address: %s\n", inet_ntoa(bps->bp_yiaddr));
+    }
+#endif
+#endif
+
+#ifdef CYGOPT_NET_ATHTTPD_USE_CGIBIN_TCL
+    cyg_httpd_init_tcl_interpreter();
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+    diag_printf("Tcl interpreter has been initialized...\n");
+#endif
+#endif    
+    
+    cyg_httpd_initialize();
+
+    // Get the network going. This is benign if the application has
+    //  already done this.
+    cyg_int32 listener = socket(AF_INET, SOCK_STREAM, 0);
+    CYG_ASSERT(listener > 0, "Socket create failed");
+    if (listener < 0)
+        return;
+
+    cyg_int32 yes = 1;
+    rc = setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
+    if (rc == -1) 
+        return;
+    
+    memset(&(httpstate.server_conn), 0, sizeof(struct sockaddr_in));
+    httpstate.server_conn.sin_family = AF_INET;
+    httpstate.server_conn.sin_addr.s_addr = INADDR_ANY;
+    httpstate.server_conn.sin_port = htons(CYGNUM_NET_ATHTTPD_SERVEROPT_PORT);
+    rc = bind(listener,
+              (struct sockaddr *)&httpstate.server_conn, 
+              sizeof(struct sockaddr)); 
+    CYG_ASSERT(rc == 0, "bind() returned error");
+    if (rc != 0)
+        return;
+
+    rc = listen(listener, SOMAXCONN);
+    CYG_ASSERT(rc == 0, "listen() returned error");
+    if (rc != 0)
+        return;
+
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+    diag_printf("Web server Started and listening...\n");
+#endif
+    cyg_int32 i;
+    for (i = 0; i < CYGPKG_NET_MAXSOCKETS; i++)
+    {
+        httpstate.sockets[i].descriptor  = 0;
+        httpstate.sockets[i].timestamp   = (time_t)0;
+    }
+    
+    FD_ZERO(&httpstate.rfds);
+    httpstate.fdmax = listener;
+    while (1)
+    {
+        // The listener is always added to the select() sensitivity list.
+        FD_SET(listener, &httpstate.rfds); 
+        struct timeval tv = {CYG_HTTPD_SOCKET_IDLE_TIMEOUT, 0};
+        rc = select(httpstate.fdmax + 1, &httpstate.rfds, NULL, NULL, &tv);
+        if (rc > 0)
+        {
+            if (FD_ISSET(listener, &httpstate.rfds))
+                // If the request is from the listener socket, then 
+                //  this must be a new connection.
+                cyg_httpd_handle_new_connection(listener);
+
+            httpstate.fdmax = listener;
+            
+            // The sensitivity list returned by select() can have multiple
+            //  socket descriptors that need service. Loop through the whole
+            //  descriptor list to see if one or more need to be served.
+            for (i = 0; i < CYGPKG_NET_MAXSOCKETS; i ++)
+            {
+                cyg_int32 descr = httpstate.sockets[i].descriptor;
+                if (descr != 0)
+                {
+                    // If the descriptor is set in the descriptor list, we
+                    //  service it. Otherwise, we add it to the descriptor list
+                    //  to listen for. The rfds list gets rewritten each time
+                    //  select() is called and after the call it contains only
+                    //  the descriptors that need be serviced. Before calling
+                    //  select() again we must repopulate the list with all the
+                    //  descriptors that must be listened for.
+                    if (FD_ISSET(descr, &httpstate.rfds))
+                        cyg_httpd_process_request(i);
+                    else       
+                        FD_SET(descr, &httpstate.rfds); 
+                    if (httpstate.sockets[i].descriptor != 0)
+                        httpstate.fdmax = MAX(httpstate.fdmax, descr);
+                }
+            }
+        }
+        else if (rc == 0)
+        {
+            cyg_httpd_close_unused_sockets(listener);
+        }
+        else
+        {
+#if CYGOPT_NET_ATHTTPD_DEBUG_LEVEL > 0
+            cyg_int8 *ptr = (cyg_int8*)&httpstate.rfds;
+            diag_printf("rfds: %x %x %x %x\n", ptr[0], ptr[1], ptr[2], ptr[3] );
+            for (i = 0; i < CYGPKG_NET_MAXSOCKETS; i++)
+                if (httpstate.sockets[i].descriptor != 0)
+                     diag_printf("Socket in list: %d\n", 
+                                 httpstate.sockets[i].descriptor);
+#endif                                 
+            CYG_ASSERT(rc != -1, "Error during select()");                 
+        }
+    }
+}
+
+void
+cyg_httpd_start(void)
+{
+    if (cyg_httpd_initialized)
+        return;
+    cyg_httpd_initialized = 1;
+    
+    cyg_thread_create(CYGNUM_NET_ATHTTPD_THREADOPT_PRIORITY,
+                      cyg_httpd_daemon,
+                      (cyg_addrword_t)0,
+                      "HTTPD Thread",
+                      (void *)cyg_httpd_thread_stack,
+                      CYG_HTTPD_DAEMON_STACK_SIZE,
+                      &cyg_httpd_thread_handle,
+                      &cyg_httpd_thread_object);
+    cyg_thread_resume(cyg_httpd_thread_handle);
+}                       
+
+
+
diff --git a/packages/net/autotest/v2_0/ChangeLog b/packages/net/autotest/v2_0/ChangeLog
new file mode 100644 (file)
index 0000000..1ac8f16
--- /dev/null
@@ -0,0 +1,301 @@
+2002-02-01  Gary Thomas  <gthomas@redhat.com>
+
+       * tests/slowpingmux.c (ping_test): 
+       * tests/routeping.inl: (ping_test): 
+       * tests/floodpingmux.c: (net_test): 
+       * tests/autohost.inl (autohost_tell): 
+       * host/awaitorder.c (main): Need valid value for sin_len.
+
+2001-10-10  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/floodping.c:
+       * tests/floodpingmux.c:
+       * tests/snmpmulti.c:
+       * tests/snmppings.c:
+       * tests/snmpwalk.c:
+       More conditional compilation needed for use of eth0_up, eth1_up
+       and the like, since the config opt is now a boolean and so these
+       might not exist.
+
+2001-06-26  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/routeping.inl (route_add_s): Add a close to the socket.
+       Don't be upset if you can't ping www.cygnus.com by number!
+
+2000-12-08  Hugo Tyson  <hmt@redhat.com>
+
+       * host/tftpget.sh (TARGET): Try a little harder to put a correct
+       test dataset into the target; we are testing GET not PUT here.  We
+       are seeing get fails of 1Mb data on the zeroth try; it could be a
+       real get bug, or problems putting the original image.  This change
+       should help diagnose which.
+
+       * tests/slowpingmux.c (ping_host): Make this much less verbose in
+       [good] output; the farm rejects too much chatter.
+
+2000-11-17  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/memcheck.inl (memcheck_final): Ignore clusters if
+       simulating network failures; I guess memory is used up with
+       partial packets awaiting reassembly, and they'll time out.
+
+       * tests/routeping.inl (net_test): Call TNR_ON/OFF() correctly.
+
+       * tests/slowpingmux.c (net_test): Call TNR_ON/OFF() correctly.
+
+       * tests/floodpingmux.c (net_test): Only call TNR_INIT() once.
+       Call TNR_OFF(); again after dumpstats() turned it on again.
+       Call TNR_ON/OFF() correctly.
+
+       * tests/autohost.inl (autohost_getresults): Add a missing
+       semicolon.  Doh!  Only a problem with realtime test harness
+       enabled.
+
+2000-11-15  Hugo Tyson  <hmt@redhat.com>
+
+       * doc/host.txt: Updated.
+
+2000-11-15  Hugo Tyson  <hmt@redhat.com>
+
+       * cdl/net_autotest.cdl: Build the new tests.
+
+       * tests/routeping.inl: New file: the meat of a testcase to check
+       that external networks are only accessible if we have added a
+       suitable route.  This requires a further network called 10.0.3.x
+       attached to the machine that serves DHCP to eth0, and one called
+       10.0.4.x on the server for eth1.  These can both be aliases for
+       loopback on the linux host if needs be.
+
+       * tests/route_none.c:
+       * tests/route_3.c: 
+       * tests/route_4.c: 
+       * tests/route_3_4.c: 
+       New files: Various invocations of the above.  These just make a
+       few #defines then #include "routeping.inl"
+       
+2000-11-10  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/autohost.inl (autohost_init): Call the memory checking
+       init and finalization functions in the appropriate places.
+
+       * tests/memcheck.inl (RATIO): New file; check for mbuf &c leaks
+       (if the API is defined in network.h, so it it'll work with the 144
+       tarball).  We allow either as much again or 15% of memory to be
+       used at the end of the test, for each of the 3 memory regions the
+       stack uses.
+
+       * tests/floodpingmux.c (net_test): Don't print out mbuf &c usage,
+       leave it up to the memory checking subsystem.
+
+2000-11-10  Hugo Tyson  <hmt@redhat.com>
+
+       * host/obey.sh: Handle the new case of doing snmpwalk and
+       snmpstatus to the target. (SNMP_WALK)
+
+       * cdl/net_autotest.cdl: Build the new tests.
+
+       * host/snmpwalk.sh: New file: snmpwalk the target's public MIB and
+       check target status for the timeout.  Much like the other cases.
+
+       * tests/snmpwalk.c: New file: do one snmpwalk session on each
+       interface.
+
+       * tests/snmpmulti.c: New file: ditto, 3 sessions per i/f.
+
+       * tests/snmppings.c: New file: ditto, 2 x snmp, plus some pinging
+       and flood pinging simulataneously.
+
+2000-11-09  Hugo Tyson  <hmt@redhat.com>
+
+       * host/obey.sh: Handle the new case of flood pinging the
+       target. (FLOOD_PING)
+
+       * host/floodping.sh: New file: flood ping the target, with a
+       variable active/sleep ratio so that we can use this to perturb
+       other tests also.  An suid executable "./_suping" is needed to be
+       able to flood ping automatically.
+
+       * cdl/net_autotest.cdl: Build the two new tests.
+
+       * tests/floodping.c: New file: ask the host to flood ping me, for
+       5 minutes in the usual manner.
+
+       * tests/floodpingmux.c: New file: as floodping.c and the target
+       floods the host in turn also.
+
+       * host/makefile: Build _suping: it must be set uid &c manually.
+
+       * host/_suping.c: New file: a tiny su root program to run ping
+       with real uid root (ping is suid root anyway) to allow us to flood
+       the target.
+
+2000-11-08  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/autohost.inl (XFAIL): Detect the configuration that means
+       simulated unreliable network is enabled.  Send the XFAIL parameter
+       to the network testing server if so.  Also do not check for the
+       count of pass messages required in the autohost_end() routine; we
+       expect them to go missing and/or there to be failures per se.
+
+       * host/obey.sh (XFAIL): Detect and pass through the XFAIL
+       parameter to indicate simulated unreliable network is enabled.
+
+       * host/tftpget.sh (XFAIL): 
+       * host/tftpput.sh (XFAIL): 
+       * host/slowping.sh (XFAIL): If XFAIL, do not report failures as
+       such; also echo the process ID ($$) in messages to help untangle
+       the interleaved status messages.
+
+       * host/sendack.sh (XFAIL): Try less zealously and moan less loudly
+       if failure is expected.
+
+       * doc/host.txt: Document XFAIL stuff.
+
+2000-10-26  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/slowping.c (net_test): New file: 
+       * tests/slowpingmux.c (net_test): New file: simple test, the host
+       pings the target (a lot, 10x simultaneously), while the target
+       also pings the host in slowpingmux.
+
+       * host/slowping.sh (TARGET): New file: handle target side of ping
+       testing.
+
+       * cdl/net_autotest.cdl: Build the new tests.
+
+2000-10-26  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/tftp_serv.inl (do_tftp_tests): Fix typo in info printf;
+       nothing of substance.
+
+2000-10-25  Hugo Tyson  <hmt@redhat.com>
+
+       * permtests/netauto_bootp.ptest: net with bootp only init.
+       * permtests/netauto_corrupt.ptest: net + 10% rx corruption.
+       * permtests/netauto_failrx.ptest: net + 10% rx discards.
+       * permtests/netauto_failtx.ptest: net + 10% tx discards.
+       * permtests/netauto_rt.ptest: net + snmp + realtime test.
+       * permtests/netauto_snmp.ptest: net + snmp.
+       * permtests/netauto_std.ptest: standard net config
+       New files; permtest configurations for farm testing.
+
+2000-10-24  Hugo Tyson  <hmt@redhat.com>
+
+       * doc/host.txt: More info added; kept up to date.
+
+2000-10-24  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/tftp_serv.inl: New file, the guts of both tftp_serv_get.c
+       and tftp_serv_put.c removed to here, so that a number of tests can
+       be created to hit the server with different sizes of datafile.
+       This is the easiest way to test lots of different filesizes and
+       edge conditions; just replicate the testcase.
+
+       * tests/tftp_serv_put.c (FILESIZE): 
+       * tests/tftp_serv_get.c (FILESIZE): Use "tftp_serv.inl" with a
+       coupla #defines for the op and the filesize to implement the test.
+
+       * tests/tftp_serv_g0.c:   New: get zero and 1-byte datafiles.
+       * tests/tftp_serv_g1M.c:  New: get 1Mb and 1Mb-1 datafiles.
+       * tests/tftp_serv_g512.c: New: get 512 and 513-byte datafiles.
+       * tests/tftp_serv_p0.c:   New: put zero and 1-byte datafiles.
+       * tests/tftp_serv_p1M.c:  New: put 1Mb and 1Mb-1 datafiles.
+       * tests/tftp_serv_p512.c: New: put 512 and 513-byte datafiles.
+
+       * cdl/net_autotest.cdl: Build all the new testcases to diddle
+       different file sizes.
+
+       * host/tftpput.sh (TARGET): Do not read back the file every time;
+       check the gotton file once at the end correctly; count up the
+       transfers for info.
+
+       * host/tftpget.sh (TARGET): Check the gotton file correctly; count
+       up the transfers for info.
+
+2000-10-23  Hugo Tyson  <hmt@redhat.com>
+
+       * host/tftpdata.src: DELETED: we now make our own data files on
+       the fly.
+
+       * host/makefile (tmpfile): Build this.  Also add a make clean.
+
+       * host/tmpfile.c (main): New file: builds to a simple executable
+       that makes a scratch file full of random data of the length
+       requested.  A simple but order-sensitive checksum is appended,
+       though the testcase doesn't use this yet.
+
+       * tests/tftp_serv_put.c (do_tftp_tests): 
+       * tests/tftp_serv_get.c (do_tftp_tests): Pass a filesize to the
+       test script; it will make a temp file accordingly.
+
+       * host/tftpput.sh: 
+       * host/tftpget.sh: Parameterize these more so that they accept a
+       filesize; the data file is created with random data.
+
+2000-10-20  Hugo Tyson  <hmt@redhat.com>
+
+       * doc/host.txt: New file.  Details the host side code, scripts,
+       environment, tempfiles, conventions, output...
+
+       * doc/strategy.txt: New file.  The original design notes.
+       
+       * host/obey.sh: Correct typo and add . to the path; stupid
+       pedantic environment.
+
+2000-10-20  Hugo Tyson  <hmt@redhat.com>
+
+       * tests/tftp_serv_get.c (net_test): 
+       * tests/tftp_serv_put.c (net_test): Use the new API, and remember
+       how many host sessions we expected to invoke.
+
+       * tests/autohost.inl (autohost_end): New API to check counts of
+       PASS and FAIL statii from the hosts.
+
+2000-10-19  Hugo Tyson  <hmt@redhat.com>
+
+       * Changelog: New file.
+       * cdl/net_autotest.cdl: New file.
+       * host/awaitorder.c: New file.
+       * host/makefile: New file.
+       * host/obey.sh: New file.
+       * host/sendack.sh: New file.
+       * host/tftpdata.src: New file.
+       * host/tftpget.sh: New file.
+       * host/tftpput.sh: New file.
+       * tests/autohost.inl: New file.
+       * tests/tftp_serv_get.c: New file.
+       * tests/tftp_serv_put.c: New file.
+       Indeed a new package, even.  Documentation will be forthcoming.
+
+//===========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//===========================================================================
diff --git a/packages/net/autotest/v2_0/cdl/net_autotest.cdl b/packages/net/autotest/v2_0/cdl/net_autotest.cdl
new file mode 100644 (file)
index 0000000..552fa0b
--- /dev/null
@@ -0,0 +1,122 @@
+# ====================================================================
+#
+#      net_autotest.cdl
+#
+#      Networking autotest subsystem configuration data
+#
+# ====================================================================
+#####ECOSGPLCOPYRIGHTBEGIN####
+## -------------------------------------------
+## This file is part of eCos, the Embedded Configurable Operating System.
+## Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+##
+## eCos 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.
+##
+## eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+## 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+##
+## As a special exception, if other files instantiate templates or use macros
+## or inline functions from this file, or you compile this file and link it
+## with other works to produce a work based on this file, this file does not
+## by itself cause the resulting work to be covered by the GNU General Public
+## License. However the source code for this file must still be made available
+## in accordance with section (3) of the GNU General Public License.
+##
+## This exception does not invalidate any other reasons why a work based on
+## this file might be covered by the GNU General Public License.
+##
+## -------------------------------------------
+#####ECOSGPLCOPYRIGHTEND####
+# ====================================================================
+######DESCRIPTIONBEGIN####
+#
+# Author(s):      hmt
+# Original data:  hmt
+# Contributors:
+# Date:           2000-10-19
+#
+#####DESCRIPTIONEND####
+#
+# ====================================================================
+
+cdl_package CYGPKG_NET_AUTOTEST {
+    display       "Networking autotest"
+    doc           doc/index.html
+    include_dir   net/autotest
+    requires      CYGPKG_IO
+    requires      CYGPKG_ISOINFRA
+    requires      CYGPKG_LIBC_TIME
+    requires      CYGPKG_ERROR
+    requires      CYGPKG_MEMALLOC
+    requires      CYGPKG_NET
+    description   "Networking autotest facilities"
+
+#    compile *NONE*
+
+    cdl_option CYGPKG_NET_AUTOTEST_TESTS {
+       display "Networking tests"
+       flavor  data
+       no_define
+       calculated { "\
+               tests/floodping.c \
+               tests/floodpingmux.c \
+               tests/route_3.c \
+               tests/route_3_4.c \
+               tests/route_4.c \
+               tests/route_none.c \
+               tests/slowping.c \
+               tests/slowpingmux.c \
+               tests/snmpwalk.c \
+               tests/snmpmulti.c \
+               tests/snmppings.c \
+               tests/tftp_serv_get.c \
+               tests/tftp_serv_put.c \
+               tests/tftp_serv_g0.c \
+               tests/tftp_serv_p0.c \
+               tests/tftp_serv_g512.c \
+               tests/tftp_serv_p512.c \
+               tests/tftp_serv_g1M.c \
+               tests/tftp_serv_p1M.c"
+        }
+       description   "
+       This option specifies the set of tests
+       for the networking package."
+    }
+       
+    cdl_component CYGPKG_NET_AUTOTEST_OPTIONS {
+        display "Networking support build options"
+        flavor  none
+       no_define
+
+        cdl_option CYGPKG_NET_AUTOTEST_CFLAGS_ADD {
+            display "Additional compiler flags"
+            flavor  data
+            no_define
+            default_value { "-D_KERNEL -D__ECOS" }
+            description   "
+                This option modifies the set of compiler flags for
+                building the autotest package.
+               These flags are used in addition
+                to the set of global flags."
+        }
+
+        cdl_option CYGPKG_NET_AUTOTEST_CFLAGS_REMOVE {
+            display "Suppressed compiler flags"
+            flavor  data
+            no_define
+            default_value { "" }
+            description   "
+                This option modifies the set of compiler flags for
+                building the autotest package. These flags are removed from
+                the set of global flags if present."
+        }
+    }
+}
diff --git a/packages/net/autotest/v2_0/doc/host.txt b/packages/net/autotest/v2_0/doc/host.txt
new file mode 100644 (file)
index 0000000..c655c81
--- /dev/null
@@ -0,0 +1,414 @@
+
+Host Software for Automated Network Testing for eCos
+====================================================
+
+Hugo Tyson, Red Hat, Cambridge UK, 2000-10-20
+
+
+What Host Software?
+-------------------
+
+This note refers to the package CYGPKG_NET_AUTOTEST which lives in
+packages/net/autotest in the eCos repository.
+
+It contains, amongst other things, some software to run a "network testing
+server" which eCos network test cases (from the same package) use to test
+the network stack.
+
+The reason such a server is needed is simple: testing the eCos network
+stack involves an external, standard, computer _doing_things_to_ the target
+board as well as having the target board's test program do things itself.
+
+For example, one test case (in the main network package, net/tcpip) to test
+TFTP will get a file from a server using TFTP and put the data to another
+file on the server using TFTP.  This tests the ability of the eCos TCPIP
+stack to act as a TFTP client.  But it does not test the eCos TCPIP stack's
+TFTP server at all.  To do that an external agent must act as client -
+using the standard tftp(1) app on linux, for example - to put and get data
+to and from an eCos testcase running on the target, offering a TFTP server.
+
+
+Quick Start Guide
+-----------------
+
+Set up your LINUX machine to serve DHCP to the target you want to test;
+ensure that any 10.0.0.x addresses used are given a class C (/24) netmask.
+Provide a genuine gateway to the internet via some route; the routing tests
+expect to ping www.cygnus.com!  Also let it have the normal networking apps
+(tftp, ftp, ping) and servers (tftpd, ftpd) available, plus the SNMP
+package from UCD: snmpwalk and snmpstatus and standard MIBs.
+
+Make sure it is on on the same network(s) as the target you want to test.
+
+Set up aliases for loopback interface on the servers: on server for eth0 on
+the target, add an alias for 10.0.3.1/24.  For eth1, 10.0.4.1/24.
+
+With a checked-out eCos source tree, change directory into either
+packages/net/autotest/current/host or a copy of it, and type make.
+
+Follow the printed instruction to change the simple executable "./_suping"
+to su root execution.  You will need to become root temporarily to do this.
+
+Make sure . is on your path and type "awaitorder | obey.sh" to run the
+server; it prints info about messages it receives and sends.
+
+The test server is now running.  You can now run test built from the
+CYGPKG_NET_AUTOTEST package (packages/net/autotest) on your target and they
+will talk to this host test server.
+
+
+Categories of Tests
+-------------------
+
+ o Host passive
+
+       The host is server, the eCos test case is the proactive client.
+
+       Such tests use the host to talk to, where the eCos testcase is the
+       client, and the host is the server.  The network testing server is
+       not involved in these tests, but other servers which must be set up
+       there are used.
+ o Host proactive
+
+       The host is client to the eCos server.
+
+       The target board running eCos is the server, the host must run
+       scripts to do thing to it and report success or otherwise over the
+       net.  The eCos test case typically starts a server, issues order
+       about how to test it, then sleeps for a time until the test is
+       deemed complete.
+
+
+Building the Network Testing Server
+-----------------------------------
+
+Cd into either packages/net/autotest/current/host or a copy of it, and type
+make.  The standard makefile just compiles ./awaitorder.c into ./awaitorder
+the executable that waits for a request from a testcase and prints it to
+its stdout.  It also builds some other utilities that are used by the test
+scripts, for example ./tmpfile from ./tmpfile.c - this just creates a file
+of random data for passing back and forth.  It also builds _suping: make
+sure this is suid-root to be able to flood-ping the target.
+
+
+Running the Network Testing Server
+----------------------------------
+
+Make sure "." is on your path, early enough, then
+
+       awaitorder | obey.sh
+
+This is all you need to do to run the testing server.
+
+
+"./awaitorder" just waits for a connection on TCP port 9980 and prints what
+it receives.  For example, to test it:
+
+               % telnet masala 9980
+ you type ---> Eggs, bacon, beans, mushrooms, toast and coffee
+               Acknowledged
+               Connection closed by foreign host.
+               % 
+
+and awaitorder will print as follows:
+
+                % awaitorder 
+               awaitorder: connection from 172.16.19.13:3739
+               ORDERS: Eggs, bacon, beans, mushrooms, toast and coffee
+
+and continue waiting for the next order.
+
+
+"./obey.sh" does rather more.  It assumes that its stdin is connected to a
+source of orders, and it expects that lines of input will look like this:
+
+       ORDERS: TFTP_SERV_GET 10.16.19.171 300
+
+or more generally
+
+       "ORDERS:" [XFAIL] <order> <target IP> <extra params...>
+
+The set of valid orders (TFTP_SERV_GET, TFTP_SERV_PUT ...) will expand with
+time as we add more tests.
+
+Having checked that an order looks generally valid, and set up some
+environment, it then switches on the order to execute a test script to do
+what the testcase that sent the order wants.  The extra params are given to
+the test script.  The test script is invoked in background, so that several
+sessions can be running at once to hit the target board hard, or of course
+one network testing server can be servicing several target boards running
+different testcases all at once.  After the test script is launched,
+obey.sh just loops back to reading an input line, to get the next order.
+
+"XFAIL" in parameter 1 means the target is configured to simulate network
+unreliability, or otherwise be uncooperative.  It is passed both to the
+individual testing scripts and to the system for returning status messages
+to the test target.
+
+This structure is designed to allow separate development and testing of the
+individual parts of the network testing server and also of new testcases;
+the eCos testcase and its test script can be developed on your desk without
+running the network test server - you only need to knit them all together
+at the end by adding a simple clause to obey.sh to invoke the test script
+automatically.
+
+
+Test Script Environment
+-----------------------
+
+There is some IO redirection nastiness in obey.sh to separate errors from
+good status from status to return to the eCos testcase and so on.
+
+awaitorder takes care to issue complaints to stderr, whilst obviously its
+stdout is piped in to obey.sh
+
+obey.sh takes care to issue problem reports to stderr, and mere commentary
+to stdout; neither is paricularly verbose right now, so there's no need to
+so anything special.
+
+Individual test scripts are invoked as follows.  Stdout is directed to a
+logfile named uniquely and for the test in question, according the the
+variable $LG.  Stderr is piped to an acknowledgement agent, by default
+"./sendack.sh", which is invoked with the target address as its argument.
+This returns status messages from the host testing script to the eCos
+testcase via TCP port 9990.
+
+Let's look at the two example switch cases for the TFTP tests.  There are
+two to mostly put versus mostly get files with the eCos TFTP server.
+
+    # Now the main swicth that runs the test script: this is where
+    # new testcases are added:
+    case $TEST in
+
+    TFTP_SERV_GET)
+    tftpget.sh $TARGET $WF/tftpget.$unique ${PARAMS[@]} \
+           2>&1 >$LG/tftpget.$unique | $SENDACK $TARGET & ;;
+
+    TFTP_SERV_PUT)
+    tftpput.sh $TARGET $WF/tftpput.$unique ${PARAMS[@]} \
+           2>&1 >$LG/tftpput.$unique | $SENDACK $TARGET & ;;
+
+OK, this is horrid.  But breaking up one example:
+
+this first part is the invokation of the script:
+
+    tftpput.sh $TARGET $WF/tftpput.$unique ${PARAMS[@]}
+
+its arguments are
+
+    tftpput.sh <target IP> <temporary file> <timeout> <filesize>
+
+ o <target IP> is $TARGET, from the original order.
+
+ o obey.sh has invented <temporary file> with a unique id, in the workfiles
+   directory, $WF.  It will typically be "/tmp/auto/wf/tftpput.1138".  In
+   this example, the test script will make files called
+   "/tmp/auto/wf/tftpput.1138.src" and "/tmp/auto/wf/tftpput.1138.tmp" to
+   play with; one is created by the tmpfile program, the other read back
+   from the TFTP server.
+
+ o <timeout> is part of the extra params supplied by the eCos testcase,
+   which in this case will serve TFTP for about 5 minutes, so it tells the
+   test script to diddle it for about 5 minutes too.
+
+ o <filesize> is another param supplied by the eCos testcase, which tells
+   the script to create a testfile of a particular size to exercise edge
+   conditions wrt the blocksize.
+
+The second part of the example is the IO redirection and backgrounding:
+
+           2>&1 >$LG/tftpput.$unique | $SENDACK $XFAIL $TARGET & ;;
+
+This sets the script's fd2 to a copy of its stdout, then sets its stdout to
+go to the logfile, typically "/tmp/auto/log/tftpput.1138", then pipes the
+original stdout which now occupies fd2 into $SENDACK, the acknowledgement
+agent, which is itself invoked with the target's IP address and optionally
+XFAIL to tell it not to be so upset if it fails to return the result.  The
+whole thing is run in background by the "&" and the ";;" is the end of this
+case within the switch statement.  Phew!
+
+More briefly, the test script's stdout goes into the logfile and the test
+script's stderr goes into $SENDACK (./sendack.sh) and thence to the
+testcase.
+
+
+Typical Output
+--------------
+
+This is the output from awaitorder | obey.sh from running just one eCos
+testcase, which requests 3 simultaneous TFTP sessions for 5 minutes:
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+awaitorder: connection from 10.16.19.171:34554
+test TFTP_SERV_PUT; target 10.16.19.171; params 300 512
+awaitorder: connection from 10.16.19.171:46052
+test TFTP_SERV_PUT; target 10.16.19.171; params 300 513
+awaitorder: connection from 172.16.19.171:25388
+test TFTP_SERV_PUT; target 172.16.19.171; params 300 512
+10.16.19.171: result INFO:<10.16.19.171 is up>
+172.16.19.171: result INFO:<172.16.19.171 is up>
+10.16.19.171: result INFO:<10.16.19.171 is up>
+10.16.19.171: result PASS:<tftp put OK, 300 seconds 513 bytes 20696 xfers>
+10.16.19.171: result PASS:<tftp put OK, 300 seconds 512 bytes 14982 xfers>
+172.16.19.171: result PASS:<tftp put OK, 300 seconds 512 bytes 12649 xfers>
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+and the eCos test case prints, amongst other things, on receipt of the
+results via sendack.sh
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+INFO:<10.16.19.171 is up> (10.16.19.171) (from 10.16.19.13:4764)
+INFO:<172.16.19.171 is up> (172.16.19.171) (from 172.16.19.13:4765)
+INFO:<10.16.19.171 is up> (10.16.19.171) (from 10.16.19.13:4766)
+....
+PASS:<tftp put OK, 300 seconds 513 bytes 20696 xfers> (10.16.19.171) (from 10.16.19.13:4775)
+PASS:<tftp put OK, 300 seconds 512 bytes 14982 xfers> (10.16.19.171) (from 10.16.19.13:4776)
+PASS:<tftp put OK, 300 seconds 512 bytes 12649 xfers> (172.16.19.171) (from 172.16.19.13:4777)
+....
+PASS:<Results from host[s] OK>
+EXIT:<Done>
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+This output format will change over time as more features may be added, but
+this example should convey the general idea.
+
+
+Individual Host Testing Scripts
+-------------------------------
+
+The params and invocation of these is entirely a matter of agreement
+between the eCos testcase and the test script.  A new case arm in the
+obey.sh switch statement must be written for any new testcase, so the
+script's invocation is not prescribed in any way.
+
+For the sake of easier separate development of testcases, it would be
+better to follow the pattern of the other testcases, also for consistency
+and comprehensibility.  Here are some guidelines and requirements, but
+first some assumptions:
+
+ o One test script "does things to" one target board, and more specifically
+   one target IP address.  If you want several things done to your target
+   board at once, invoke several scripts at once - all on the same IP
+   address if you want, that's fine.
+
+ o The test script may need to be told that the target network stack is
+   configured to simulate network unreliability, so the test script should
+   not expect perfect communications.  Eg. weaker protocols will in fact
+   fail - the point of the test is verify that the target does not hang or
+   crash or assert-fail and so on; host side network failures within the
+   script are unimportant.  Otherwise, the test script should expect
+   correct operation in the operations it performs.
+
+ o The network test server can serve testing to many eCos target boards at
+   once.  Therefore any particular test script can be invoked several times
+   at once to deal with different target boards, if they happen at random
+   to run the same testcase at the same time as each other.  Therefore a
+   test script should only use temporary files which are uniquely named per
+   invocation.
+
+These lead to requirements and guidelines:
+
+ o Take the flag XFAIL optionally as the first argument, if it is XFAIL
+   shift to get the other arguments.
+
+ o Take the target IP address as the next argument; it's an obvious place
+   for it and you'll certainly need it anyhow.
+
+ o For workfiles, have obey.sh supply a parameter to name such files
+   uniquely.  Use a full pathname.  Include the test type also, for example
+   "/tmp/auto/wf/tftpput.1138" identifies the file as belonging to the
+   tftpput testcase.  Make required workfiles be second and subsequent
+   arguments.
+
+ o Further arguments which are arbitrary and passed from the testcase
+   should be last, and passed all together.  It's not convenient in the
+   shell to split out words 2 through the end from an array if you already
+   quoted word one elsewhere, so instead put all the extras together as in
+   ${PARAMS[@]} in the tftpput.sh invocation discussed above.
+
+
+Other Environment
+-----------------
+
+ o DHCP
+
+Set up DHCP to support the target board - it's the easiest way.
+
+The tests know which server to talk to by looking in the server ID field of
+the bootp information record; if DHCP or BOOTP is used, this will be the
+server that served it.  It is also possible to set up the stack with static
+initialization of that field - if you do this, make sure it points to a
+machine that is running the network test server.
+
+Setting up the server to serve DHCP to the target boards only is easy;
+keeping other DHCP servers, who offer dynamic addresses to any new net
+presence, from offering service to them requires a little trick.  A dynamic
+server should be set up to supply a static address to the target board's
+MAC address, with the additional key: "deny booting;".  This does nothing
+malicious, but it lets the server recognize the target board and ignore it.
+
+This ensures that the network test server machine "wins" the race to set up
+the target, and so ensures that the test talks to the network test server
+rather than trying to talk to a global DHCP server.
+
+
+ o /tmp clearance
+
+The ongoing testing fills /tmp with log files and work files.  The logs
+will likely not be very large, but the work files could be a few Mb per
+test run.
+
+A cron job to remove everything older than an hour, or some such might be
+useful; or if the machine can stand it, just wipe /tmp/auto every night.
+
+
+ o Ping!
+
+The tests will expect to ping (and flood ping) the server; it should be
+allowed to do this back.  An suid executable (CARE!) is needed to enable
+this.  "./_suping" is built by the host makefile: make it be suid root.
+It is a trivial app that execs ping after setting the effective UID to
+root.  This is necessary because ping is an suid-root executable anyway, to
+be able to get at raw sockets; it checks the effective UID to decide
+whether to permit flood pinging; we need this for the flood tests floodping
+and floodpingmux.
+
+
+ o Network aliases in the loopback interface
+
+The routing tests require a network setup like this:
+
+  10.0.3.1      A.B.C.D   A.B.C.E        N.M.O.P   N.M.O.Q      10.0.4.1
+  -------- Box1 ----------------- target ----------------- Box2 --------
+
+
+Optionally with 10.0.3 and 10.0.4 being real networks, with other stations
+on them; addresses 10.0.x.99 are also pinged.  Alternatively, 10.0.3 and
+10.0.4 can be aliases for the loopback device in Box1 and Box2 (which may
+be the same box really).  A typical setup might really look like:
+             
+  HOST: eth0 172.16.19.13 ------ 172.16.19.171 eth0 on TARGET
+  HOST: eth1 10.16.19.13 -------- 10.16.19.171 eth1 on TARGET
+  HOST: lo:0 10.0.3.1
+  HOST: lo:1 10.0.4.1
+
+with all netmasks being /24 (255.255.255.0).
+
+This means that the target can only ping addresses 10.0.3.x and 10.0.4.x if
+a route has been set up via 172.16.19.13 or 10.16.19.13 (respectively, for
+the case of having two distinct hosts).  The routing tests verify that
+behaviour.
+
+
+ o TFTP server and its files
+
+No test of the eCos TFTP client yet, so no details here.
+
+ o FTP server and its files
+
+No test for the eCos FTP client yet, so no details here.
+
+
+
+.fin
diff --git a/packages/net/autotest/v2_0/doc/strategy.txt b/packages/net/autotest/v2_0/doc/strategy.txt
new file mode 100644 (file)
index 0000000..aa7c40d
--- /dev/null
@@ -0,0 +1,237 @@
+
+Some Thoughts on Automated Network Testing for eCos
+***************************************************
+
+Hugo Tyson, Red Hat, Cambridge UK, 2000-07-28
+
+
+Requirements
+============
+
+This thinking is dominated by the need for automated continuous testing
+of the StrongARM EBSA-285 boards, which have two ethernet interfaces.
+We also have some needs for ongoing eCos network testing.
+
+ o TCP testing: move a large amount of data, checking its correctness.
+   (with several streams running in parallel at once)
+
+ o UDP testing: similar but using UDP.
+
+ o TFTP testing: an external server, from a choice of LINUX, NT, SunOS, and
+   another EBSA board, get from the target some files, of sizes 0, 1, 512,
+   513, 1048576 bytes.  (with several streams running in parallel at once)
+
+ o TFTP testing: put to the target some files, ....
+
+ o TFTP testing: the target tftp client code does the same, getting and
+   putting, to an external server.
+
+   [ All that TFTP test makes explicit testing of UDP unneccessary; UDP
+   testing would need sequence numbers and so on, so we may as well use
+   TFTP as the implementation of that]
+
+ o FTP test: we have a trivial "connect" test; continue to use it.
+
+ o Performance testing: TCP_ECHO, TCP_SOURCE, TCP_SINK programs work in
+   concert to measure throughput of a partially loaded target board.
+   Source and Sink apps run on an external host.
+
+ o Flood pings: the target floods the hosts on its two external interfaces
+   whilst they flood it.  This is left going for a long time, and store
+   leaks or crashes are checked for.
+
+Orthogonally to these "feature tests" are requirements to run these tests
+with and without these features in combinations:
+
+ o The "realtime test harness" operating - it checks interrupt latencies
+   and so on.  This is written and works.
+
+ o Booting statically, via bootp, via DHCP statically/leased on the two
+   interfaces in combination.
+
+ o Simulated failure of the network, of the kinds "drop 1 in N packets",
+   "drop all for 0 < random() < 30 Seconds" and the like.  Corrupted
+   packets being sent out by the target, also!
+
+Needs
+---------------
+
+We have some other requirements:
+
+ o Support testing of other net-enabled targets!
+
+ o Run tests at a reasonable rate, so do NOT require a reboot of, say, a
+   LINUX host every test run to reconfigure the network environment.
+
+ o Feasible: do NOT require anything too complex in terms of controlling
+   the network environment.
+
+ o Do not use too many machines.  The farm is full already.
+
+
+Other Goals
+-----------
+
+These are some ideas that are useful but not strictly necessary:
+
+ o Re-use/work-with the existing test infrastructure
+
+ o Provide the sort of results information that the existing test
+   infrastructure does.
+
+ o Work with standard testing *host* computers of various kinds.
+
+ o Support conveniently debugging these test examples at developers' desks
+   - not just in the farm.
+
+
+Details
+=======
+
+Because of the flood pinging and malformed packet requirements, the target
+boards need to be on an isolated network.
+
+The target board's two interfaces need to be on distinct networks for the
+stack to behave properly.
+
+
+
+Strategy
+========
+
+I believe we can implement everything we need for the host computers to do
+using a daemon or server, (cf. the serial test filter) which sits on the
+host computer waiting to be told what test we are about to run, and takes
+appropriate action.
+
+Note that this does work even for situations where the target is passive,
+eg. being a TFTP server.  The target simply "does" TFTP serving for a set
+period of time - or perhaps until a cookie file exists in its test file
+system - and then performs a set of consistency checks (including on the
+state of the test FS), thus creating a PASS/FAIL test result.  It can also
+periodically run those checks anyway, and choose FAIL at any time.
+
+But who tells the host daemon what to do?  The target does, of course.
+That way, the host is stateless, it simply runs that daemon doing what it's
+bid, and does NOT ever have to report test results.  This has enormous
+advantages, because it means we gather test results from what the target
+said, and no other source, thus minimizing changes to the farm software.
+It also means that to add a new test, we can asynchronously add the feature
+to the test daemons of that is required, then add a new testcase in the
+usual manner, with all the usual (compile-time) testing of its
+applicability as usual.
+
+Network Topology
+----------------
+
+The idea is that we can initially have a setup like this:
+
+    house network <---> [net-testfarm-machine] serial -------+
+                                                             |
+                                                           serial
+    house network <----> eth0 [LINUX BOX] eth1 <---> eth0 [ EBSA ]
+                              [ dhcpd   ] eth2 <---> eth1 [      ]
+                              [ tftpd   ]
+                              [ ftpd    ]
+                              [ testd   ]
+
+for developing the system.  Testd is our new daemon that runs tcp_sink, or
+tcp_source, or a floodping, or does tftp to the target (rather than vice
+versa) as and when the target instructs it.  The target can report test
+results to the net-testfarm-machine as usual, but with bigger timeouts &c
+configured in the test farm.
+
+This system can then be generalized to
+
+        test-server1            test-server2            test-serverN
+           eth0                   eth0                     eth0
+            |                      |                        |
+            |                      |                        |
+           eth0                    |                        |
+        target1                 target4                 targetM
+           target2                target5                 targetM+1
+              target3               target6                 targetM+2
+           eth1
+            |
+            |
+        test-server11
+                
+where target1,2,3 have 2 ethernet interfaces and the others have only one.
+
+And further, provided the testd protocol supports targets choosing one
+server from many which offer service, which would be a good thing:
+
+        test-server1            test-server2            test-serverN
+           eth0                   eth0                     eth0
+         [LINUX]                 [Solaris]                [NT4.0]
+            |                      |                        |
+            +----------------------+------------------------+
+            |                      |                        |
+           eth0                    |                        |
+        target1                 target4                 targetM
+           target2                target5                 targetM+1
+              target3               target6                 targetM+2
+           eth1
+            |
+            +-----------------------+
+            |                       |
+         [LINUX]                 [NT4.0]
+        test-server11          test-server12
+
+which would IMHO be a good thing IN ADDITION to a completely partitioned
+set of test network as above.  The partitioned set of test networks is
+required also because we need to test all of:
+
+ Target asks for BOOTP vs. DHCP  -X-  Server does only BOOTP vs. DHCP
+
+in combinations on the different interfaces.  Simply setting up servers
+that way statically is best, rather than trying to script controls for
+servers that have them offering bootp one minute and DHCP the next.
+
+
+Test Farm
+---------
+
+Orthogonal to the network topology, the network test farm is connected to
+all these targets in the usual manner by serial lines.  That way the tests
+can run and busy/cripple that local network without affecting the house
+network *and* without affecting the debug connection, and with the
+advantage that tests net traffic can interfere with each other, providing a
+diverse network environment for testing, rather than a quiet net.
+
+For testing with GDB connection over the network, which is desirable, I
+suggest either keeping those machines separate, or having the farm's
+connection into the test-net be via second interfaces fitted to the server
+machines.
+
+Otherwise, it's a standard test farm, which knows to choose only from a
+special set of perms, and which has waaay longer timeouts.
+
+
+Test Cases
+----------
+
+In this way, tests of the form "make an external machine do tftp to the
+target board" are implemented by means of a standard eCos test case, which
+requests that action from a server, then waits for it to be told AOK or
+just for a certain time, and reports as such to the test farm as usual.
+
+These special tests are only compiled in certain perms.
+
+Those same special perms select between the various initialization options
+required also: DHCP or BOOTP or static initialization, and so on, in the
+usual manner.
+
+
+Implementation
+--------------
+
+Just a quick note on this: DHCP has a lot of the properties we want for the
+test protocol.  We should take a copy of that and use different port
+numbers, re-use a lot of the code, since server code is also available.
+
+Or something simpler; none of this seems especially challenging.
+
+
+That's all for now.
+.ends
diff --git a/packages/net/autotest/v2_0/host/_suping.c b/packages/net/autotest/v2_0/host/_suping.c
new file mode 100644 (file)
index 0000000..6689f2e
--- /dev/null
@@ -0,0 +1,14 @@
+// _suping.c
+
+#include <unistd.h>
+
+// This a piece of lameness to convince ping to do a floodping.
+int main( int argc, char **argv )
+{
+    setuid( 0 );
+    execvp( "ping", argv );
+    perror( "What, no ping?" );
+    exit( 1 );
+}
+
+// EOF
diff --git a/packages/net/autotest/v2_0/host/awaitorder.c b/packages/net/autotest/v2_0/host/awaitorder.c
new file mode 100644 (file)
index 0000000..c2c34ab
--- /dev/null
@@ -0,0 +1,153 @@
+//==========================================================================
+//
+//      awaitorder.c
+//
+//      Await an order from the target, and print it out...
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <stdio.h>
+
+#include <net/if.h>
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <netinet/ip_icmp.h>
+#include <net/route.h>
+
+void
+pexit(char *s)
+{
+    perror(s);
+    exit(1);
+}
+
+#define SOURCE_PORT 9980
+
+int main( int argc, char **argv )
+{
+    int s_source, e_source;
+    struct sockaddr_in e_source_addr, local;
+    int one = 1;
+    int len;
+    char orders[256];
+    char ack[] = "Acknowledged\n";
+    int loop = 1;
+
+    if ( 2 < argc ) {
+    usage:
+        fprintf( stderr, "usage: %s [once|many]\n", argv[0] );
+        exit(1);
+    } 
+
+    if ( 2 == argc ) {
+        if ( !strcmp( "once", argv[1] ) )
+            loop = 0;
+        else if ( !strcmp( "many", argv[1] ) )
+            loop = 1;
+        else 
+            goto usage;
+    }
+
+    s_source = socket(AF_INET, SOCK_STREAM, 6 /* TCP */ );
+    if (s_source < 0) {
+        pexit("stream socket");
+    }
+
+
+    memset(&local, 0, sizeof(local));
+    local.sin_family = AF_INET;
+    local.sin_len = sizeof(local);
+    local.sin_port = ntohs(SOURCE_PORT);
+    local.sin_addr.s_addr = INADDR_ANY;
+    if(bind(s_source, (struct sockaddr *) &local, sizeof(local)) < 0) {
+        pexit("bind /source/ error");
+    }
+    if (setsockopt(s_source, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
+        pexit("setsockopt /source/ SO_REUSEADDR");
+    }
+#ifdef SO_REUSEPORT
+    if (setsockopt(s_source, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one))) {
+        pexit("setsockopt /source/ SO_REUSEPORT");
+    }
+#endif
+
+    listen(s_source, SOMAXCONN);
+
+    do {
+        len = sizeof(e_source_addr);
+        if ((e_source = accept(s_source,
+                 (struct sockaddr *)&e_source_addr, &len)) < 0) {
+            pexit("accept /source/");
+        }
+        fprintf( stderr, "awaitorder: connection from %s:%d\n", 
+                 inet_ntoa(e_source_addr.sin_addr), ntohs(e_source_addr.sin_port));
+        
+        // Wait for "source" to tell us the orders
+        if ( 0 >= (len = read(e_source, orders, sizeof(orders)))) {
+            pexit("Can't read orders");
+        }
+        if ( sizeof(ack) != write(e_source, ack, sizeof( ack ) ) ) {
+            pexit("Can't write ACK");
+        }
+
+        orders[len] = 0;
+
+        printf( "ORDERS: %s\n", orders );
+        fflush( stdout );
+
+        close( e_source );
+    } while ( loop );
+
+    close( s_source );
+}
+// EOF awaitorder.c
diff --git a/packages/net/autotest/v2_0/host/floodping.sh b/packages/net/autotest/v2_0/host/floodping.sh
new file mode 100755 (executable)
index 0000000..dc5e181
--- /dev/null
@@ -0,0 +1,86 @@
+#!/bin/sh
+
+# timeout is the total time to run the test, or thereabouts.
+#
+# ping/rest times are to let us do stuff like flood for 3 seconds then do
+# nothing for 5 seconds, over the total test time.
+#
+# That way this script can be used to torment other test variants such as
+# the SNMP walk, ordinary pinging and so on, all making for a more diverse
+# test environment.
+
+
+if [ $# -lt 1 ]; then
+    echo "Usage: $0 [XFAIL] target [timeout [size [ping rest]]" > /dev/stderr
+    exit 1
+fi
+
+[ "xXFAIL" == "x$1" ] && { XFAIL="XFAIL"; shift; }
+TARGET=$1
+if [ "x" == "x$2" ]; then TIMEOUT=10;   else TIMEOUT=$2;  fi
+if [ "x" == "x$3" ]; then PINGSIZE=64;  else PINGSIZE=$3; fi
+if [ "x" == "x$4" ]; then PINGTIME=19;  else PINGTIME=$4; fi
+if [ "x" == "x$5" ]; then RESTTIME=1;   else RESTTIME=$5; fi
+
+# By default, flood for 19 seconds then rest for one.
+# We take one second off occasionally to allow eg. DHCP to stay alive in
+# configurations/environments where it is so short lived.
+
+if [ "x$XFAIL" != "xXFAIL" ]; then
+    # first try normal size packets
+    if ping -n -c 5 $TARGET > /dev/null ; then
+       echo "INFO:<$$: $TARGET is up>" > /dev/stderr
+    else
+       echo "FAIL:<$$: $TARGET is down>" > /dev/stderr; exit 1
+    fi
+fi
+
+# allow other pingers &c to start up:
+sleep 5
+
+declare -i COUNT=0
+
+# then the size we were asked to do, for the time requested
+
+while [ $SECONDS -le $TIMEOUT ]; do
+
+# Use an explicit path in '.' because this must be an SUID script to be
+# able to use the flood option.  Direct stderr to tmp also because we
+# cannot report results whilst flooding.
+./_suping -f -n -w $PINGTIME -q -s $PINGSIZE $TARGET > /tmp/ping$$ 2>&1
+
+# dump this out for the controller logfile
+cat /tmp/ping$$
+
+INFO1=$(grep "bytes of data" /tmp/ping$$)
+INFO2=$(grep "packet loss" /tmp/ping$$)
+INFO3=$(grep "round-trip" /tmp/ping$$)
+
+rm -f /tmp/ping$$
+
+# but do not print it all out to stderr (and so to sendack and over the
+# net); the two cannot coexist reliably.
+
+#[ "x" != "x$INFO1" ] && echo "INFO:<$$: $INFO1>" > /dev/stderr
+#[ "x" != "x$INFO2" ] && echo "INFO:<$$: $INFO2>" > /dev/stderr
+#[ "x" != "x$INFO3" ] && echo "INFO:<$$: $INFO3>" > /dev/stderr
+
+# then a delay for other traffic - else other tests fail
+sleep $RESTTIME
+
+((COUNT++));
+done
+
+# allow other flood pingers to finish:
+sleep 5
+
+if [ "x$XFAIL" == "xXFAIL" ]; then
+    echo "PASS:<$$: flood ping XFAIL, $PINGSIZE bytes $TIMEOUT seconds $COUNT sessions>" > /dev/stderr
+    exit 0
+fi
+
+# we cannot really look for pass/fail from a flood ping...
+
+echo "PASS:<$$: flood ping OK, $PINGSIZE bytes $TIMEOUT seconds $COUNT sessions>" > /dev/stderr
+
+# EOF
diff --git a/packages/net/autotest/v2_0/host/makefile b/packages/net/autotest/v2_0/host/makefile
new file mode 100644 (file)
index 0000000..c684bac
--- /dev/null
@@ -0,0 +1,19 @@
+
+all: awaitorder tmpfile _suping
+
+awaitorder: awaitorder.c
+       gcc -g -o awaitorder awaitorder.c
+
+
+tmpfile: tmpfile.c
+       gcc -g -o tmpfile tmpfile.c
+
+_suping: _suping.c
+       gcc -g -o _suping _suping.c
+       @echo "*** Don't forget to   chown root _suping; chmod u+sx _suping   ***"
+
+clean:
+       rm -f tmpfile
+       rm -f awaitorder
+       rm -f _suping
+       rm -f *~
diff --git a/packages/net/autotest/v2_0/host/obey.sh b/packages/net/autotest/v2_0/host/obey.sh
new file mode 100755 (executable)
index 0000000..d7c5dee
--- /dev/null
@@ -0,0 +1,83 @@
+#!/bin/sh
+
+if [ $# -gt 1 ]; then
+    echo "Usage: $0 [acknowledgement-agent]" > /dev/stderr
+    exit 1
+fi
+
+# add . to the path for testing.
+export PATH=$PATH:.
+
+# get a script for returning results to the testcase; its API is
+#      echo .... | SENDACK [XFAIL] <target>
+if [ $# -gt 0 ]; then
+    SENDACK=$1; shift
+else
+    SENDACK=sendack.sh
+fi
+
+TMP=/tmp/auto  ;# root of temporary filespace
+
+WF=${TMP}/wf   ;# work files for tftp et al
+LG=${TMP}/log  ;# log files for individual tests
+
+declare -i unique=0 ;# unique IDs for workfiles and logfiles
+
+while [ true ]; do
+
+    ((unique++))
+
+    read -a ORDERS || {        echo "FAIL: EOF on read" > /dev/stderr; exit 1; }
+
+    set ${ORDERS[@]}
+
+    [ "xQUIT" == "x$1" ] && break
+
+    [ "xORDERS:" != "x$1" ] && \
+       { echo "No ORDERS tag" > /dev/stderr; continue; }
+
+    XFAIL=""; [ "xXFAIL" == "x$2" ] && { XFAIL="XFAIL"; shift; }
+
+    shift; TEST=$1
+    shift; TARGET=$1
+    shift; PARAMS=($@)
+
+    echo "test $TEST [$XFAIL]; target $TARGET; params ${PARAMS[@]}"
+
+    # Be robust against zealous GC of workfiles - as late as possible
+    # before we use them, it's in the read above that we sleep.
+    [ ! -d ${TMP} ] && mkdir ${TMP}
+    [ ! -d ${WF}  ] && mkdir ${WF}
+    [ ! -d ${LG}  ] && mkdir ${LG}
+
+    # Now the main switch that runs the test script: this is where
+    # new testcases are added:
+    case $TEST in
+
+    TFTP_SERV_GET)
+    tftpget.sh $XFAIL $TARGET $WF/tftpget.$unique ${PARAMS[@]} \
+           2>&1 >$LG/tftpget.$unique   | $SENDACK $XFAIL $TARGET & ;;
+
+    TFTP_SERV_PUT)
+    tftpput.sh $XFAIL $TARGET $WF/tftpput.$unique ${PARAMS[@]} \
+           2>&1 >$LG/tftpput.$unique   | $SENDACK $XFAIL $TARGET & ;;
+
+    SLOW_PING)
+    slowping.sh $XFAIL $TARGET ${PARAMS[@]} \
+           2>&1 >$LG/slowping.$unique  | $SENDACK $XFAIL $TARGET & ;;
+
+    FLOOD_PING)
+    floodping.sh $XFAIL $TARGET ${PARAMS[@]} \
+           2>&1 >$LG/floodping.$unique  | $SENDACK $XFAIL $TARGET & ;;
+
+    SNMP_WALK)
+    snmpwalk.sh $XFAIL $TARGET ${PARAMS[@]} \
+           2>&1 >$LG/snmpwalk.$unique  | $SENDACK $XFAIL $TARGET & ;;
+
+    *) echo "Unknown order $TEST" > /dev/stderr ;;
+
+    esac
+
+done
+
+# EOF
diff --git a/packages/net/autotest/v2_0/host/sendack.sh b/packages/net/autotest/v2_0/host/sendack.sh
new file mode 100755 (executable)
index 0000000..a808c18
--- /dev/null
@@ -0,0 +1,42 @@
+#!/bin/sh
+
+if [ $# -gt 2 ] || [ $# -lt 1 ]; then
+    echo "Usage: $0 [XFAIL] target-IP [port]" > /dev/stderr
+    exit 1
+fi
+
+[ "xXFAIL" == "x$1" ] && { XFAIL="XFAIL"; shift; }
+
+TARGET=$1; shift
+
+PORT=9990; [ "x" != "x$1" ] && { PORT=$1; shift; }
+
+while [ true ]; do
+
+    read -a RESULT || {        exit 0; }
+
+    echo "$TARGET: result ${RESULT[@]}"
+
+    # I really want it to try quite hard to get the message through
+    # (but not too hard if XFAIL)
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    { sleep 1 && { \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    { sleep 3 && { \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    { [ "x$XFAIL" != "xXFAIL" ] && sleep 5 && { \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    { sleep 10 && { \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    echo "${RESULT[@]} ($TARGET)" > /dev/tcp/$TARGET/$PORT || \
+    echo "***FAILED TO SEND RESULT TO $TARGET: result ${RESULT[@]}" \
+    ;};};};};};};};}
+    # brute force seems as good as any means...
+
+done
+
+# EOF
diff --git a/packages/net/autotest/v2_0/host/slowping.sh b/packages/net/autotest/v2_0/host/slowping.sh
new file mode 100755 (executable)
index 0000000..2a2a9af
--- /dev/null
@@ -0,0 +1,50 @@
+#!/bin/sh
+
+if [ $# -lt 1 ]; then
+    echo "Usage: $0 [XFAIL] target [timeout [size]]" > /dev/stderr
+    exit 1
+fi
+
+[ "xXFAIL" == "x$1" ] && { XFAIL="XFAIL"; shift; }
+TARGET=$1
+if [ "x" == "x$2" ]; then TIMEOUT=10;   else TIMEOUT=$2; fi
+if [ "x" == "x$3" ]; then PINGSIZE=64;  else PINGSIZE=$3; fi
+
+if [ "x$XFAIL" != "xXFAIL" ]; then
+    # first try normal size packets
+    if ping -n -c 5 $TARGET > /dev/null ; then
+       echo "INFO:<$$: $TARGET is up>" > /dev/stderr
+    else
+       echo "FAIL:<$$: $TARGET is down>" > /dev/stderr; exit 1
+    fi
+fi
+
+# then the size we were asked to do, for the time requested
+ping -n -c $TIMEOUT -s $PINGSIZE $TARGET > /tmp/ping$$ && PINGRESULT=ok
+
+# dump this out for the controller logfile
+cat /tmp/ping$$
+
+INFO1=$(grep "bytes of data" /tmp/ping$$)
+INFO2=$(grep "packet loss" /tmp/ping$$)
+INFO3=$(grep "round-trip" /tmp/ping$$)
+
+rm -f /tmp/ping$$
+
+[ "x" != "x$INFO1" ] && echo "INFO:<$$: $INFO1>" > /dev/stderr
+[ "x" != "x$INFO2" ] && echo "INFO:<$$: $INFO2>" > /dev/stderr
+[ "x" != "x$INFO3" ] && echo "INFO:<$$: $INFO3>" > /dev/stderr
+
+if [ "x$XFAIL" == "xXFAIL" ]; then
+    echo "PASS:<$$: slow ping XFAIL, $PINGSIZE bytes $TIMEOUT packets/seconds>" > /dev/stderr
+    exit 0
+fi
+
+if [ "x" == "x$PINGRESULT" ]; then
+    echo "FAIL:<$$: slow ping failed, $PINGSIZE bytes $TIMEOUT packets/seconds>" > /dev/stderr
+    exit 1
+fi
+
+echo "PASS:<$$: slow ping OK, $PINGSIZE bytes $TIMEOUT packets/seconds>" > /dev/stderr
+
+# EOF
diff --git a/packages/net/autotest/v2_0/host/snmpwalk.sh b/packages/net/autotest/v2_0/host/snmpwalk.sh
new file mode 100755 (executable)
index 0000000..d6a4896
--- /dev/null
@@ -0,0 +1,51 @@
+#!/bin/sh
+
+if [ $# -lt 1 ]; then
+    echo "Usage: $0 [XFAIL] target [timeout]" > /dev/stderr
+    exit 1
+fi
+
+[ "xXFAIL" == "x$1" ] && { XFAIL="XFAIL"; shift; }
+TARGET=$1
+if [ "x" == "x$2" ]; then TIMEOUT=10;   else TIMEOUT=$2;  fi
+
+if [ "x$XFAIL" != "xXFAIL" ]; then
+    # first try normal size packets
+    if ping -n -c 5 $TARGET > /dev/null ; then
+       echo "INFO:<$$: $TARGET is up>" > /dev/stderr
+    else
+       echo "FAIL:<$$: $TARGET is down>" > /dev/stderr; exit 1
+    fi
+fi
+
+export MIBS=all
+
+declare -i COUNT=0
+declare -i FAILS=0
+
+# then the size we were asked to do, for the time requested
+
+while [ $SECONDS -le $TIMEOUT ]; do
+
+snmpwalk -OS $TARGET public
+
+snmpstatus $TARGET public || { ((FAILS++)); [ "x$XFAIL" == "xXFAIL" ]; } || break
+
+((COUNT++));
+
+done
+
+
+if [ "x$XFAIL" == "xXFAIL" ]; then
+    echo "PASS:<$$: snmpwalk XFAIL, $TIMEOUT seconds $COUNT snmpwalks $FAILS failed>" > /dev/stderr
+    exit 0
+fi
+
+if [ $FAILS -ne 0 ]; then
+    echo "FAIL:<$$: snmpwalk $TIMEOUT seconds $COUNT snmpwalks - status failed>" > /dev/stderr
+    exit 1
+fi
+
+echo "PASS:<$$: snmpwalk $TIMEOUT seconds $COUNT snmpwalks>" > /dev/stderr
+
+# EOF
diff --git a/packages/net/autotest/v2_0/host/tftpget.sh b/packages/net/autotest/v2_0/host/tftpget.sh
new file mode 100755 (executable)
index 0000000..090d786
--- /dev/null
@@ -0,0 +1,104 @@
+#!/bin/sh
+
+if [ $# -lt 1 ]; then
+    echo "Usage: $0 target [tempfile [timeout [filesize]]]" > /dev/stderr
+    exit 1
+fi
+
+[ "xXFAIL" == "x$1" ] && { XFAIL="XFAIL"; shift; }
+TARGET=$1
+if [ "x" == "x$2" ]; then TMP=tftpdata; else TMP=$2; fi
+if [ "x" == "x$3" ]; then TIMEOUT=10;   else TIMEOUT=$3; fi
+if [ "x" == "x$4" ]; then SIZE=unknown; else SIZE=$4; fi
+
+if [ -f $TMP ]; then
+    SRC=${TMP}
+    TMP=${TMP}.tmp
+else
+    SRC=${TMP}.src
+    TMP=${TMP}.tmp
+fi
+
+if [ -f $SRC ]; then
+    [ $SIZE == unknown ] ||  \
+    { echo "FAIL: '$SRC' exists but size given" > /dev/stderr; exit 1; }
+else
+    [ $SIZE == unknown ] && SIZE=876543
+    tmpfile $SRC $SIZE $$ || \
+    { echo "FAIL: Sourcefile '$SRC' create" > /dev/stderr; exit 1; }
+fi
+
+if [ ! -f $SRC ]; then
+    echo "FAIL: Sourcefile '$SRC' not found" > /dev/stderr; exit 1
+fi
+
+if [ "x$XFAIL" != "xXFAIL" ]; then
+    if ping -n -c5 $TARGET > /dev/null ; then
+       echo "INFO:<$$: $TARGET is up>" > /dev/stderr
+    else
+       echo "FAIL:<$$: $TARGET is down>" > /dev/stderr; exit 1
+    fi
+fi
+
+tftp $TARGET  <<-EOF
+       rexmt 1
+       binary
+       put $SRC $TMP
+EOF
+
+declare -i COUNT=0
+declare -i FAILS=0
+
+# This test is to test tftp GET not PUT so gloss over one failed put
+# (ie. if it reports corrupt the first time, put it again).
+rm -f $TMP
+tftp $TARGET  <<-EOF
+       rexmt 1
+       binary
+       get $TMP $TMP
+EOF
+if ! cmp -s $SRC $TMP; then
+echo "INFO:<$$: putting $SIZE bytes to $TARGET a second time>"
+tftp $TARGET  <<-EOF
+       rexmt 1
+       binary
+       put $SRC $TMP
+EOF
+else
+((COUNT++));
+fi
+
+while [ $SECONDS -le $TIMEOUT ]; do
+rm -f $TMP
+tftp $TARGET  <<-EOF
+       rexmt 1
+       binary
+       get $TMP $TMP
+EOF
+[ -f $TMP ]       || [ "x$XFAIL" == "xXFAIL" ] || break
+cmp -s $SRC $TMP  || { ((FAILS++)); [ "x$XFAIL" == "xXFAIL" ]; } || break
+((COUNT++));
+done
+
+if [ "x$XFAIL" == "xXFAIL" ]; then
+    echo "PASS:<$$: tftp get XFAIL, $TIMEOUT seconds $SIZE bytes $FAILS/$COUNT fails>" > /dev/stderr
+    exit 0
+fi
+
+if [ 1 -lt $FAILS ]; then
+    echo "FAIL:<$$: wierd, multiple failures $FAILS in $COUNT xfers>" > /dev/stderr
+fi
+
+if [ ! -f $TMP ]; then
+    echo "FAIL:<$$: temp file $TMP nonexistent $COUNT xfers>" > /dev/stderr
+    exit 1
+fi
+
+if ! cmp -s $SRC $TMP; then
+    echo "FAIL:<$$: temp file $TMP corrupt $COUNT xfers>" > /dev/stderr
+    exit 1
+fi
+
+echo "PASS:<$$: tftp get OK, $TIMEOUT seconds $SIZE bytes $COUNT xfers>" > /dev/stderr
+
+# EOF
diff --git a/packages/net/autotest/v2_0/host/tftpput.sh b/packages/net/autotest/v2_0/host/tftpput.sh
new file mode 100755 (executable)
index 0000000..049dd8b
--- /dev/null
@@ -0,0 +1,80 @@
+#!/bin/sh
+
+if [ $# -lt 1 ]; then
+    echo "Usage: $0 target [tempfile [timeout [filesize]]]" > /dev/stderr
+    exit 1
+fi
+
+[ "xXFAIL" == "x$1" ] && { XFAIL="XFAIL"; shift; }
+TARGET=$1
+if [ "x" == "x$2" ]; then TMP=tftpdata; else TMP=$2; fi
+if [ "x" == "x$3" ]; then TIMEOUT=10;   else TIMEOUT=$3; fi
+if [ "x" == "x$4" ]; then SIZE=unknown; else SIZE=$4; fi
+
+if [ -f $TMP ]; then
+    SRC=${TMP}
+    TMP=${TMP}.tmp
+else
+    SRC=${TMP}.src
+    TMP=${TMP}.tmp
+fi
+
+if [ -f $SRC ]; then
+    [ $SIZE == unknown ] ||  \
+    { echo "FAIL: '$SRC' exists but size given" > /dev/stderr; exit 1; }
+else
+    [ $SIZE == unknown ] && SIZE=876543
+    tmpfile $SRC $SIZE $$ || \
+    { echo "FAIL: Sourcefile '$SRC' create" > /dev/stderr; exit 1; }
+fi
+
+if [ ! -f $SRC ]; then
+    echo "FAIL: Sourcefile '$SRC' not found" > /dev/stderr; exit 1
+fi
+
+if [ "x$XFAIL" != "xXFAIL" ]; then
+    if ping -n -c5 $TARGET > /dev/null ; then
+       echo "INFO:<$$: $TARGET is up>" > /dev/stderr
+    else
+       echo "FAIL:<$$: $TARGET is down>" > /dev/stderr; exit 1
+    fi
+fi
+
+declare -i COUNT=0
+
+# Just put the file without checking the data; the get test tests that.
+while [ $SECONDS -le $TIMEOUT ]; do
+tftp $TARGET  <<-EOF
+       rexmt 1
+       binary
+       put $SRC $TMP
+EOF
+((COUNT++));
+done
+
+if [ "x$XFAIL" == "xXFAIL" ]; then
+    echo "PASS:<$$: tftp put XFAIL, $TIMEOUT seconds $SIZE bytes $COUNT tries>" > /dev/stderr
+    exit 0
+fi
+
+# Verify it once at the end.
+rm -f $TMP
+tftp $TARGET  <<-EOF
+       rexmt 1
+       binary
+       get $TMP $TMP
+EOF
+
+if [ ! -f $TMP ]; then
+    echo "FAIL:<$$: temp file $TMP nonexistent $COUNT xfers>" > /dev/stderr
+    exit 1
+fi
+
+if ! cmp -s $SRC $TMP; then
+    echo "FAIL:<$$: temp file $TMP corrupt $COUNT xfers>" > /dev/stderr
+    exit 1
+fi
+
+echo "PASS:<$$: tftp put OK, $TIMEOUT seconds $SIZE bytes $COUNT xfers>" > /dev/stderr
+
+# EOF
diff --git a/packages/net/autotest/v2_0/host/tmpfile.c b/packages/net/autotest/v2_0/host/tmpfile.c
new file mode 100644 (file)
index 0000000..33b379c
--- /dev/null
@@ -0,0 +1,144 @@
+//==========================================================================
+//
+//      tmpfile.c
+//
+//      Make a temporary data file for test purposes
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt
+// Contributors: hmt
+// Date:         2000-10-23
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <stdio.h>
+#include <errno.h>
+
+int main( int argc, char **argv )
+{
+    FILE *f;
+    int i;
+    unsigned int size, iirandom, z, csum;
+    char sizec, scratchc;
+
+    if ( 3 > argc || 4 < argc) {
+    usage:
+        fprintf( stderr, "usage: %s filename length [seed]\n", argv[0] );
+        exit(1);
+    } 
+
+    f = fopen( argv[1], "rb" );
+    if ( f ) {
+        fclose( f );
+        fprintf( stderr, "File %s already exists\n", argv[1] );
+        goto usage;
+    }
+
+    i = sscanf( argv[2], "%u%1c%1c", &size, &sizec, &scratchc );
+    if ( 0 >= i || 2 < i )
+        goto usage;
+
+    if ( 2 == i ) 
+        switch ( sizec ) {
+        case 'G': size *= 1024;
+        case 'M': size *= 1024;
+        case 'k': size *= 1024;
+            break;
+        case 'b': size *= 512;
+            break;
+        default:
+            goto usage;
+        }
+
+    iirandom = 0;
+    if ( 4 == argc ) {
+        i = sscanf( argv[3], "%u%1c", &iirandom, &scratchc );
+        if ( 0 >= i || 1 < i )
+            goto usage;
+    }
+
+    f = fopen( argv[1], "wb" );
+    if ( !f ) {
+        perror( "fopen [create]" );
+        goto usage;
+    }
+
+    csum = 0;
+    iirandom += 0x23164920; // What date said
+
+    if ( size > 4 ) i = size-4; else i = size;
+
+    for ( /* i */ ; i > 0; i-- ) {
+        iirandom = iirandom * 91 + 137;
+        iirandom ^= iirandom >> 14 | iirandom << 7;
+        z = (i ^ iirandom) & 0xff;
+        // Keep a simple checksum in case we make some trick to check it in
+        // the pretend filesystem.
+        csum += z;
+        csum = (csum >> (z & 31)) ^ (csum << (32 - (z & 31)));
+        if ( 0 > putc( z, f ) ) {
+            perror( "putc" );
+            fclose( f );
+            exit( 1 );
+        }
+    }
+    // And bung the checksum on the end.
+    for ( i = 4 ; i < size && i > 0; i-- ) {
+        z = csum & 0xff;
+        csum >>= 8;
+        if ( 0 > putc( z, f ) ) {
+            perror( "putc" );
+            fclose( f );
+            exit( 1 );
+        }
+    }
+    fclose( f );
+    exit( 0 );
+}
+
+// EOF awaitorder.c
diff --git a/packages/net/autotest/v2_0/permtests/netauto_bootp.ptest b/packages/net/autotest/v2_0/permtests/netauto_bootp.ptest
new file mode 100644 (file)
index 0000000..6e4d3fe
--- /dev/null
@@ -0,0 +1,13 @@
+
+# add the net and the net drivers
+pkgconf -disable-uitron -enable-net -enable-net_drivers -enable-autotest
+
+# asserts on
+header infra.h {
+       enable CYGPKG_INFRA_DEBUG
+}
+
+# no DHCP, just bootp
+header net.h {
+       disable CYGPKG_NET_DHCP
+}
diff --git a/packages/net/autotest/v2_0/permtests/netauto_corrupt.ptest b/packages/net/autotest/v2_0/permtests/netauto_corrupt.ptest
new file mode 100644 (file)
index 0000000..717f75d
--- /dev/null
@@ -0,0 +1,19 @@
+
+# add the net and the net drivers, and the SNMP parts
+pkgconf -disable-uitron -enable-net -enable-net_drivers -enable-snmplib -enable-snmpagent -enable-autotest
+
+# larger heap for SNMP to run?  Not needed any more.
+
+# asserts on
+header infra.h {
+        enable CYGPKG_INFRA_DEBUG
+}
+
+# Simulated failures on:
+header io_eth_drivers.h {
+       enable CYGPKG_IO_ETH_DRIVERS_SIMULATED_FAILURES
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_DROP_RX      
+       value CYGPKG_IO_ETH_DRIVERS_SIMULATE_CORRUPT_RX  10
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_DROP_TX    
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_LINE_CUT
+}
diff --git a/packages/net/autotest/v2_0/permtests/netauto_failrx.ptest b/packages/net/autotest/v2_0/permtests/netauto_failrx.ptest
new file mode 100644 (file)
index 0000000..3f3bd65
--- /dev/null
@@ -0,0 +1,19 @@
+
+# add the net and the net drivers, and the SNMP parts
+pkgconf -disable-uitron -enable-net -enable-net_drivers -enable-snmplib -enable-snmpagent -enable-autotest
+
+# larger heap for SNMP to run?  Not needed any more.
+
+# asserts on
+header infra.h {
+        enable CYGPKG_INFRA_DEBUG
+}
+
+# Simulated failures on:
+header io_eth_drivers.h {
+       enable CYGPKG_IO_ETH_DRIVERS_SIMULATED_FAILURES
+       value   CYGPKG_IO_ETH_DRIVERS_SIMULATE_DROP_RX    10   
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_CORRUPT_RX
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_DROP_TX    
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_LINE_CUT
+}
diff --git a/packages/net/autotest/v2_0/permtests/netauto_failtx.ptest b/packages/net/autotest/v2_0/permtests/netauto_failtx.ptest
new file mode 100644 (file)
index 0000000..66953e5
--- /dev/null
@@ -0,0 +1,19 @@
+
+# add the net and the net drivers, and the SNMP parts
+pkgconf -disable-uitron -enable-net -enable-net_drivers -enable-snmplib -enable-snmpagent -enable-autotest
+
+# larger heap for SNMP to run?  Not needed any more.
+
+# asserts on
+header infra.h {
+        enable CYGPKG_INFRA_DEBUG
+}
+
+# Simulated failures on:
+header io_eth_drivers.h {
+       enable CYGPKG_IO_ETH_DRIVERS_SIMULATED_FAILURES
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_DROP_RX      
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_CORRUPT_RX
+       value   CYGPKG_IO_ETH_DRIVERS_SIMULATE_DROP_TX   10 
+       disable CYGPKG_IO_ETH_DRIVERS_SIMULATE_LINE_CUT
+}
diff --git a/packages/net/autotest/v2_0/permtests/netauto_rt.ptest b/packages/net/autotest/v2_0/permtests/netauto_rt.ptest
new file mode 100644 (file)
index 0000000..3307199
--- /dev/null
@@ -0,0 +1,13 @@
+
+# add the net and the net drivers, and the SNMP parts
+pkgconf -disable-uitron -enable-net -enable-net_drivers -enable-snmplib -enable-snmpagent -enable-autotest
+
+# larger heap for SNMP to run?  Not needed any more.
+
+# use the RealTime test harness, and two loopback interfaces
+header net.h {
+       enable CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS
+       value  CYGPKG_NET_NLOOP 2
+}
+
+
diff --git a/packages/net/autotest/v2_0/permtests/netauto_snmp.ptest b/packages/net/autotest/v2_0/permtests/netauto_snmp.ptest
new file mode 100644 (file)
index 0000000..41183ec
--- /dev/null
@@ -0,0 +1,11 @@
+
+# add the net and the net drivers, and the SNMP parts
+pkgconf -disable-uitron -enable-net -enable-net_drivers -enable-snmplib -enable-snmpagent -enable-autotest
+
+# larger heap for SNMP to run?  Not needed any more.
+
+# asserts on
+header infra.h {
+        enable CYGPKG_INFRA_DEBUG
+}
+
diff --git a/packages/net/autotest/v2_0/permtests/netauto_std.ptest b/packages/net/autotest/v2_0/permtests/netauto_std.ptest
new file mode 100644 (file)
index 0000000..4c7dc44
--- /dev/null
@@ -0,0 +1,10 @@
+
+# add the net and the net drivers
+pkgconf -disable-uitron -enable-net -enable-net_drivers -enable-autotest
+
+
+# asserts on
+header infra.h {
+        enable CYGPKG_INFRA_DEBUG
+}
+
diff --git a/packages/net/autotest/v2_0/tests/autohost.inl b/packages/net/autotest/v2_0/tests/autohost.inl
new file mode 100644 (file)
index 0000000..03df503
--- /dev/null
@@ -0,0 +1,367 @@
+//==========================================================================
+//
+//      tests/auto/autohost.inl
+//
+//      Automated Testing by a Host Computer
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-18
+// Purpose:      Automated testing of the eCos TCP/IP Network Stack
+// Description:  
+
+//     This .inl file defines routines which send /orders/ to the server
+//     running on the host machine who served us DHCP, and receive
+//     /results/ from the same machine or machines.
+//
+//     autohost_tell() sends the order to an app "awaitorder" which feeds
+//     the order into obey.sh which obeys the order, for example, running
+//     some tftp sessions to exercise the tftp server.
+//
+//     The /orders/ must come from a predefined list, to match the
+//     selection which obey.sh is expecting, for example "TFTP_SERV_GET"
+//     which has further parameters <target> <timeout>.  Additional
+//     parameters are added/manipulated by obey.sh which then invokes a
+//     relevent script (tftpget.sh) to do the test.
+//
+//     The test script's output is returned to us, and is collected by
+//     autohost_getresults() which runs in a high-ist prio thread.  It
+//     prints the output, which is expected to match the traditional eCos
+//     PASS:<happy> FAIL:<eek!> sort of format, so that the test farm can
+//     collect these messages from the testcase output, without any direct
+//     connection to the server.
+//
+//     autohost_init() simply starts the autohost_getresults() thread.
+//
+//     The predefined list of orders is *not* defined here or anywhere
+//     else besides obey.sh which does a switch statement for them, to
+//     make it easier to extent; similarly the params each order takes are
+//     not centrally recorded either.  It is however a convention that the
+//     word following the /order/ is our own IP address.
+//
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include "memcheck.inl"                 // check on memory usage
+
+externC int sprintf( char * /* str */, const char * /* format */, ... );
+
+// ------------------------------------------------------------------------
+
+#include <pkgconf/system.h>
+#ifdef CYGPKG_IO_ETH_DRIVERS
+#include <pkgconf/io_eth_drivers.h>
+#endif
+
+#if defined(XFAIL) || defined(XPASS)
+// So that the test can override this automation
+# if defined(XFAIL) && defined(XPASS)
+#  error Both XFAIL and XPASS predefined
+# endif
+# undef XFAIL
+# ifndef XPASS
+#  define XFAIL "XFAIL"
+# endif
+#else
+# ifdef CYGPKG_IO_ETH_DRIVERS_SIMULATED_FAILURES
+// Then we must tell the test server to expect failures.
+#  define XFAIL "XFAIL"
+# endif
+#endif // XFAIL/XPASS not predefined
+
+// ------------------------------------------------------------------------
+
+void
+pexit(char *s)
+{
+    TNR_OFF();
+    CYG_TEST_FAIL_EXIT( s );
+}
+
+// ------------------------------------------------------------------------
+
+#define SOURCE_PORT 9980
+#define RESULT_PORT 9990
+
+static int
+autohost_tell( struct bootp *bp, char *orders )
+{
+    int s_host;
+    struct sockaddr_in slave, local;
+    int one = 1;
+    int len = strlen( orders );
+    char ack[32];
+    int ret;
+
+    char complete_order[256];
+
+    if ( len > 240 )
+        pexit( "Orders too long" );
+
+    memset(&slave, 0, sizeof(slave));
+    slave.sin_family = AF_INET;
+    slave.sin_len = sizeof(slave);
+    slave.sin_port = htons(SOURCE_PORT);
+    slave.sin_addr = bp->bp_siaddr; // Talk to our DHCP server
+
+    s_host = socket(AF_INET, SOCK_STREAM, 0);
+    if (s_host < 0) {
+        pexit("stream socket");
+    }
+
+    memset(&local, 0, sizeof(local));
+    local.sin_family = AF_INET;
+    local.sin_len = sizeof(local);
+    local.sin_port = INADDR_ANY;
+    local.sin_addr.s_addr = INADDR_ANY;
+    if(bind(s_host, (struct sockaddr *) &local, sizeof(local)) < 0) {
+        pexit("bind /source/ error");
+   }
+    if (setsockopt(s_host, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
+        pexit("setsockopt /source/ SO_REUSEADDR");
+    }
+
+    ret = connect(s_host, (struct sockaddr *)&slave, sizeof(slave));
+    if ( ret < 0) {
+        TNR_OFF();
+        diag_printf(
+            "Connect failed %d err %d, s_host %d, sin_port %x, sin_addr %08x\n", 
+                    ret, errno, s_host, slave.sin_port, slave.sin_addr.s_addr );
+        pexit("Can't connect to target");
+    }
+
+    sprintf( complete_order,
+#ifdef XFAIL
+             "%s %s", XFAIL,
+#else
+             "%s",
+#endif
+             orders );
+    len = 1 + strlen( complete_order ); // Send the null also
+
+    if ( len != write(s_host, (unsigned char *)complete_order, len ) ) {
+        pexit("Can't send orders");
+    }
+    ret = read(s_host, (unsigned char *)&ack, sizeof(ack));
+    if ( 0 >= ret ) {
+        pexit("Can't get ACK");
+    }
+    close(s_host);
+    return 1;
+}
+
+// ---------------------------------------------------------------------------
+
+#define nHALTAFTERFAIL
+#ifdef HALTAFTERFAIL
+static cyg_alarm ahr_fail_alarm;
+static cyg_handle_t ahr_fail_alarm_handle = 0;
+static cyg_alarm_t ahr_fail_alarm_function;
+
+void ahr_fail_alarm_function(cyg_handle_t alarm, cyg_addrword_t data)
+{
+    CYG_TEST_FAIL_EXIT( "Failure reported by autohost" );
+}
+#endif
+
+static int result_passes = 0;
+static int result_fails  = 0;
+
+static void
+autohost_getresults( cyg_addrword_t loop )
+{
+    int s_source, e_source;
+    struct sockaddr_in e_source_addr, local;
+    int one = 1;
+    int len;
+    char result[256];
+
+    s_source = socket(AF_INET, SOCK_STREAM, 6 /* TCP */ );
+    if (s_source < 0) {
+        pexit("stream socket");
+    }
+
+    memset(&local, 0, sizeof(local));
+    local.sin_family = AF_INET;
+    local.sin_len = sizeof(local);
+    local.sin_port = ntohs(RESULT_PORT);
+    local.sin_addr.s_addr = INADDR_ANY;
+    if(bind(s_source, (struct sockaddr *) &local, sizeof(local)) < 0) {
+        pexit("bind /source/ error");
+    }
+    if (setsockopt(s_source, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) {
+        pexit("setsockopt /source/ SO_REUSEADDR");
+    }
+#ifdef SO_REUSEPORT
+    if (setsockopt(s_source, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one))) {
+        pexit("setsockopt /source/ SO_REUSEPORT");
+    }
+#endif
+
+    listen(s_source, SOMAXCONN);
+
+    do {
+        len = sizeof(e_source_addr);
+        if ((e_source = accept(s_source,
+                 (struct sockaddr *)&e_source_addr, &len)) < 0) {
+            pexit("accept /source/");
+        }
+        
+        // Wait for "source" to tell us the result
+        if ( 0 >= (len = read(e_source, result, sizeof(result)))) {
+            pexit("Can't read result");
+        }
+
+        result[len] = 0;
+        len--;
+        while( len && ('\r' == result[len] || '\n' == result[len]) )
+            result[len--] = 0;
+
+        TNR_OFF();
+        diag_printf( "%s (from %s:%d)\n", result,
+           inet_ntoa(e_source_addr.sin_addr), ntohs(e_source_addr.sin_port));
+        TNR_ON();
+
+        // Check for a pass message right now:
+        if ( 'P' == result[0] &&
+             'A' == result[1] &&
+             'S' == result[2] &&
+             'S' == result[3] ) {
+            result_passes++;
+        }
+        else
+        // Check for a failure right now:
+        if ( 'F' == result[0] &&
+             'A' == result[1] &&
+             'I' == result[2] &&
+             'L' == result[3] ) {
+            result_fails++;
+#ifdef HALTAFTERFAIL
+            // Wait a bit for the others, if any, to come in before halting
+            // the test, since the host is typically running multiple
+            // threads to torment us.  Set an alarm to go FAIL_EXIT in 20S.
+            if ( ! ahr_fail_alarm_handle ) {
+                cyg_handle_t h;
+                cyg_clock_to_counter(cyg_real_time_clock(), &h),
+                cyg_alarm_create(
+                    h,                       /* Attached to this ctr */
+                    ahr_fail_alarm_function, /* Call-back function   */
+                    0,                       /* Call-back data       */
+                    &ahr_fail_alarm_handle,  /* Returned alarm obj   */
+                    &ahr_fail_alarm          /* put alarm here       */
+                    );
+                cyg_alarm_initialize(
+                    ahr_fail_alarm_handle,
+                    cyg_current_time() + (20 * 100),
+                    0 );
+                cyg_alarm_enable( ahr_fail_alarm_handle );
+            }
+#endif
+        }
+
+        close( e_source );
+    } while ( loop );
+
+    close( s_source );
+}
+
+// ---------------------------------------------------------------------------
+
+static void autohost_end( int expected_passes )
+{
+#ifdef HALTAFTERFAIL
+    if ( ahr_fail_alarm_handle )
+        cyg_alarm_disable( ahr_fail_alarm_handle );
+#endif
+#ifdef XFAIL
+    if ( ! (result_passes >= expected_passes) )
+        CYG_TEST_INFO( "XFAIL: Not enough PASS results posted" );
+    if ( ! (0 == result_fails) )
+        CYG_TEST_INFO( "XFAIL: FAIL results posted" );
+    if ( ! (result_passes >= expected_passes && 0 == result_fails) )
+        CYG_TEST_PASS( "XFAIL: Pass anyway" );
+#else
+    CYG_TEST_CHECK( result_passes >= expected_passes,
+                    "Not enough PASS results posted" );
+    CYG_TEST_CHECK( 0 == result_fails,
+                    "FAIL results posted" );
+#endif
+    if ( result_passes >= expected_passes && 0 == result_fails )
+        CYG_TEST_PASS( "Results from host[s] OK" );
+
+    // Record and check final state of net stack memory consumption
+    memcheck_final();
+}
+
+// ---------------------------------------------------------------------------
+
+static char ahr_stack[ CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x400 ];
+static cyg_thread ahr_thread_data;
+
+static void autohost_init( void )
+{
+    cyg_handle_t ahr_thread_handle;
+    cyg_thread_create(    5,            // Priority - just a number
+           autohost_getresults,         // entry
+           1,                           // entry parameter
+           "Autohost result monitor",   // Name
+           &ahr_stack[0],               // Stack
+           sizeof(ahr_stack),           // Size
+           &ahr_thread_handle,          // Handle
+           &ahr_thread_data             // Thread data structure
+        );
+    cyg_thread_resume(ahr_thread_handle);  // Start it
+
+    // Record initial state of net stack memory consumption
+    memcheck_init();
+}
+
+// EOF autohost.inl
diff --git a/packages/net/autotest/v2_0/tests/floodping.c b/packages/net/autotest/v2_0/tests/floodping.c
new file mode 100644 (file)
index 0000000..e1ed0fd
--- /dev/null
@@ -0,0 +1,183 @@
+//==========================================================================
+//
+//      autotest/current/tests/floodping.c
+//
+//      Flood pinging test, the server floods me and little else.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#include "autohost.inl"
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_ping_tests(struct bootp *bp, int testtime, int filesize)
+{
+    char order[256];
+    diag_printf( "INFO: telling %s to run 1 flood ping for %d seconds, %d bytes\n",
+          inet_ntoa(bp->bp_siaddr), testtime, filesize );
+
+    sprintf( order, "%s %s %d %d", "FLOOD_PING",
+             inet_ntoa(bp->bp_yiaddr),
+             testtime,
+             filesize );
+    autohost_tell( bp, order );
+}
+
+#define TESTTIME (5 * 60) // Seconds
+
+void
+net_test(cyg_addrword_t param)
+{
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start PING server test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    TNR_INIT();
+    
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        do_ping_tests(&eth0_bootp_data, TESTTIME, 56);
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        do_ping_tests(&eth1_bootp_data, TESTTIME, 56);
+    }
+#endif
+
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the stuff start up first
+    TNR_ON();
+    cyg_thread_delay(TESTTIME*100); // FIXME - assume cS clock.
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( 0
+#ifdef CYGHWR_NET_DRIVER_ETH0
+                  + eth0_up
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+                  + eth1_up
+#endif
+        ); // check for 2 pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+void
+cyg_start(void)
+{
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+}
+
+// EOF floodping.c
diff --git a/packages/net/autotest/v2_0/tests/floodpingmux.c b/packages/net/autotest/v2_0/tests/floodpingmux.c
new file mode 100644 (file)
index 0000000..a5011d3
--- /dev/null
@@ -0,0 +1,466 @@
+//==========================================================================
+//
+//      autotest/current/tests/floodpingmux.c
+//
+//      Flood pinging test, the server floods me and I flood hir.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#define MAX_PACKET 4096
+
+#define NUMTHREADS 3
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + MAX_PACKET + MAX_PACKET + 0x1000)
+static char thread_stack[NUMTHREADS][STACK_SIZE];
+static cyg_thread thread_data[NUMTHREADS];
+static cyg_handle_t thread_handle[NUMTHREADS];
+
+#define DO_DUMPSTATS( seq ) (0 == (0xffff & seq))
+
+#ifdef CYGHWR_NET_DRIVER_ETH0
+struct sockaddr_in host0;
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+struct sockaddr_in host1;
+#endif
+static int sock;
+
+static int uniqueid[3] = { 0x1234, 0x4321, 0xdead };
+
+static int ok_recv[3] = { 0,0,0 };
+static int bogus_recv[3] = { 0,0,0 };
+static int pings_sent[3] = { 0,0,0 };
+
+// ------------------------------------------------------------------------
+static void dumpstats(void)
+{
+    TNR_OFF();
+    diag_printf( "------------------------\n" );
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        diag_printf("%16s: Sent %d packets, received %d OK, %d bad\n",
+                    inet_ntoa(host0.sin_addr), pings_sent[0],
+                    ok_recv[0], bogus_recv[0]);
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        diag_printf("%16s: Sent %d packets, received %d OK, %d bad\n",
+                    inet_ntoa(host1.sin_addr), pings_sent[1],
+                    ok_recv[1], bogus_recv[1]);
+    }
+#endif
+    if ( pings_sent[2] )
+        diag_printf("Wierd!  %d unknown sends!\n", pings_sent[2] );
+    if ( ok_recv[2] )
+        diag_printf("Wierd!  %d unknown good recvs!\n", ok_recv[2] );
+    if ( bogus_recv[2] )
+        diag_printf("Wierd!  %d unknown bogus recvs!\n", bogus_recv[2] );
+    diag_printf( "------------------------\n" );
+    TNR_ON();
+}
+
+
+// ------------------------------------------------------------------------
+// Compute INET checksum
+int
+inet_cksum(u_short *addr, int len)
+{
+    register int nleft = len;
+    register u_short *w = addr;
+    register u_short answer;
+    register u_int sum = 0;
+    u_short odd_byte = 0;
+
+    /*
+     *  Our algorithm is simple, using a 32 bit accumulator (sum),
+     *  we add sequential 16 bit words to it, and at the end, fold
+     *  back all the carry bits from the top 16 bits into the lower
+     *  16 bits.
+     */
+    while( nleft > 1 )  {
+        sum += *w++;
+        nleft -= 2;
+    }
+
+    /* mop up an odd byte, if necessary */
+    if( nleft == 1 ) {
+        *(u_char *)(&odd_byte) = *(u_char *)w;
+        sum += odd_byte;
+    }
+
+    /*
+     * add back carry outs from top 16 bits to low 16 bits
+     */
+    sum = (sum >> 16) + (sum & 0x0000ffff); /* add hi 16 to low 16 */
+    sum += (sum >> 16);                     /* add carry */
+    answer = ~sum;                          /* truncate to 16 bits */
+    return (answer);
+}
+
+// ------------------------------------------------------------------------
+static void
+show_icmp(unsigned char *pkt, int len, struct sockaddr_in *from)
+{
+    cyg_tick_count_t *tp, tv;
+    struct ip *ip;
+    struct icmp *icmp;
+    int which = 2;
+    tv = cyg_current_time();
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up && (from->sin_addr.s_addr == host0.sin_addr.s_addr) )
+        which = 0;
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up && (from->sin_addr.s_addr == host1.sin_addr.s_addr) )
+        which = 1;
+#endif
+
+    ip = (struct ip *)pkt;
+    if ((len < sizeof(*ip)) || ip->ip_v != IPVERSION) {
+        TNR_OFF();
+        diag_printf("%s: Short packet or not IP! - Len: %d, Version: %d\n", 
+                    inet_ntoa(from->sin_addr), len, ip->ip_v);
+        TNR_ON();
+        bogus_recv[which]++;
+        return;
+    }
+    icmp = (struct icmp *)(pkt + sizeof(*ip));
+    len -= (sizeof(*ip) + 8);
+    tp = (cyg_tick_count_t *)&icmp->icmp_data;
+    if (icmp->icmp_type != ICMP_ECHOREPLY) { 
+        TNR_OFF();
+        diag_printf("%s: Invalid ICMP - type: %d\n", 
+                    inet_ntoa(from->sin_addr), icmp->icmp_type);
+        TNR_ON();
+        bogus_recv[which]++;
+        return;
+    }
+    ok_recv[which]++;
+    if (icmp->icmp_id != uniqueid[which]) {
+        TNR_OFF();
+        diag_printf("%s: ICMP received for wrong id - sent: %x, recvd: %x\n", 
+                    inet_ntoa(from->sin_addr), uniqueid[which], icmp->icmp_id);
+        TNR_ON();
+    }
+//    diag_printf("%d bytes from %s: ", len, inet_ntoa(from->sin_addr));
+//    diag_printf("icmp_seq=%d", icmp->icmp_seq);
+//    diag_printf(", time=%dms\n", (int)(tv - *tp)*10);
+}
+
+// ------------------------------------------------------------------------
+static void
+floodrecv(cyg_addrword_t p)
+{
+    unsigned char pkt[MAX_PACKET];
+    struct sockaddr_in from;
+    int len, fromlen;
+
+    diag_printf("PING listener...\n" );
+    for (;;) {
+        // Wait for a response
+        fromlen = sizeof(from);
+        len = recvfrom(sock, pkt, sizeof(pkt), 0,
+                       (struct sockaddr *)&from, &fromlen);
+        if (len < 0)
+            perror("recvfrom");
+        else
+            show_icmp(pkt, len, &from);
+    }
+}
+
+// ------------------------------------------------------------------------
+static void
+pingsend( int seq, struct sockaddr_in *host,
+          struct icmp *icmp, int icmp_len, int which )
+{
+    cyg_tick_count_t *tp;
+    long *dp;
+    int i;
+    // Build ICMP packet for interface
+    icmp->icmp_type = ICMP_ECHO;
+    icmp->icmp_code = 0;
+    icmp->icmp_cksum = 0;
+    icmp->icmp_seq = seq;
+    icmp->icmp_id = uniqueid[which];
+    // Set up ping data
+    tp = (cyg_tick_count_t *)&icmp->icmp_data;
+    *tp++ = cyg_current_time();
+    dp = (long *)tp;
+    for (i = sizeof(*tp);  i < icmp_len;  i += sizeof(*dp))
+        *dp++ = i;
+
+    // Add checksum
+    icmp->icmp_cksum = inet_cksum( (u_short *)icmp, icmp_len+8);
+    // Send it off
+    if (sendto(sock, icmp, icmp_len+8, MSG_DONTWAIT,
+              (struct sockaddr *)host, sizeof(*host)) < 0) {
+        perror("sendto");
+    }
+    pings_sent[which]++;
+}
+
+// ------------------------------------------------------------------------
+static void
+floodsend(cyg_addrword_t param)
+{
+    unsigned char pkt0[MAX_PACKET], pkt1[MAX_PACKET];
+
+    struct icmp *icmp0 = (struct icmp *)pkt0;
+    struct icmp *icmp1 = (struct icmp *)pkt1;
+
+    int icmp_len = 64;
+    int seq;
+
+    for (seq = 0; 1 ; seq++) {
+        if ( DO_DUMPSTATS( seq ) )
+            dumpstats();
+
+#ifdef CYGHWR_NET_DRIVER_ETH0
+        if (eth0_up)
+            pingsend( seq, &host0, icmp0, icmp_len, 0 );
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+        if (eth1_up)
+            pingsend( seq, &host1, icmp1, icmp_len, 1 );
+#endif
+    }
+}
+
+
+// ------------------------------------------------------------------------
+
+#include "autohost.inl"
+
+static void
+do_ping_tests(struct bootp *bp, int testtime, int filesize)
+{
+    char order[256];
+    diag_printf( "INFO: telling %s to run 1 flood ping for %d seconds, %d bytes\n",
+          inet_ntoa(bp->bp_siaddr), testtime, filesize );
+
+    sprintf( order, "%s %s %d %d", "FLOOD_PING",
+             inet_ntoa(bp->bp_yiaddr),
+             testtime,
+             filesize );
+    autohost_tell( bp, order );
+}
+
+// ------------------------------------------------------------------------
+
+#define TESTTIME (5 * 60) // Seconds
+
+void
+net_test(cyg_addrword_t param)
+{
+    struct protoent *p;
+
+    diag_printf("Start Flood PING test\n");
+    init_all_network_interfaces();
+    diag_printf("Interfaces up:\n");
+
+    if ((p = getprotobyname("icmp")) == (struct protoent *)0) {
+        perror("getprotobyname");
+        return;
+    }
+    sock = socket(AF_INET, SOCK_RAW, p->p_proto);
+    if (sock < 0) {
+        perror("tx socket");
+        return;
+    }
+
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        host0.sin_family = AF_INET;
+        host0.sin_len = sizeof(host0);
+        host0.sin_addr = eth0_bootp_data.bp_siaddr;
+        host0.sin_port = 0;
+        diag_printf("PING server %16s\n", inet_ntoa(host0.sin_addr));
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        host1.sin_family = AF_INET;
+        host1.sin_len = sizeof(host1);
+        host1.sin_addr = eth1_bootp_data.bp_siaddr;
+        host1.sin_port = 0;
+        diag_printf("PING server %16s\n", inet_ntoa(host1.sin_addr));
+    }
+#endif
+    autohost_init();
+
+    TNR_INIT();
+    
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        do_ping_tests(&eth0_bootp_data, TESTTIME, 56);
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        do_ping_tests(&eth1_bootp_data, TESTTIME, 56);
+    }
+#endif
+
+    // And start the threads that make us ping them, and count the results
+    cyg_thread_resume(thread_handle[1]);
+    cyg_thread_resume(thread_handle[2]);
+
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the stuff start up first
+    TNR_ON();
+    cyg_thread_delay(TESTTIME*100); // FIXME - assume cS clock.
+
+    // Stop the threads that make us ping them.  Thread [2] is the pinger,
+    // thread [1] the receiver so that might as well continue.
+    cyg_thread_suspend(thread_handle[2]);
+
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( 0
+#ifdef CYGHWR_NET_DRIVER_ETH0
+                  + eth0_up
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+                  + eth1_up
+#endif
+        ); // check for 2 pass messages from hosts
+
+    diag_printf("After running:\n");
+    dumpstats();
+    TNR_OFF(); // dumpstats() turned it on again!
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+void
+cyg_start(void)
+{
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                     &thread_stack[0][0], // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle[0], // Handle
+                      &thread_data[0]    // Thread data structure
+            );
+    cyg_thread_resume(thread_handle[0]);  // Start it
+
+    // Create the secondary threads
+    cyg_thread_create(11,                // Priority - just a number
+                      floodrecv,         // entry
+                      0,                 // entry parameter
+                      "Flood Ping Recv", // Name
+                     &thread_stack[1][0], // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle[1], // Handle
+                      &thread_data[1]    // Thread data structure
+            );
+    cyg_thread_create(12,                // Priority - just a number
+                      floodsend,         // entry
+                      0,                 // entry parameter
+                      "Flood Ping Send", // Name
+                     &thread_stack[2][0], // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle[2], // Handle
+                      &thread_data[2]    // Thread data structure
+            );
+
+    cyg_scheduler_start();
+}
+
+// EOF floodpingmux.c
diff --git a/packages/net/autotest/v2_0/tests/memcheck.inl b/packages/net/autotest/v2_0/tests/memcheck.inl
new file mode 100644 (file)
index 0000000..617a7f2
--- /dev/null
@@ -0,0 +1,132 @@
+//==========================================================================
+//
+//      tests/auto/memcheck.inl
+//
+//      Automated Testing by a Host Computer
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt
+// Contributors: hmt
+// Date:         2000-11-10
+// Purpose:      Check memory usage of the eCos TCP/IP Network Stack
+// Description:  
+
+#ifndef CYG_NET_GET_MEM_STATS_MISC
+// API is not present, so dummies:
+void memcheck_init( void )  {}
+void memcheck_final( void ) {}
+#else
+
+#include <sys/mbuf.h>
+extern struct  mbstat mbstat;
+
+extern void cyg_kmem_print_stats( void );
+
+cyg_mempool_info initial[3], final[3];
+
+#define RATIO 15
+
+static char *names[3] = { "Misc", "Mbufs", "Clusters" };
+
+void memcheck_init( void )
+{
+    int i;
+
+    cyg_kmem_print_stats();
+
+    for ( i = 0; i < 3; i++ )
+        if ( ! cyg_net_get_mem_stats( i, initial + i ) )
+            CYG_TEST_FAIL( "Getting initial mem stats" );
+}
+
+void memcheck_final( void )
+{
+    int i;
+    for ( i = 0; i < 3; i++ )
+        if ( ! cyg_net_get_mem_stats( i, final + i ) )
+            CYG_TEST_FAIL( "Getting final mem stats" );
+
+    cyg_kmem_print_stats();
+
+    // NB do NOT check clusters (index 2) because clusters are managed
+    // differently.
+    for ( i = 0; i < 3; i++ ) {
+        int size = final[i].totalmem;
+        int initial_used = size - initial[i].freemem;
+        int margin = size * RATIO / 100;
+        int final_used = size - final[i].freemem;
+        int extra_used = final_used - initial_used;
+
+        if ( 2 == i ) {
+#ifdef XFAIL
+            // ignore clusters if a faulty network is being simulated
+            // because memory gets eaten for partial packets awaiting
+            // reassembly.
+            continue; 
+#else            
+            // Then it's clusters - they're managed differently
+            final_used -= (mbstat.m_clfree * final[i].blocksize);
+            extra_used = final_used - initial_used;
+#endif
+        }
+
+        // Using up up to whatever was initially used -or- the percentage
+        // we test for; whichever is larger, is OK.
+        if ( (extra_used > initial_used) && (extra_used > margin) ) {
+            CYG_TEST_INFO( "Memory leak suspected" );
+            CYG_TEST_INFO( names[i] );
+            CYG_TEST_INFO( (final[i].blocksize > 0) ?
+                           "Variable mempool" : "Fixed mempool" );
+            CYG_TEST_FAIL( "Too much memory used - storeleak suspected" );
+        }
+    }
+}
+
+#undef RATIO
+
+#endif
+
+// EOF memcheck.inl
diff --git a/packages/net/autotest/v2_0/tests/route_3.c b/packages/net/autotest/v2_0/tests/route_3.c
new file mode 100644 (file)
index 0000000..b747d7b
--- /dev/null
@@ -0,0 +1,76 @@
+//==========================================================================
+//
+//      autotest/current/tests/route_3.c
+//
+//      Simple pinging test, the server pings me and I ping her.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+// Check that we can be pinged by the host(s):
+#define DOHOSTPINGS
+
+// Add a route to net 10.0.3.x via eth0's server
+#define ADDROUTETONET_10_0_3_x
+
+// Add a route to net 10.0.4.x via eth1's server
+//#define ADDROUTETONET_10_0_4_x
+
+// Check the correct working of a global gateway:
+#define PING_WWW_CYGNUS_COM
+
+#include "routeping.inl"
+
+// EOF route_3.c
diff --git a/packages/net/autotest/v2_0/tests/route_3_4.c b/packages/net/autotest/v2_0/tests/route_3_4.c
new file mode 100644 (file)
index 0000000..ceaea91
--- /dev/null
@@ -0,0 +1,76 @@
+//==========================================================================
+//
+//      autotest/current/tests/route_3_4.c
+//
+//      Simple pinging test, the server pings me and I ping her.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+// Check that we can be pinged by the host(s):
+#define DOHOSTPINGS
+
+// Add a route to net 10.0.3.x via eth0's server
+#define ADDROUTETONET_10_0_3_x
+
+// Add a route to net 10.0.4.x via eth1's server
+#define ADDROUTETONET_10_0_4_x
+
+// Check the correct working of a global gateway:
+#define PING_WWW_CYGNUS_COM
+
+#include "routeping.inl"
+
+// EOF route_3_4.c
diff --git a/packages/net/autotest/v2_0/tests/route_4.c b/packages/net/autotest/v2_0/tests/route_4.c
new file mode 100644 (file)
index 0000000..26025ea
--- /dev/null
@@ -0,0 +1,76 @@
+//==========================================================================
+//
+//      autotest/current/tests/route_4.c
+//
+//      Simple pinging test, the server pings me and I ping her.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+// Check that we can be pinged by the host(s):
+#define DOHOSTPINGS
+
+// Add a route to net 10.0.3.x via eth0's server
+//#define ADDROUTETONET_10_0_3_x
+
+// Add a route to net 10.0.4.x via eth1's server
+#define ADDROUTETONET_10_0_4_x
+
+// Check the correct working of a global gateway:
+#define PING_WWW_CYGNUS_COM
+
+#include "routeping.inl"
+
+// EOF route_4.c
diff --git a/packages/net/autotest/v2_0/tests/route_none.c b/packages/net/autotest/v2_0/tests/route_none.c
new file mode 100644 (file)
index 0000000..29bfdd4
--- /dev/null
@@ -0,0 +1,76 @@
+//==========================================================================
+//
+//      autotest/current/tests/route_none.c
+//
+//      Simple pinging test, the server pings me and I ping her.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+// Check that we can be pinged by the host(s):
+#define DOHOSTPINGS
+
+// Add a route to net 10.0.3.x via eth0's server
+//#define ADDROUTETONET_10_0_3_x
+
+// Add a route to net 10.0.4.x via eth1's server
+//#define ADDROUTETONET_10_0_4_x
+
+// Check the correct working of a global gateway:
+#define PING_WWW_CYGNUS_COM
+
+#include "routeping.inl"
+
+// EOF route_none.c
diff --git a/packages/net/autotest/v2_0/tests/routeping.inl b/packages/net/autotest/v2_0/tests/routeping.inl
new file mode 100644 (file)
index 0000000..21c3ad3
--- /dev/null
@@ -0,0 +1,640 @@
+//==========================================================================
+//
+//      autotest/current/tests/routeping.inl
+//
+//      Simple pinging test, the server pings me and I ping her.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#include "autohost.inl"
+
+// ------------------------------------------------------------------------
+
+externC int sscanf( char * /* str */, const char * /* format */, ... );
+
+// ------------------------------------------------------------------------
+
+static int route_add_s( struct sockaddr_in *target,
+                        struct sockaddr_in *gw,
+                        int maskbits,
+                        int metric )
+{
+    struct ecos_rtentry route;
+    struct sockaddr_in mask;
+
+    int s;
+
+    memcpy( &mask, gw, sizeof(*gw) );
+    maskbits--;
+    mask.sin_addr.s_addr = htonl( (0xfffffffful ^ ((0x80000000ul >> maskbits)-1)) );
+
+    memset( &route, 0, sizeof(route) );
+
+    memcpy( &route.rt_dst    ,  target, sizeof(*target) );
+    memcpy( &route.rt_gateway,  gw    , sizeof(*gw) );
+    memcpy( &route.rt_genmask, &mask  , sizeof(mask) ); 
+
+    route.rt_flags = RTF_UP|RTF_GATEWAY;
+    route.rt_metric = metric;
+
+    route.rt_dev = NULL;
+
+    diag_printf("INFO:<Route - dst: %s",
+                inet_ntoa(((struct sockaddr_in *)&route.rt_dst)->sin_addr));
+    diag_printf(", mask: %s",
+                inet_ntoa(((struct sockaddr_in *)&route.rt_genmask)->sin_addr));
+    diag_printf(", gateway: %s>\n",
+                inet_ntoa(((struct sockaddr_in *)&route.rt_gateway)->sin_addr));
+
+    s = socket( AF_INET, SOCK_DGRAM, 0 );
+    if (s < 0) {
+        perror( "socket" );
+        return false;
+    }
+    if (ioctl(s, SIOCADDRT, &route)) {
+        perror("SIOCADDRT");
+        close(s);
+        return false;
+    }
+    diag_printf( "PASS:<Route added OK>\n" );
+    close(s);
+    return true;
+}
+
+
+
+int route_add( char *target,
+                      char *gw,
+                      int maskbits,
+                      int metric )
+{
+    struct sockaddr_in t_s, gw_s;
+    int ints[4];
+
+    memset( &t_s,  0, sizeof(t_s)  );
+    memset( &gw_s, 0, sizeof(gw_s) );
+
+    t_s.sin_len    = gw_s.sin_len    = sizeof(t_s);
+    t_s.sin_family = gw_s.sin_family = AF_INET;
+
+    if ( 4 != sscanf( target, "%d.%d.%d.%d", ints, ints+1, ints+2, ints+3 ) )
+        CYG_TEST_FAIL( "sscanf of target IP addr" );
+    else
+        t_s.sin_addr.s_addr = htonl( 
+            (ints[0] << 24) |
+            (ints[1] << 16) |
+            (ints[2] <<  8) |
+            (ints[3]      )  );
+    
+    if ( 4 != sscanf( gw, "%d.%d.%d.%d", ints, ints+1, ints+2, ints+3 ) )
+        CYG_TEST_FAIL( "sscanf of target IP addr" );
+    else
+        gw_s.sin_addr.s_addr = htonl( 
+            (ints[0] << 24) |
+            (ints[1] << 16) |
+            (ints[2] <<  8) |
+            (ints[3]      )  );
+
+    return route_add_s( &t_s, &gw_s, maskbits, metric );
+}
+
+// ------------------------------------------------------------------------
+
+#define NUM_PINGS 16
+#define MAX_PACKET 4096
+#define MIN_PACKET   64
+#define MAX_SEND   4000
+
+#define PACKET_ADD  ((MAX_SEND - MIN_PACKET)/NUM_PINGS)
+#define nPACKET_ADD  1 
+
+static unsigned char pkt1[MAX_PACKET], pkt2[MAX_PACKET];
+
+#define UNIQUEID 0x1234
+
+// Compute INET checksum
+int
+inet_cksum(u_short *addr, int len)
+{
+    register int nleft = len;
+    register u_short *w = addr;
+    register u_short answer;
+    register u_int sum = 0;
+    u_short odd_byte = 0;
+
+    /*
+     *  Our algorithm is simple, using a 32 bit accumulator (sum),
+     *  we add sequential 16 bit words to it, and at the end, fold
+     *  back all the carry bits from the top 16 bits into the lower
+     *  16 bits.
+     */
+    while( nleft > 1 )  {
+        sum += *w++;
+        nleft -= 2;
+    }
+
+    /* mop up an odd byte, if necessary */
+    if( nleft == 1 ) {
+        *(u_char *)(&odd_byte) = *(u_char *)w;
+        sum += odd_byte;
+    }
+
+    /*
+     * add back carry outs from top 16 bits to low 16 bits
+     */
+    sum = (sum >> 16) + (sum & 0x0000ffff); /* add hi 16 to low 16 */
+    sum += (sum >> 16);                     /* add carry */
+    answer = ~sum;                          /* truncate to 16 bits */
+    return (answer);
+}
+
+static int
+errshorts, errinvalids, errbadids, errwronghosts, errsendtos, errrecvfroms;
+#define ERRRESET() \
+errshorts=errinvalids=errbadids=errwronghosts=errsendtos=errrecvfroms=0
+
+static int
+check_icmp(unsigned char *pkt, int len, 
+          struct sockaddr_in *from, struct sockaddr_in *to)
+{
+    cyg_tick_count_t *tp, tv;
+    struct ip *ip;
+    struct icmp *icmp;
+    tv = cyg_current_time();
+    ip = (struct ip *)pkt;
+    if (len < sizeof(*ip))
+        if (ip->ip_v != IPVERSION) {
+        errshorts++;
+        return 0;
+    }
+    icmp = (struct icmp *)(pkt + sizeof(*ip));
+    len -= (sizeof(*ip) + 8);
+    tp = (cyg_tick_count_t *)&icmp->icmp_data;
+    if (icmp->icmp_type != ICMP_ECHOREPLY) {
+        errinvalids++;
+        return 0;
+    }
+    if (icmp->icmp_id != UNIQUEID) {
+        errbadids++;
+        return 0;
+    }
+    if (from->sin_addr.s_addr != to->sin_addr.s_addr) {
+        errwronghosts++;
+        return 0;
+    }
+    return 1;
+}
+
+// expect is
+// 0 - require failure
+// 1 - require success
+// 2 - don't care
+
+#define FAILURE_REQUIRED 0
+#define SUCCESS_REQUIRED 1
+#define NOTHING_REQUIRED 2
+
+static void
+ping_host(int s, struct sockaddr_in *host, int expect )
+{
+    struct icmp *icmp = (struct icmp *)pkt1;
+    int icmp_len = MIN_PACKET;
+    int seq, ok_recv, bogus_recv;
+    cyg_tick_count_t *tp;
+    long *dp;
+    struct sockaddr_in from;
+    int i, len, fromlen;
+
+    ERRRESET();
+    ok_recv = 0;
+    bogus_recv = 0;
+    TNR_OFF();
+    diag_printf("INFO:<PING server %s ....>\n", inet_ntoa(host->sin_addr));
+    for (seq = 0;  seq < NUM_PINGS;  seq++, icmp_len += PACKET_ADD ) {
+        TNR_ON();
+        cyg_thread_delay( 47 ); // Half a second...
+        // Build ICMP packet
+        icmp->icmp_type = ICMP_ECHO;
+        icmp->icmp_code = 0;
+        icmp->icmp_cksum = 0;
+        icmp->icmp_seq = seq;
+        icmp->icmp_id = 0x1234;
+        // Set up ping data
+        tp = (cyg_tick_count_t *)&icmp->icmp_data;
+        *tp++ = cyg_current_time();
+        dp = (long *)tp;
+        for (i = sizeof(*tp);  i < icmp_len;  i += sizeof(*dp)) {
+            *dp++ = i;
+        }
+        // Add checksum
+        icmp->icmp_cksum = inet_cksum( (u_short *)icmp, icmp_len+8);
+        // Send it off
+        if (sendto(s, icmp, icmp_len+8, 0, (struct sockaddr *)host, sizeof(*host)) < 0) {
+            errsendtos++;
+            continue;
+        }
+        // Wait for a response
+        fromlen = sizeof(from);
+        len = recvfrom(s, pkt2, sizeof(pkt2), 0, (struct sockaddr *)&from, &fromlen);
+        if (len < 0) {
+            errrecvfroms++;
+            icmp_len = MIN_PACKET - PACKET_ADD; // just in case - long routes
+        } else {
+            if ( check_icmp(pkt2, len, &from, host) )
+                ok_recv++;
+            else
+                bogus_recv++;
+        }
+    }
+    TNR_OFF();
+    diag_printf("INFO:<Sent %d packets, received %d OK, %d bad>\n", NUM_PINGS, ok_recv, bogus_recv);
+    if ( errsendtos + errrecvfroms )
+        diag_printf("INFO:<%d sendto errors, %d recvfrom errors>\n", errsendtos, errrecvfroms );
+
+    if ( SUCCESS_REQUIRED == expect ) {
+        CYG_TEST_CHECK( 0 < ok_recv, "No pings succeeded" );
+        CYG_TEST_CHECK( 0 == errsendtos, "Sendto failures" );
+#ifndef XFAIL
+        CYG_TEST_CHECK( NUM_PINGS/2 <  ok_recv, "Not enough pings succeeded" );
+        CYG_TEST_CHECK( NUM_PINGS/2 > bogus_recv, "Too many pings failed" );
+#endif
+    }
+    if ( FAILURE_REQUIRED == expect ) {
+        CYG_TEST_CHECK( 0 == ok_recv, "Pings succeeded" );
+        CYG_TEST_CHECK( bogus_recv + errsendtos + errrecvfroms == NUM_PINGS, "Not enough failures" );
+#ifndef XFAIL
+        CYG_TEST_CHECK( 0 == bogus_recv, "Some pings got bogus recv" );
+#endif
+    }
+    CYG_TEST_PASS( SUCCESS_REQUIRED == expect ? "Expected successful ping behaviour" :
+                   FAILURE_REQUIRED == expect ? "Expected failure ping behaviour" :
+                                                "Non-predicted ping behaviour" );
+
+    TNR_ON();
+    return;
+}
+
+static void
+ping_test(struct bootp *bp)
+{
+    struct protoent *p;
+    struct timeval tv;
+    struct sockaddr_in host;
+    int s;
+
+    if ((p = getprotobyname("icmp")) == (struct protoent *)0) {
+        pexit("getprotobyname");
+        return;
+    }
+    s = socket(AF_INET, SOCK_RAW, p->p_proto);
+    if (s < 0) {
+        pexit("socket");
+        return;
+    }
+    tv.tv_sec = 1;
+    tv.tv_usec = 0;
+    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+    // Set up host address
+    host.sin_family = AF_INET;
+    host.sin_len = sizeof(host);
+    host.sin_addr = bp->bp_siaddr;
+    host.sin_port = 0;
+    ping_host(s, &host, SUCCESS_REQUIRED );
+    // Now try a bogus host
+    host.sin_addr.s_addr = htonl(ntohl(host.sin_addr.s_addr) + 32);
+    ping_host(s, &host, NOTHING_REQUIRED ); // Success is optional
+    close(s);
+}
+
+static void
+station_ping(char *name, int expect)
+{
+    struct protoent *p;
+    struct timeval tv;
+    struct sockaddr_in host;
+    int s;
+
+    int ints[4];
+
+    if ((p = getprotobyname("icmp")) == (struct protoent *)0) {
+        pexit("getprotobyname");
+        return;
+    }
+    s = socket(AF_INET, SOCK_RAW, p->p_proto);
+    if (s < 0) {
+        pexit("socket");
+        return;
+    }
+    tv.tv_sec = 1;
+    tv.tv_usec = 0;
+    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+    // Set up host address
+    host.sin_family = AF_INET;
+    host.sin_len = sizeof(host);
+    host.sin_port = 0;
+
+    if ( 4 != sscanf( name, "%d.%d.%d.%d", ints, ints+1, ints+2, ints+3 ) )
+        CYG_TEST_FAIL( "sscanf of host IP addr" );
+    else {
+        host.sin_addr.s_addr = htonl( 
+            (ints[0] << 24) |
+            (ints[1] << 16) |
+            (ints[2] <<  8) |
+            (ints[3]      )  );
+            
+        ping_host(s, &host, expect );
+
+    }
+    close(s);
+}
+
+// ------------------------------------------------------------------------
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_ping_tests(struct bootp *bp, int N, int testtime, int filesize)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d pings for %d seconds, %d bytes and up\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime, filesize );
+
+    // For 2nd and subsequent orders, we vary the ping data size:
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d %d", "SLOW_PING",
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime,
+                 filesize + 100 * i );
+        autohost_tell( bp, order );
+    }
+}
+
+#define TESTTIME (5 * 60) // Seconds
+
+#define NUM_SESSIONS 10 // why not?
+
+// ------------------------------------------------------------------------
+//
+// The plan is as follows: 
+//
+// The host(s) will be set up so as to have additional interfaces as follows:
+//
+// eth0-host -> 10.0.3.1 and maybe others
+// eth1-host -> 10.0.4.1 and maybe others
+//              10.0.5.x should not exist
+//
+// These additional addresses can exist as extra loopback addresses, lo0:0,
+// lo0:1 and so on in a linux box.
+//
+// We want to ping all of the following:
+//
+// eth0-host           should always work
+// eth0-host+32                not expected to work
+// eth1-host           should always work
+// eth1-host+32                not expected to work
+// www.cygnus.com      should always work if default gw is correct
+// 10.0.3.1            should only work if route via eth0-host is added
+// 10.0.3.99           might work if route via eth0-host is added
+// 10.0.4.1            should only work if route via eth0-host is added
+// 10.0.4.99           might work if route via eth0-host is added
+// 10.0.5.1            should never work
+// 10.0.5.99           should never work
+//
+// So we test those places in the following contexts:
+// 
+// 1) No special routing added
+// 2) route via eth0-host to 10.0.3.x is added
+// 3) route via eth1-host to 10.0.4.x is added
+// 4) Both routes are added
+//
+// and check for correct operation and correct failure in all cases.
+//
+// Because of the time taken, these are separate test cases which include
+// this INL file after making suitable #defines.
+//
+// All the while, the hosts shall ping us, and when all is going we loop for
+// the rest of the test time.
+//
+
+void
+net_test(cyg_addrword_t param)
+{
+#ifdef DOHOSTPINGS
+    int i;
+    int numtests;
+#endif
+    int net3expect = FAILURE_REQUIRED;
+    int net4expect = FAILURE_REQUIRED;
+
+    cyg_tick_count_t ticks;
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start PING routing test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    TNR_INIT();
+
+#ifdef ADDROUTETONET_10_0_3_x
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        route_add( "10.0.3.0", inet_ntoa(eth0_bootp_data.bp_siaddr), 24, 1 );
+        net3expect = SUCCESS_REQUIRED;
+    }
+#endif
+#endif // ADDROUTETONET_10_0_3_x
+
+#ifdef ADDROUTETONET_10_0_4_x
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        route_add( "10.0.4.0", inet_ntoa(eth1_bootp_data.bp_siaddr), 24, 1 );
+        net4expect = SUCCESS_REQUIRED;
+    }
+#endif
+#endif // ADDROUTETONET_10_0_4_x
+
+    numtests = NUM_SESSIONS; // The number of pingers started OK
+    i = numtests;
+#ifdef DOHOSTPINGS
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        do_ping_tests(&eth0_bootp_data, 1, TESTTIME, 64);
+        do_ping_tests(&eth0_bootp_data, 1, TESTTIME, 2000);
+        i -= 2;
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up && i > 0) {
+        do_ping_tests(&eth1_bootp_data, 1, TESTTIME, 100);
+        do_ping_tests(&eth1_bootp_data, 1, TESTTIME, 1800);
+        i -= 2;
+    }
+#endif
+#endif // DOHOSTPINGS
+    numtests -= i; // Adjust to how many we *actually* requested
+
+    ticks = cyg_current_time() + TESTTIME * 100; // FIXME - assume cS clock.
+
+    // Let the server run for 5 minutes
+    TNR_ON();
+
+    while (1) {
+#ifdef CYGHWR_NET_DRIVER_ETH0
+        if (eth0_up)
+            ping_test(&eth0_bootp_data);
+        if ( ticks < cyg_current_time() ) break;
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+        if (eth1_up)
+            ping_test(&eth1_bootp_data);
+        if ( ticks < cyg_current_time() ) break;
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH0
+        if (eth0_up) {
+            station_ping( "10.0.3.1",  net3expect );
+            if ( ticks < cyg_current_time() ) break;
+            station_ping( "10.0.3.99", net3expect );
+        }
+        if ( ticks < cyg_current_time() ) break;
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+        if (eth1_up) {
+            station_ping( "10.0.4.1",  net4expect );
+            if ( ticks < cyg_current_time() ) break;
+            station_ping( "10.0.4.99", net4expect );
+        }
+        if ( ticks < cyg_current_time() ) break;
+#endif
+        station_ping( "10.0.5.1", FAILURE_REQUIRED ); // Not valid
+        if ( ticks < cyg_current_time() ) break;
+        station_ping( "10.0.5.99", FAILURE_REQUIRED ); // Not valid
+        if ( ticks < cyg_current_time() ) break;
+#ifdef PING_WWW_CYGNUS_COM
+        station_ping( "205.180.83.41", NOTHING_REQUIRED ); // www.cygnus.com
+        if ( ticks < cyg_current_time() ) break;
+#endif
+    };
+
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( 0 ); // check for N pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+void
+cyg_start(void)
+{
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+}
+
+// EOF routeping.inl
diff --git a/packages/net/autotest/v2_0/tests/slowping.c b/packages/net/autotest/v2_0/tests/slowping.c
new file mode 100644 (file)
index 0000000..3463142
--- /dev/null
@@ -0,0 +1,201 @@
+//==========================================================================
+//
+//      autotest/current/tests/slowping.c
+//
+//      Simple pinging test, the server pings me and little else.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#include "autohost.inl"
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_ping_tests(struct bootp *bp, int N, int testtime, int filesize)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d pings for %d seconds, %d bytes and up\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime, filesize );
+
+    // For 2nd and subsequent orders, we vary the ping data size:
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d %d", "SLOW_PING",
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime,
+                 filesize + 50 * i );
+        autohost_tell( bp, order );
+    }
+}
+
+#define TESTTIME (5 * 60) // Seconds
+
+#define NUM_SESSIONS 10 // why not?
+
+void
+net_test(cyg_addrword_t param)
+{
+    int i;
+    int numtests;
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start PING server test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    TNR_INIT();
+    
+    numtests = NUM_SESSIONS; // The number of pingers started OK
+    i = numtests;
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        // 2 small tests by default and a couple of larger ones
+        do_ping_tests(&eth0_bootp_data, 2, TESTTIME, 64);
+        do_ping_tests(&eth0_bootp_data, 2, TESTTIME, 1000);
+        do_ping_tests(&eth0_bootp_data, 2, TESTTIME, 10000);
+        i -= 6;
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up && i > 0) {
+        // rest of the tests depending...
+        do_ping_tests(&eth1_bootp_data, 1, TESTTIME, 64);
+        i--;
+        if ( i > 0 ) {
+            do_ping_tests(&eth1_bootp_data, 1, TESTTIME, 4000);
+            i--;
+        }
+        if ( i > 0 ) {
+            do_ping_tests(&eth1_bootp_data, i, TESTTIME, 1200);
+            i = 0;
+        }
+    }
+#endif
+    numtests -= i; // Adjust to how many we *actually* requested
+
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the stuff start up first
+    TNR_ON();
+    cyg_thread_delay(TESTTIME*100); // FIXME - assume cS clock.
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( numtests ); // check for N pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+void
+cyg_start(void)
+{
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+}
+
+// EOF slowping.c
diff --git a/packages/net/autotest/v2_0/tests/slowpingmux.c b/packages/net/autotest/v2_0/tests/slowpingmux.c
new file mode 100644 (file)
index 0000000..080f08c
--- /dev/null
@@ -0,0 +1,391 @@
+//==========================================================================
+//
+//      autotest/current/tests/slowpingmux.c
+//
+//      Simple pinging test, the server pings me and I ping her.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#include "autohost.inl"
+
+
+#define NUM_PINGS 16
+#define MAX_PACKET 4096
+#define MIN_PACKET   64
+#define MAX_SEND   4000
+
+#define PACKET_ADD  ((MAX_SEND - MIN_PACKET)/NUM_PINGS)
+#define nPACKET_ADD  1 
+
+static unsigned char pkt1[MAX_PACKET], pkt2[MAX_PACKET];
+
+#define UNIQUEID 0x1234
+
+// Compute INET checksum
+int
+inet_cksum(u_short *addr, int len)
+{
+    register int nleft = len;
+    register u_short *w = addr;
+    register u_short answer;
+    register u_int sum = 0;
+    u_short odd_byte = 0;
+
+    /*
+     *  Our algorithm is simple, using a 32 bit accumulator (sum),
+     *  we add sequential 16 bit words to it, and at the end, fold
+     *  back all the carry bits from the top 16 bits into the lower
+     *  16 bits.
+     */
+    while( nleft > 1 )  {
+        sum += *w++;
+        nleft -= 2;
+    }
+
+    /* mop up an odd byte, if necessary */
+    if( nleft == 1 ) {
+        *(u_char *)(&odd_byte) = *(u_char *)w;
+        sum += odd_byte;
+    }
+
+    /*
+     * add back carry outs from top 16 bits to low 16 bits
+     */
+    sum = (sum >> 16) + (sum & 0x0000ffff); /* add hi 16 to low 16 */
+    sum += (sum >> 16);                     /* add carry */
+    answer = ~sum;                          /* truncate to 16 bits */
+    return (answer);
+}
+
+static int
+show_icmp(unsigned char *pkt, int len, 
+          struct sockaddr_in *from, struct sockaddr_in *to)
+{
+    cyg_tick_count_t *tp, tv;
+    struct ip *ip;
+    struct icmp *icmp;
+    tv = cyg_current_time();
+    ip = (struct ip *)pkt;
+    if ((len < sizeof(*ip)) || ip->ip_v != IPVERSION) {
+        diag_printf("%s: Short packet or not IP! - Len: %d, Version: %d\n", 
+                    inet_ntoa(from->sin_addr), len, ip->ip_v);
+        return 0;
+    }
+    icmp = (struct icmp *)(pkt + sizeof(*ip));
+    len -= (sizeof(*ip) + 8);
+    tp = (cyg_tick_count_t *)&icmp->icmp_data;
+    if (icmp->icmp_type != ICMP_ECHOREPLY) {
+        diag_printf("%s: Invalid ICMP - type: %d\n", 
+                    inet_ntoa(from->sin_addr), icmp->icmp_type);
+        return 0;
+    }
+    if (icmp->icmp_id != UNIQUEID) {
+        diag_printf("%s: ICMP received for wrong id - sent: %x, recvd: %x\n", 
+                    inet_ntoa(from->sin_addr), UNIQUEID, icmp->icmp_id);
+    }
+//    diag_printf("%d bytes from %s: ", len, inet_ntoa(from->sin_addr));
+//    diag_printf("icmp_seq=%d", icmp->icmp_seq);
+//    diag_printf(", time=%dms\n", (int)(tv - *tp)*10);
+    return (from->sin_addr.s_addr == to->sin_addr.s_addr);
+}
+
+static void
+ping_host(int s, struct sockaddr_in *host)
+{
+    struct icmp *icmp = (struct icmp *)pkt1;
+    int icmp_len = MIN_PACKET;
+    int seq, ok_recv, bogus_recv;
+    cyg_tick_count_t *tp;
+    long *dp;
+    struct sockaddr_in from;
+    int i, len, fromlen;
+    int maxlen = 0;
+
+    ok_recv = 0;
+    bogus_recv = 0;
+    TNR_OFF();
+    diag_printf("PING server %s\n", inet_ntoa(host->sin_addr));
+    for (seq = 0;  seq < NUM_PINGS;  seq++, icmp_len += PACKET_ADD ) {
+        TNR_ON();
+        cyg_thread_delay( 47 ); // Half a second...
+        // Build ICMP packet
+        icmp->icmp_type = ICMP_ECHO;
+        icmp->icmp_code = 0;
+        icmp->icmp_cksum = 0;
+        icmp->icmp_seq = seq;
+        icmp->icmp_id = 0x1234;
+        // Set up ping data
+        tp = (cyg_tick_count_t *)&icmp->icmp_data;
+        *tp++ = cyg_current_time();
+        dp = (long *)tp;
+        for (i = sizeof(*tp);  i < icmp_len;  i += sizeof(*dp)) {
+            *dp++ = i;
+        }
+        // Add checksum
+        icmp->icmp_cksum = inet_cksum( (u_short *)icmp, icmp_len+8);
+        // Send it off
+        if (sendto(s, icmp, icmp_len+8, 0, (struct sockaddr *)host, sizeof(*host)) < 0) {
+            TNR_OFF();
+            perror("sendto");
+            continue;
+        }
+        // Wait for a response
+        fromlen = sizeof(from);
+        len = recvfrom(s, pkt2, sizeof(pkt2), 0, (struct sockaddr *)&from, &fromlen);
+        TNR_OFF();
+        if (len < 0) {
+//            perror("recvfrom");
+            icmp_len = MIN_PACKET - PACKET_ADD; // just in case - long routes
+        } else {
+            if (show_icmp(pkt2, len, &from, host)) {
+                ok_recv++;
+                if ( len > maxlen )
+                    maxlen = len;
+            } else {
+                bogus_recv++;
+            }
+        }
+    }
+    TNR_OFF();
+    diag_printf("Sent %d packets, received %d OK, %d bad max len %d\n",
+                NUM_PINGS, ok_recv, bogus_recv, maxlen);
+}
+
+static void
+ping_test(struct bootp *bp)
+{
+    struct protoent *p;
+    struct timeval tv;
+    struct sockaddr_in host;
+    int s;
+
+    if ((p = getprotobyname("icmp")) == (struct protoent *)0) {
+        pexit("getprotobyname");
+        return;
+    }
+    s = socket(AF_INET, SOCK_RAW, p->p_proto);
+    if (s < 0) {
+        pexit("socket");
+        return;
+    }
+    tv.tv_sec = 1;
+    tv.tv_usec = 0;
+    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+    // Set up host address
+    host.sin_family = AF_INET;
+    host.sin_len = sizeof(host);
+    host.sin_addr = bp->bp_siaddr;
+    host.sin_port = 0;
+    ping_host(s, &host);
+    // Now try a bogus host
+    host.sin_addr.s_addr = htonl(ntohl(host.sin_addr.s_addr) + 32);
+    ping_host(s, &host);
+    close(s);
+}
+
+// ------------------------------------------------------------------------
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_ping_tests(struct bootp *bp, int N, int testtime, int filesize)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d pings for %d seconds, %d bytes and up\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime, filesize );
+
+    // For 2nd and subsequent orders, we vary the ping data size:
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d %d", "SLOW_PING",
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime,
+                 filesize + 100 * i );
+        autohost_tell( bp, order );
+    }
+}
+
+#define TESTTIME (5 * 60) // Seconds
+
+#define NUM_SESSIONS 10 // why not?
+
+void
+net_test(cyg_addrword_t param)
+{
+    int i;
+    int numtests;
+    cyg_tick_count_t ticks;
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start PING server test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    TNR_INIT();
+    
+    numtests = NUM_SESSIONS; // The number of pingers started OK
+    i = numtests;
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        // 2 small tests by default and a couple of larger ones
+        do_ping_tests(&eth0_bootp_data, 1, TESTTIME, 64);
+        do_ping_tests(&eth0_bootp_data, 2, TESTTIME, 1000);
+        do_ping_tests(&eth0_bootp_data, 2, TESTTIME, 10000);
+        i -= 5;
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up && i > 0) {
+        // rest of the tests depending...
+        do_ping_tests(&eth1_bootp_data, 2, TESTTIME, 64);
+        i -= 2;
+        do_ping_tests(&eth1_bootp_data, 1, TESTTIME, 4000);
+        i -= 1;
+        do_ping_tests(&eth1_bootp_data, i, TESTTIME, 1200);
+        i = 0; // Since we just used up the rest
+    }
+#endif
+    numtests -= i; // Adjust to how many we *actually* requested
+
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the stuff start up first
+    TNR_ON();
+
+    ticks = cyg_current_time() + TESTTIME * 100; // FIXME - assume cS clock.
+    while (1) {
+        if ( ticks < cyg_current_time() ) break;
+#ifdef CYGHWR_NET_DRIVER_ETH0
+        if (eth0_up) {
+            ping_test(&eth0_bootp_data);
+        }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+        if ( ticks < cyg_current_time() ) break;
+        if (eth1_up) {
+            ping_test(&eth1_bootp_data);
+        }
+#endif
+    };
+
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( numtests ); // check for N pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+void
+cyg_start(void)
+{
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+}
+
+// EOF slowpingmux.c
diff --git a/packages/net/autotest/v2_0/tests/snmpmulti.c b/packages/net/autotest/v2_0/tests/snmpmulti.c
new file mode 100644 (file)
index 0000000..300eddb
--- /dev/null
@@ -0,0 +1,203 @@
+//==========================================================================
+//
+//      autotest/current/tests/snmpmulti.c
+//
+//      Simple pinging test, the server pings me and little else.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGPKG_SNMPAGENT // Do we support SNMP at all?
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#include "autohost.inl"
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_snmp_tests(struct bootp *bp, int N, int testtime)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d snmpwalks for %d seconds\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime );
+
+#ifdef XFAIL
+    // reduce the time to run so that we get a result
+    testtime *= 3;
+    testtime /= 4;
+#endif
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d", "SNMP_WALK",
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime );
+        autohost_tell( bp, order );
+    }
+}
+
+#define TESTTIME (5 * 60) // Seconds
+
+#define NUM_SESSIONS 10 // why not?
+
+void
+net_test(cyg_addrword_t param)
+{
+    extern void cyg_net_snmp_init(void);
+
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start multiple SNMP server test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    cyg_net_snmp_init();
+
+    TNR_INIT();
+    
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        do_snmp_tests(&eth0_bootp_data, 3, TESTTIME);
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        do_snmp_tests(&eth1_bootp_data, 3, TESTTIME);
+    }
+#endif
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the stuff start up first
+    TNR_ON();
+    cyg_thread_delay(TESTTIME*100); // FIXME - assume cS clock.
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( 3 * (0
+#ifdef CYGHWR_NET_DRIVER_ETH0
+                  + eth0_up
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+                  + eth1_up
+#endif
+        ) ); // check for N pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+#endif // CYGPKG_SNMPAGENT - Do we support SNMP at all?
+
+void
+cyg_start(void)
+{
+#ifdef CYGPKG_SNMPAGENT // Do we support SNMP at all?
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+#else
+    CYG_TEST_NA( "No SNMP agent in this configuration" );
+#endif // CYGPKG_SNMPAGENT - Do we support SNMP at all?
+}
+
+// EOF snmpmulti.c
diff --git a/packages/net/autotest/v2_0/tests/snmppings.c b/packages/net/autotest/v2_0/tests/snmppings.c
new file mode 100644 (file)
index 0000000..5154180
--- /dev/null
@@ -0,0 +1,251 @@
+//==========================================================================
+//
+//      autotest/current/tests/snmppings.c
+//
+//      Simple pinging test, the server pings me and little else.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGPKG_SNMPAGENT // Do we support SNMP at all?
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#include "autohost.inl"
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_ping_tests(struct bootp *bp, int N, int testtime, int filesize)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d pings for %d seconds, %d bytes and up\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime, filesize );
+
+    // For 2nd and subsequent orders, we vary the ping data size:
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d %d", "SLOW_PING",
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime,
+                 filesize + 50 * i );
+        autohost_tell( bp, order );
+    }
+}
+
+static void
+do_snmp_tests(struct bootp *bp, int N, int testtime)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d snmpwalks for %d seconds\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime );
+
+#ifdef XFAIL
+    // reduce the time to run so that we get a result
+    testtime *= 3;
+    testtime /= 4;
+#endif
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d", "SNMP_WALK",
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime );
+        autohost_tell( bp, order );
+    }
+}
+
+static void
+do_flood_tests(struct bootp *bp, int testtime, int on, int off)
+{
+    char order[256];
+    diag_printf( "INFO: telling %s to run 1 flood ping for %d seconds, %d/%d flood/sleep\n",
+          inet_ntoa(bp->bp_siaddr), testtime, on, off );
+
+    sprintf( order, "%s %s %d %d %d %d", "FLOOD_PING",
+             inet_ntoa(bp->bp_yiaddr),
+             testtime,
+             56, // constant size
+             on, off );
+    autohost_tell( bp, order );
+}
+
+
+#define TESTTIME (5 * 60) // Seconds
+
+#define NUM_SESSIONS 10 // why not?
+
+void
+net_test(cyg_addrword_t param)
+{
+    extern void cyg_net_snmp_init(void);
+
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start multiple SNMP server test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    cyg_net_snmp_init();
+
+    TNR_INIT();
+    
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        // Two SNMP walk tests
+        do_snmp_tests(&eth0_bootp_data, 2, TESTTIME);
+        // ...and flood ping for one second in 10
+        do_flood_tests(&eth0_bootp_data, TESTTIME, 1, 9 );
+        // ...and ping a couple of times too, 56 bytes and 2000 bytes.
+        do_ping_tests(&eth0_bootp_data, 1, TESTTIME, 56 );
+        do_ping_tests(&eth0_bootp_data, 1, TESTTIME, 2000 );
+        // which makes 5 tests in all.
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        // Two SNMP walk tests
+        do_snmp_tests(&eth1_bootp_data, 2, TESTTIME);
+        // ...and flood ping for two seconds in 13
+        do_flood_tests(&eth1_bootp_data, TESTTIME, 2, 11 );
+        // ...and ping a couple of times too, 500 bytes and 1600 bytes.
+        do_ping_tests(&eth1_bootp_data, 1, TESTTIME, 500 );
+        do_ping_tests(&eth1_bootp_data, 1, TESTTIME, 1600 );
+        // which makes 5 tests in all.
+    }
+#endif
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the stuff start up first
+    TNR_ON();
+    cyg_thread_delay(TESTTIME*100); // FIXME - assume cS clock.
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( 5 * (0
+#ifdef CYGHWR_NET_DRIVER_ETH0
+                  + eth0_up
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+                  + eth1_up
+#endif
+        ) ); // check for N pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+#endif // CYGPKG_SNMPAGENT - Do we support SNMP at all?
+
+void
+cyg_start(void)
+{
+#ifdef CYGPKG_SNMPAGENT // Do we support SNMP at all?
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+#else
+    CYG_TEST_NA( "No SNMP agent in this configuration" );
+#endif // CYGPKG_SNMPAGENT - Do we support SNMP at all?
+}
+
+// EOF snmppings.c
diff --git a/packages/net/autotest/v2_0/tests/snmpwalk.c b/packages/net/autotest/v2_0/tests/snmpwalk.c
new file mode 100644 (file)
index 0000000..0ce5ec2
--- /dev/null
@@ -0,0 +1,203 @@
+//==========================================================================
+//
+//      autotest/current/tests/snmpwalk.c
+//
+//      Simple pinging test, the server pings me and little else.
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-23
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#ifdef CYGPKG_SNMPAGENT // Do we support SNMP at all?
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+
+#include "autohost.inl"
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_snmp_tests(struct bootp *bp, int N, int testtime)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d snmpwalks for %d seconds\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime );
+
+#ifdef XFAIL
+    // reduce the time to run so that we get a result
+    testtime *= 3;
+    testtime /= 4;
+#endif
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d", "SNMP_WALK",
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime );
+        autohost_tell( bp, order );
+    }
+}
+
+#define TESTTIME (5 * 60) // Seconds
+
+#define NUM_SESSIONS 10 // why not?
+
+void
+net_test(cyg_addrword_t param)
+{
+    extern void cyg_net_snmp_init(void);
+
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start simple SNMP server test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    cyg_net_snmp_init();
+
+    TNR_INIT();
+    
+    // Now command the host to do ping to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        do_snmp_tests(&eth0_bootp_data, 1, TESTTIME);
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up) {
+        do_snmp_tests(&eth1_bootp_data, 1, TESTTIME);
+    }
+#endif
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the stuff start up first
+    TNR_ON();
+    cyg_thread_delay(TESTTIME*100); // FIXME - assume cS clock.
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    autohost_end( 0
+#ifdef CYGHWR_NET_DRIVER_ETH0
+                  + eth0_up
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+                  + eth1_up
+#endif
+        ); // check for 2 pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+#endif // CYGPKG_SNMPAGENT - Do we support SNMP at all?
+
+void
+cyg_start(void)
+{
+#ifdef CYGPKG_SNMPAGENT // Do we support SNMP at all?
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+#else
+    CYG_TEST_NA( "No SNMP agent in this configuration" );
+#endif // CYGPKG_SNMPAGENT - Do we support SNMP at all?
+}
+
+// EOF snmpwalk.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv.inl b/packages/net/autotest/v2_0/tests/tftp_serv.inl
new file mode 100644 (file)
index 0000000..d1e873d
--- /dev/null
@@ -0,0 +1,229 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv.inl
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#ifdef CYGBLD_DEVS_ETH_DEVICE_H    // Get the device config if it exists
+#include CYGBLD_DEVS_ETH_DEVICE_H  // May provide CYGTST_DEVS_ETH_TEST_NET_REALTIME
+#endif
+
+#ifdef CYGPKG_NET_TESTS_USE_RT_TEST_HARNESS // do we use the rt test?
+# ifdef CYGTST_DEVS_ETH_TEST_NET_REALTIME // Get the test ancilla if it exists
+#  include CYGTST_DEVS_ETH_TEST_NET_REALTIME
+# endif
+#endif
+
+
+// Fill in the blanks if necessary
+#ifndef TNR_OFF
+# define TNR_OFF()
+#endif
+#ifndef TNR_ON
+# define TNR_ON()
+#endif
+#ifndef TNR_INIT
+# define TNR_INIT()
+#endif
+#ifndef TNR_PRINT_ACTIVITY
+# define TNR_PRINT_ACTIVITY()
+#endif
+
+// ------------------------------------------------------------------------
+
+#include <errno.h>
+#include <network.h>
+#include <tftp_support.h>
+
+#include "autohost.inl"
+
+#define STACK_SIZE (CYGNUM_HAL_STACK_SIZE_TYPICAL + 0x10000)
+static char stack[STACK_SIZE];
+static cyg_thread thread_data;
+static cyg_handle_t thread_handle;
+
+static void
+do_tftp_tests(struct bootp *bp, int N, int testtime, int filesize)
+{
+    int i;
+    char order[256];
+    diag_printf( "INFO: telling %s to run %d tests for %d seconds, %d+/-%d bytes\n",
+          inet_ntoa(bp->bp_siaddr), N, testtime, filesize, N-1 );
+
+    // For 2nd and subsequent orders, we vary the filesize, thus testing
+    // together: 0 and 1 bytes; 512 and 513 bytes; 1Mb and 1Mb-1; in the
+    // standard invocations of this test.  Don't go over 1Mb.
+    for ( i = 0; i < N; i++ ) {
+        sprintf( order, "%s %s %d %d", OPERATION,
+                 inet_ntoa(bp->bp_yiaddr),
+                 testtime,
+                 filesize + ((filesize < (1024*1024)) ? i : -i ) );
+        autohost_tell( bp, order );
+    }
+}
+
+#define NUM_SERVERS 4
+static int servers[NUM_SERVERS] = { 0 };
+
+#define TESTTIME (5 * 60) // Seconds
+
+#define NUM_SESSIONS 3 // the dummy fileops system can only accept 3 new files
+
+void
+net_test(cyg_addrword_t param)
+{
+    int i;
+    int numtests;
+    CYG_TEST_INIT();
+    CYG_TEST_INFO("Start TFTP server test");
+    init_all_network_interfaces();
+
+    autohost_init();
+
+    TNR_INIT();
+    
+    // Create TFTP servers
+    for ( i = 0; i < NUM_SERVERS; i++ ) {
+        extern struct tftpd_fileops dummy_fileops;
+        int server_id = tftpd_start(0, &dummy_fileops);
+        if (server_id > 0) {
+            diag_printf("INFO: TFTP server %d created - id: %x\n", i, server_id);
+            servers[i] = server_id;
+        }
+        else {
+            diag_printf("INFO: TFTP server %d NOT created [%x]\n", i, server_id);
+            i--;
+            break;
+        }
+    }
+
+    numtests = i; // The number of servers started OK
+    if ( numtests > NUM_SESSIONS )
+        numtests = NUM_SESSIONS;
+    i = numtests;
+
+    if ( i < 1 ) {
+        CYG_TEST_FAIL_EXIT( "Not enough TFTP servers created" );
+    }
+
+    // Now command the host to do tftp to us...
+#ifdef CYGHWR_NET_DRIVER_ETH0
+    if (eth0_up) {
+        // 2 tests by default - if we have enough servers
+        if ( i > 1 ) {
+            do_tftp_tests(&eth0_bootp_data, 2, TESTTIME, FILESIZE);
+            i -= 2;
+        }
+        else {
+            do_tftp_tests(&eth0_bootp_data, 1, TESTTIME, FILESIZE);
+            i -= 1;
+        }
+    }
+#endif
+#ifdef CYGHWR_NET_DRIVER_ETH1
+    if (eth1_up && i > 0) {
+        // rest of the tests depending...
+        do_tftp_tests(&eth1_bootp_data, i, TESTTIME, FILESIZE);
+        i = 0;
+    }
+#endif
+    numtests -= i; // Adjust to how many we *actually* requested
+
+    // Let the server run for 5 minutes
+    cyg_thread_delay(2*100); // let the tftpds start up first
+    TNR_ON();
+    cyg_thread_delay(TESTTIME*100); // FIXME - assume cS clock.
+    // Additional delay 'cos host may be slower than us - and it has to
+    // complete a transfer anyway:
+    cyg_thread_delay(  30    *100); // FIXME - assume cS clock.
+    TNR_OFF();
+
+    for ( i = 0; i < NUM_SERVERS; i++ ) {
+        int server_id = servers[i];
+        if ( server_id ) {
+            int res = tftpd_stop(servers[i]);
+            diag_printf("INFO: TFTP server %d stopped - res: %d\n", i, res);
+            CYG_TEST_CHECK( res > 0, "TFTP server did not die" );
+        }
+    }
+
+    autohost_end( numtests ); // check for 3 pass messages from hosts
+
+    TNR_PRINT_ACTIVITY();
+    CYG_TEST_EXIT("Done");
+}
+
+void
+cyg_start(void)
+{
+    // Create a main thread, so we can run the scheduler and have time 'pass'
+    cyg_thread_create(10,                // Priority - just a number
+                      net_test,          // entry
+                      0,                 // entry parameter
+                      "Network test",    // Name
+                      &stack[0],         // Stack
+                      STACK_SIZE,        // Size
+                      &thread_handle,    // Handle
+                      &thread_data       // Thread data structure
+            );
+    cyg_thread_resume(thread_handle);  // Start it
+    cyg_scheduler_start();
+}
+
+// EOF tftp_serv.inl
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_g0.c b/packages/net/autotest/v2_0/tests/tftp_serv_g0.c
new file mode 100644 (file)
index 0000000..e21a9ad
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_g0.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_GET"
+#define FILESIZE  0
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_g0.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_g1M.c b/packages/net/autotest/v2_0/tests/tftp_serv_g1M.c
new file mode 100644 (file)
index 0000000..bf2c191
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_g1M.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_GET"
+#define FILESIZE  (1024 * 1024)
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_g1M.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_g512.c b/packages/net/autotest/v2_0/tests/tftp_serv_g512.c
new file mode 100644 (file)
index 0000000..dd342da
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_g512.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_GET"
+#define FILESIZE  512
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_g512.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_get.c b/packages/net/autotest/v2_0/tests/tftp_serv_get.c
new file mode 100644 (file)
index 0000000..606695b
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_get.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_GET"
+#define FILESIZE  (512 * 512 - 128)
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_get.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_p0.c b/packages/net/autotest/v2_0/tests/tftp_serv_p0.c
new file mode 100644 (file)
index 0000000..339b8f3
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_p0.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_PUT"
+#define FILESIZE  0
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_p0.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_p1M.c b/packages/net/autotest/v2_0/tests/tftp_serv_p1M.c
new file mode 100644 (file)
index 0000000..ee0b82d
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_p1M.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_PUT"
+#define FILESIZE  (1024 * 1024)
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_p1M.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_p512.c b/packages/net/autotest/v2_0/tests/tftp_serv_p512.c
new file mode 100644 (file)
index 0000000..420b00d
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_p512.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_PUT"
+#define FILESIZE  512
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_p512.c
diff --git a/packages/net/autotest/v2_0/tests/tftp_serv_put.c b/packages/net/autotest/v2_0/tests/tftp_serv_put.c
new file mode 100644 (file)
index 0000000..83d4032
--- /dev/null
@@ -0,0 +1,74 @@
+//==========================================================================
+//
+//      tests/auto/tftp_serv_put.c
+//
+//      Automated Multiple TFTP server GET test
+//
+//==========================================================================
+//####ECOSGPLCOPYRIGHTBEGIN####
+// -------------------------------------------
+// This file is part of eCos, the Embedded Configurable Operating System.
+// Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
+//
+// eCos 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.
+//
+// eCos 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 eCos; if not, write to the Free Software Foundation, Inc.,
+// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+//
+// As a special exception, if other files instantiate templates or use macros
+// or inline functions from this file, or you compile this file and link it
+// with other works to produce a work based on this file, this file does not
+// by itself cause the resulting work to be covered by the GNU General Public
+// License. However the source code for this file must still be made available
+// in accordance with section (3) of the GNU General Public License.
+//
+// This exception does not invalidate any other reasons why a work based on
+// this file might be covered by the GNU General Public License.
+//
+// -------------------------------------------
+//####ECOSGPLCOPYRIGHTEND####
+//####BSDCOPYRIGHTBEGIN####
+//
+// -------------------------------------------
+//
+// Portions of this software may have been derived from OpenBSD or other sources,
+// and are covered by the appropriate copyright disclaimers included herein.
+//
+// -------------------------------------------
+//
+//####BSDCOPYRIGHTEND####
+//==========================================================================
+//#####DESCRIPTIONBEGIN####
+//
+// Author(s):    hmt,gthomas
+// Contributors: hmt,gthomas
+// Date:         2000-10-10
+// Purpose:      
+// Description:  
+//              
+//
+//####DESCRIPTIONEND####
+//
+//==========================================================================
+// TFTP test code
+
+#include <pkgconf/system.h>
+
+#include <cyg/infra/testcase.h>         // testing infrastructure
+
+#include <pkgconf/net.h>
+
+#define OPERATION "TFTP_SERV_PUT"
+#define FILESIZE  (512 * 512 + 128)
+
+#include "tftp_serv.inl"
+
+// EOF tftp_serv_put.c
diff --git a/packages/net/ipsec/.cvsignore b/packages/net/ipsec/.cvsignore
new file mode 100644 (file)
index 0000000..ea2673d
--- /dev/null
@@ -0,0 +1 @@
+bsd_crypto
\ No newline at end of file