diff --git a/.gtkwaverc b/.gtkwaverc index ef06773..df0602d 100644 --- a/.gtkwaverc +++ b/.gtkwaverc @@ -34,6 +34,7 @@ # color additions # color_back 000000 +color_baseline ffffff color_grid 202070 color_high 00ff00 color_low 008000 diff --git a/INSTALL b/INSTALL index 9fb5be0..c4aa673 100644 --- a/INSTALL +++ b/INSTALL @@ -6,9 +6,35 @@ VCD project directory. It contains the prefs for a good configuration that most people find ergonomic. +[Note: for mingw builds with gtk+-1, you might need a fake gtk-config file like +the following..] + +<> +#!/bin/sh + +if [ "$1" == "--libs" ] + then + echo -L/home/bybell/libs -lgck -lgdk-1.3 -lgimp-1.2 -lgimpi -lgimpui-1.2 -lglib-1.3 -lgmodule-1.3 -lgnu-intl -lgobject-1.3 -lgthread-1.3 -lgtk-1.3 -liconv-1.3 -ljpeg -llibgplugin_a -llibgplugin_b -lpng -lpthread32 -ltiff-lzw -ltiff-nolzw -ltiff + fi + +if [ "$1" == "--cflags" ] + then + echo " -mms-bitfields -I/home/bybell/src/glib -I/home/bybell/src/gtk+/gtk -I/home/bybell/src/gtk+/gdk -I/home/bybell/src/gtk+ " + fi +<> + +[Note2: for mingw with gtk+-2, you don't need to do anything except have +pkg-config in your PATH.] + + Note that Ver Structural Verilog Compiler AET files are no longer supported. They have been superceded by LXT. Also note that the AMULET group will be taking over maintenance of the viewer effective immediately. --251201ajb bybell@linux-workshop.com +-251201ajb bybell@nc.rr.com + +AMULET has ceased development of the 2.x branch of the viewer. 1.3 +apparently is the only active version currently. + +-150405ajb bybell@nc.rr.com diff --git a/LICENSE.TXT b/LICENSE.TXT index 07c7fc8..31930c3 100644 --- a/LICENSE.TXT +++ b/LICENSE.TXT @@ -1,5 +1,5 @@ -GTKWave 1.3.34 Wave Viewer is Copyright (C) 1999-2003 Tony Bybell. -Portions of GTKWave are Copyright (C) 1999-2003 Udi Finkelstein. +GTKWave 1.3.63 Wave Viewer is Copyright (C) 1999-2005 Tony Bybell. +Portions of GTKWave are Copyright (C) 1999-2005 Udi Finkelstein. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free diff --git a/Makefile.in b/Makefile.in index 1355be1..aad7355 100644 --- a/Makefile.in +++ b/Makefile.in @@ -3,7 +3,7 @@ bindir = @bindir@ mandir = @mandir@ -all: config.log bin/gtkwave bin/mvl2vcd bin/tex2vcd bin/mvl2lxt bin/vcd2lxt bin/vcd2lxt2 bin/lxt2vcd +all: config.log bin/gtkwave bin/mvl2vcd bin/tex2vcd bin/mvl2lxt bin/vcd2lxt bin/vcd2lxt2 bin/lxt2vcd bin/vcd2vzt bin/vzt2vcd config.log: ./configure; @@ -13,6 +13,7 @@ install: cd bin;\ + install -d $(bindir);\ install -m 0755 gtkwave $(bindir)/gtkwave;\ install -m 0755 mvl2vcd $(bindir)/mvl2vcd;\ install -m 0755 mvl2lxt $(bindir)/mvl2lxt;\ @@ -20,44 +21,50 @@ install -m 0755 vcd2lxt $(bindir)/vcd2lxt;\ install -m 0755 vcd2lxt2 $(bindir)/vcd2lxt2;\ install -m 0755 lxt2vcd $(bindir)/lxt2vcd;\ + install -m 0755 vcd2vzt $(bindir)/vcd2vzt;\ + install -m 0755 vzt2vcd $(bindir)/vzt2vcd;\ cd ../man;\ + install -d $(mandir)/man1;\ install -m 0644 gtkwave.1 $(mandir)/man1/gtkwave.1;\ install -m 0644 lxt2vcd.1 $(mandir)/man1/lxt2vcd.1;\ install -m 0644 mvl2lxt.1 $(mandir)/man1/mvl2lxt.1;\ install -m 0644 mvl2vcd.1 $(mandir)/man1/mvl2vcd.1;\ install -m 0644 tex2vcd.1 $(mandir)/man1/tex2vcd.1;\ install -m 0644 vcd2lxt.1 $(mandir)/man1/vcd2lxt.1;\ - install -m 0644 vcd2lxt2.1 $(mandir)/man1/vcd2lxt2.1 + install -m 0644 vcd2lxt2.1 $(mandir)/man1/vcd2lxt2.1;\ + install -m 0644 vcd2vzt.1 $(mandir)/man1/vcd2vzt.1;\ + install -m 0644 vzt2vcd.1 $(mandir)/man1/vzt2vcd.1 dist: make clean - rm -f config.* Makefile src/Makefile src/helpers/Makefile + rm -f config.* Makefile src/Makefile src/helpers/Makefile src/libz/Makefile src/libbz2/Makefile bin/gtkwave: # Compiling GTKWave... cd src;make all bin/mvl2vcd: - # Compiling mvl2vcd/tex2vcd... cd src/helpers;make all bin/mvl2lxt: - # Compiling mvl2vcd/tex2vcd... cd src/helpers;make all bin/tex2vcd: - # Compiling tex2vcd/mvl2vcd... cd src/helpers;make all bin/vcd2lxt: - # Compiling tex2vcd/mvl2vcd... cd src/helpers;make all bin/vcd2lxt2: - # Compiling tex2vcd/mvl2vcd... cd src/helpers;make all bin/lxt2vcd: - # Compiling tex2vcd/mvl2vcd... cd src/helpers;make all +bin/vcd2vzt: + cd src/helpers;make all + +bin/vzt2vcd: + cd src/helpers;make all + + diff --git a/configure b/configure index ad8142d..f5b3234 100755 --- a/configure +++ b/configure @@ -1,19 +1,60 @@ #!/bin/sh + +if [ `uname|grep MINGW|wc -l` = "1" ] + then + echo "Building GTKWave for MinGW with gtk..." + # symlinks don't exist in mingw... + rm -f src/lxt2_read.? + cp src/helpers/lxt2_read.? src/ + rm -f src/vzt_read.? + cp src/helpers/vzt_read.? src/ + rm -f src/Makefile.in + + X="" + echo "Build GTKWave for GTK+-1.x or 2.x? Please enter '1' or '2'" + read X + + if [ "$X" = "" ] + then X="1" + fi + + if [ "$X" = "1" ] + then echo "Building for GTK+-1.x..." + cp src/Makefile_GTK1.in src/Makefile.in + fi + + if [ "$X" = "2" ] + then echo "Building for GTK+-2.x..." + cp src/Makefile_GTK2.in src/Makefile.in + fi + + cat Makefile.in | sed 's#log bin/gtkwave.*#log bin/gtkwave#' >Makefile.tmp + cat src/Makefile.in | sed 's#CFLAGS \= #CFLAGS \= \-mms\-bitfields #' | sed 's#\-lpthread##' >src/Makefile.tmp + mv Makefile.tmp Makefile.in + mv src/Makefile.tmp src/Makefile.in + ./configure2 "$@" + ./configure3 + exit + fi while [ 1 ] do +# in case of automatic build, default to gtk+-1.x... + X="" -while [ -z "$X" ] - do - echo "Build GTKWave for GTK+-1.x or 2.x? Please enter '1' or '2'" - read X - done +echo "Build GTKWave for GTK+-1.x or 2.x? Please enter '1' or '2'" +read X + +if [ "$X" = "" ] + then X="1" + fi if [ "$X" = "1" ] then echo "Building for GTK+-1.x..." ln -fs Makefile_GTK1.in src/Makefile.in ./configure2 "$@" + ./configure3 exit fi @@ -21,6 +62,7 @@ then echo "Building for GTK+-2.x..." ln -fs Makefile_GTK2.in src/Makefile.in ./configure2 "$@" + ./configure3 exit fi diff --git a/configure.scan b/configure.scan new file mode 100644 index 0000000..fb14773 --- /dev/null +++ b/configure.scan @@ -0,0 +1,30 @@ +dnl Process this file with autoconf to produce a configure script. +AC_INIT(src/aet.c) + +dnl Checks for programs. +AC_PROG_CC +AC_PROG_RANLIB +AC_PROG_MAKE_SET + +dnl Checks for libraries. + +dnl Checks for header files. +AC_HEADER_STDC +AC_CHECK_HEADERS(fcntl.h malloc.h strings.h unistd.h) + +dnl Checks for typedefs, structures, and compiler characteristics. +AC_C_CONST +AC_TYPE_OFF_T +AC_TYPE_SIZE_T +AC_HEADER_TIME +AC_STRUCT_TM + +dnl Checks for library functions. +AC_FUNC_ALLOCA +AC_FUNC_MEMCMP +AC_FUNC_MMAP +AC_FUNC_SETVBUF_REVERSED +AC_FUNC_VPRINTF +AC_CHECK_FUNCS(strdup strerror strstr) + +AC_OUTPUT(src/helpers/Makefile src/libz/Makefile Makefile src/Makefile src/libbz2/Makefile) diff --git a/configure2 b/configure2 index 29e1fd6..1af0ad3 100755 --- a/configure2 +++ b/configure2 @@ -744,8 +744,38 @@ fi fi +# Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +echo $ac_n "checking for $ac_word""... $ac_c" 1>&6 +echo "configure:751: checking for $ac_word" >&5 +if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else + IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS=":" + ac_dummy="$PATH" + for ac_dir in $ac_dummy; do + test -z "$ac_dir" && ac_dir=. + if test -f $ac_dir/$ac_word; then + ac_cv_prog_RANLIB="ranlib" + break + fi + done + IFS="$ac_save_ifs" + test -z "$ac_cv_prog_RANLIB" && ac_cv_prog_RANLIB=":" +fi +fi +RANLIB="$ac_cv_prog_RANLIB" +if test -n "$RANLIB"; then + echo "$ac_t""$RANLIB" 1>&6 +else + echo "$ac_t""no" 1>&6 +fi + echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6 -echo "configure:749: checking whether ${MAKE-make} sets \${MAKE}" >&5 +echo "configure:779: checking whether ${MAKE-make} sets \${MAKE}" >&5 set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_prog_make_${ac_make}_set'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -772,52 +802,9 @@ fi -echo $ac_n "checking for main in -libs""... $ac_c" 1>&6 -echo "configure:777: checking for main in -libs" >&5 -ac_lib_var=`echo ibs'_'main | sed 'y%./+-%__p_%'` -if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - ac_save_LIBS="$LIBS" -LIBS="-libs $LIBS" -cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=yes" -else - echo "configure: failed program was:" >&5 - cat conftest.$ac_ext >&5 - rm -rf conftest* - eval "ac_cv_lib_$ac_lib_var=no" -fi -rm -f conftest* -LIBS="$ac_save_LIBS" - -fi -if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then - echo "$ac_t""yes" 1>&6 - ac_tr_lib=HAVE_LIB`echo ibs | sed -e 's/[^a-zA-Z0-9_]/_/g' \ - -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'` - cat >> confdefs.h <&6 -fi - echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6 -echo "configure:821: checking how to run the C preprocessor" >&5 +echo "configure:808: checking how to run the C preprocessor" >&5 # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= @@ -832,13 +819,13 @@ # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. cat > conftest.$ac_ext < Syntax Error EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:842: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:829: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then : @@ -849,13 +836,13 @@ rm -rf conftest* CPP="${CC-cc} -E -traditional-cpp" cat > conftest.$ac_ext < Syntax Error EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:859: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:846: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then : @@ -866,13 +853,13 @@ rm -rf conftest* CPP="${CC-cc} -nologo -E" cat > conftest.$ac_ext < Syntax Error EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:876: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:863: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then : @@ -897,12 +884,12 @@ echo "$ac_t""$CPP" 1>&6 echo $ac_n "checking for ANSI C header files""... $ac_c" 1>&6 -echo "configure:901: checking for ANSI C header files" >&5 +echo "configure:888: checking for ANSI C header files" >&5 if eval "test \"`echo '$''{'ac_cv_header_stdc'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < #include @@ -910,7 +897,7 @@ #include EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:914: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:901: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -927,7 +914,7 @@ if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat > conftest.$ac_ext < EOF @@ -945,7 +932,7 @@ if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat > conftest.$ac_ext < EOF @@ -966,7 +953,7 @@ : else cat > conftest.$ac_ext < #define ISLOWER(c) ('a' <= (c) && (c) <= 'z') @@ -977,7 +964,7 @@ exit (0); } EOF -if { (eval echo configure:981: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null +if { (eval echo configure:968: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null then : else @@ -1004,17 +991,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:1008: checking for $ac_hdr" >&5 +echo "configure:995: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:1018: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:1005: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -1042,12 +1029,12 @@ echo $ac_n "checking for working const""... $ac_c" 1>&6 -echo "configure:1046: checking for working const" >&5 +echo "configure:1033: checking for working const" >&5 if eval "test \"`echo '$''{'ac_cv_c_const'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext <&5; (eval $ac_compile) 2>&5; }; then +if { (eval echo configure:1087: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then rm -rf conftest* ac_cv_c_const=yes else @@ -1116,13 +1103,13 @@ fi -echo $ac_n "checking for size_t""... $ac_c" 1>&6 -echo "configure:1121: checking for size_t" >&5 -if eval "test \"`echo '$''{'ac_cv_type_size_t'+set}'`\" = set"; then - echo $ac_n "(cached) $ac_c" 1>&6 -else - cat > conftest.$ac_ext <&6 +echo "configure:1108: checking for off_t" >&5 +if eval "test \"`echo '$''{'ac_cv_type_off_t'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < #if STDC_HEADERS @@ -1131,6 +1118,39 @@ #endif EOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + egrep "(^|[^a-zA-Z_0-9])off_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then + rm -rf conftest* + ac_cv_type_off_t=yes +else + rm -rf conftest* + ac_cv_type_off_t=no +fi +rm -f conftest* + +fi +echo "$ac_t""$ac_cv_type_off_t" 1>&6 +if test $ac_cv_type_off_t = no; then + cat >> confdefs.h <<\EOF +#define off_t long +EOF + +fi + +echo $ac_n "checking for size_t""... $ac_c" 1>&6 +echo "configure:1141: checking for size_t" >&5 +if eval "test \"`echo '$''{'ac_cv_type_size_t'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < +#if STDC_HEADERS +#include +#include +#endif +EOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | egrep "(^|[^a-zA-Z_0-9])size_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then rm -rf conftest* ac_cv_type_size_t=yes @@ -1149,13 +1169,48 @@ fi +echo $ac_n "checking whether time.h and sys/time.h may both be included""... $ac_c" 1>&6 +echo "configure:1174: checking whether time.h and sys/time.h may both be included" >&5 +if eval "test \"`echo '$''{'ac_cv_header_time'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < +#include +#include +int main() { +struct tm *tp; +; return 0; } +EOF +if { (eval echo configure:1188: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then + rm -rf conftest* + ac_cv_header_time=yes +else + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -rf conftest* + ac_cv_header_time=no +fi +rm -f conftest* +fi + +echo "$ac_t""$ac_cv_header_time" 1>&6 +if test $ac_cv_header_time = yes; then + cat >> confdefs.h <<\EOF +#define TIME_WITH_SYS_TIME 1 +EOF + +fi + echo $ac_n "checking whether struct tm is in sys/time.h or time.h""... $ac_c" 1>&6 -echo "configure:1154: checking whether struct tm is in sys/time.h or time.h" >&5 +echo "configure:1209: checking whether struct tm is in sys/time.h or time.h" >&5 if eval "test \"`echo '$''{'ac_cv_struct_tm'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < #include @@ -1163,7 +1218,7 @@ struct tm *tp; tp->tm_sec; ; return 0; } EOF -if { (eval echo configure:1167: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then +if { (eval echo configure:1222: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then rm -rf conftest* ac_cv_struct_tm=time.h else @@ -1187,19 +1242,19 @@ # The Ultrix 4.2 mips builtin alloca declared by alloca.h only works # for constant arguments. Useless! echo $ac_n "checking for working alloca.h""... $ac_c" 1>&6 -echo "configure:1191: checking for working alloca.h" >&5 +echo "configure:1246: checking for working alloca.h" >&5 if eval "test \"`echo '$''{'ac_cv_header_alloca_h'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < int main() { char *p = alloca(2 * sizeof(int)); ; return 0; } EOF -if { (eval echo configure:1203: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:1258: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* ac_cv_header_alloca_h=yes else @@ -1220,12 +1275,12 @@ fi echo $ac_n "checking for alloca""... $ac_c" 1>&6 -echo "configure:1224: checking for alloca" >&5 +echo "configure:1279: checking for alloca" >&5 if eval "test \"`echo '$''{'ac_cv_func_alloca_works'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:1312: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* ac_cv_func_alloca_works=yes else @@ -1285,12 +1340,12 @@ echo $ac_n "checking whether alloca needs Cray hooks""... $ac_c" 1>&6 -echo "configure:1289: checking whether alloca needs Cray hooks" >&5 +echo "configure:1344: checking whether alloca needs Cray hooks" >&5 if eval "test \"`echo '$''{'ac_cv_os_cray'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext <&6 -echo "configure:1319: checking for $ac_func" >&5 +echo "configure:1374: checking for $ac_func" >&5 if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:1402: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_func_$ac_func=yes" else @@ -1370,7 +1425,7 @@ fi echo $ac_n "checking stack direction for C alloca""... $ac_c" 1>&6 -echo "configure:1374: checking stack direction for C alloca" >&5 +echo "configure:1429: checking stack direction for C alloca" >&5 if eval "test \"`echo '$''{'ac_cv_c_stack_direction'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else @@ -1378,7 +1433,7 @@ ac_cv_c_stack_direction=0 else cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null +if { (eval echo configure:1456: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null then ac_cv_c_stack_direction=1 else @@ -1419,7 +1474,7 @@ fi echo $ac_n "checking for 8-bit clean memcmp""... $ac_c" 1>&6 -echo "configure:1423: checking for 8-bit clean memcmp" >&5 +echo "configure:1478: checking for 8-bit clean memcmp" >&5 if eval "test \"`echo '$''{'ac_cv_func_memcmp_clean'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else @@ -1427,7 +1482,7 @@ ac_cv_func_memcmp_clean=no else cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null +if { (eval echo configure:1496: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null then ac_cv_func_memcmp_clean=yes else @@ -1454,15 +1509,55 @@ echo "$ac_t""$ac_cv_func_memcmp_clean" 1>&6 test $ac_cv_func_memcmp_clean = no && LIBOBJS="$LIBOBJS memcmp.${ac_objext}" -for ac_func in re_comp regcomp strstr +for ac_hdr in stdlib.h unistd.h sys/stat.h sys/types.h +do +ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` +echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 +echo "configure:1517: checking for $ac_hdr" >&5 +if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < +EOF +ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" +{ (eval echo configure:1527: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` +if test -z "$ac_err"; then + rm -rf conftest* + eval "ac_cv_header_$ac_safe=yes" +else + echo "$ac_err" >&5 + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -rf conftest* + eval "ac_cv_header_$ac_safe=no" +fi +rm -f conftest* +fi +if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then + echo "$ac_t""yes" 1>&6 + ac_tr_hdr=HAVE_`echo $ac_hdr | sed 'y%abcdefghijklmnopqrstuvwxyz./-%ABCDEFGHIJKLMNOPQRSTUVWXYZ___%'` + cat >> confdefs.h <&6 +fi +done + +for ac_func in getpagesize do echo $ac_n "checking for $ac_func""... $ac_c" 1>&6 -echo "configure:1461: checking for $ac_func" >&5 +echo "configure:1556: checking for $ac_func" >&5 if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:1584: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then + rm -rf conftest* + eval "ac_cv_func_$ac_func=yes" +else + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -rf conftest* + eval "ac_cv_func_$ac_func=no" +fi +rm -f conftest* +fi + +if eval "test \"`echo '$ac_cv_func_'$ac_func`\" = yes"; then + echo "$ac_t""yes" 1>&6 + ac_tr_func=HAVE_`echo $ac_func | tr 'abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` + cat >> confdefs.h <&6 +fi +done + +echo $ac_n "checking for working mmap""... $ac_c" 1>&6 +echo "configure:1609: checking for working mmap" >&5 +if eval "test \"`echo '$''{'ac_cv_func_mmap_fixed_mapped'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + if test "$cross_compiling" = yes; then + ac_cv_func_mmap_fixed_mapped=no +else + cat > conftest.$ac_ext < +#include +#include + +#if HAVE_SYS_TYPES_H +# include +#endif + +#if HAVE_STDLIB_H +# include +#endif + +#if HAVE_SYS_STAT_H +# include +#endif + +#if HAVE_UNISTD_H +# include +#endif + +/* This mess was copied from the GNU getpagesize.h. */ +#ifndef HAVE_GETPAGESIZE + +/* Assume that all systems that can run configure have sys/param.h. */ +# ifndef HAVE_SYS_PARAM_H +# define HAVE_SYS_PARAM_H 1 +# endif + +# ifdef _SC_PAGESIZE +# define getpagesize() sysconf(_SC_PAGESIZE) +# else /* no _SC_PAGESIZE */ +# ifdef HAVE_SYS_PARAM_H +# include +# ifdef EXEC_PAGESIZE +# define getpagesize() EXEC_PAGESIZE +# else /* no EXEC_PAGESIZE */ +# ifdef NBPG +# define getpagesize() NBPG * CLSIZE +# ifndef CLSIZE +# define CLSIZE 1 +# endif /* no CLSIZE */ +# else /* no NBPG */ +# ifdef NBPC +# define getpagesize() NBPC +# else /* no NBPC */ +# ifdef PAGESIZE +# define getpagesize() PAGESIZE +# endif /* PAGESIZE */ +# endif /* no NBPC */ +# endif /* no NBPG */ +# endif /* no EXEC_PAGESIZE */ +# else /* no HAVE_SYS_PARAM_H */ +# define getpagesize() 8192 /* punt totally */ +# endif /* no HAVE_SYS_PARAM_H */ +# endif /* no _SC_PAGESIZE */ + +#endif /* no HAVE_GETPAGESIZE */ + +#ifdef __cplusplus +extern "C" { void *malloc(unsigned); } +#else +char *malloc(); +#endif + +int +main() +{ + char *data, *data2, *data3; + int i, pagesize; + int fd; + + pagesize = getpagesize(); + + /* + * First, make a file with some known garbage in it. + */ + data = malloc(pagesize); + if (!data) + exit(1); + for (i = 0; i < pagesize; ++i) + *(data + i) = rand(); + umask(0); + fd = creat("conftestmmap", 0600); + if (fd < 0) + exit(1); + if (write(fd, data, pagesize) != pagesize) + exit(1); + close(fd); + + /* + * Next, try to mmap the file at a fixed address which + * already has something else allocated at it. If we can, + * also make sure that we see the same garbage. + */ + fd = open("conftestmmap", O_RDWR); + if (fd < 0) + exit(1); + data2 = malloc(2 * pagesize); + if (!data2) + exit(1); + data2 += (pagesize - ((int) data2 & (pagesize - 1))) & (pagesize - 1); + if (data2 != mmap(data2, pagesize, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED, fd, 0L)) + exit(1); + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data2 + i)) + exit(1); + + /* + * Finally, make sure that changes to the mapped area + * do not percolate back to the file as seen by read(). + * (This is a bug on some variants of i386 svr4.0.) + */ + for (i = 0; i < pagesize; ++i) + *(data2 + i) = *(data2 + i) + 1; + data3 = malloc(pagesize); + if (!data3) + exit(1); + if (read(fd, data3, pagesize) != pagesize) + exit(1); + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data3 + i)) + exit(1); + close(fd); + unlink("conftestmmap"); + exit(0); +} + +EOF +if { (eval echo configure:1770: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null +then + ac_cv_func_mmap_fixed_mapped=yes +else + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -fr conftest* + ac_cv_func_mmap_fixed_mapped=no +fi +rm -fr conftest* +fi + +fi + +echo "$ac_t""$ac_cv_func_mmap_fixed_mapped" 1>&6 +if test $ac_cv_func_mmap_fixed_mapped = yes; then + cat >> confdefs.h <<\EOF +#define HAVE_MMAP 1 +EOF + +fi + +echo $ac_n "checking whether setvbuf arguments are reversed""... $ac_c" 1>&6 +echo "configure:1793: checking whether setvbuf arguments are reversed" >&5 +if eval "test \"`echo '$''{'ac_cv_func_setvbuf_reversed'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + if test "$cross_compiling" = yes; then + { echo "configure: error: can not run test program while cross compiling" 1>&2; exit 1; } +else + cat > conftest.$ac_ext < +/* If setvbuf has the reversed format, exit 0. */ +main () { + /* This call has the arguments reversed. + A reversed system may check and see that the address of main + is not _IOLBF, _IONBF, or _IOFBF, and return nonzero. */ + if (setvbuf(stdout, _IOLBF, (char *) main, BUFSIZ) != 0) + exit(1); + putc('\r', stdout); + exit(0); /* Non-reversed systems segv here. */ +} +EOF +if { (eval echo configure:1815: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext} && (./conftest; exit) 2>/dev/null +then + ac_cv_func_setvbuf_reversed=yes +else + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -fr conftest* + ac_cv_func_setvbuf_reversed=no +fi +rm -fr conftest* +fi + +rm -f core core.* *.core +fi + +echo "$ac_t""$ac_cv_func_setvbuf_reversed" 1>&6 +if test $ac_cv_func_setvbuf_reversed = yes; then + cat >> confdefs.h <<\EOF +#define SETVBUF_REVERSED 1 +EOF + +fi + +echo $ac_n "checking for vprintf""... $ac_c" 1>&6 +echo "configure:1839: checking for vprintf" >&5 +if eval "test \"`echo '$''{'ac_cv_func_vprintf'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < +/* Override any gcc2 internal prototype to avoid an error. */ +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char vprintf(); + +int main() { + +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_vprintf) || defined (__stub___vprintf) +choke me +#else +vprintf(); +#endif + +; return 0; } +EOF +if { (eval echo configure:1867: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then + rm -rf conftest* + eval "ac_cv_func_vprintf=yes" +else + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -rf conftest* + eval "ac_cv_func_vprintf=no" +fi +rm -f conftest* +fi + +if eval "test \"`echo '$ac_cv_func_'vprintf`\" = yes"; then + echo "$ac_t""yes" 1>&6 + cat >> confdefs.h <<\EOF +#define HAVE_VPRINTF 1 +EOF + +else + echo "$ac_t""no" 1>&6 +fi + +if test "$ac_cv_func_vprintf" != yes; then +echo $ac_n "checking for _doprnt""... $ac_c" 1>&6 +echo "configure:1891: checking for _doprnt" >&5 +if eval "test \"`echo '$''{'ac_cv_func__doprnt'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < +/* Override any gcc2 internal prototype to avoid an error. */ +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char _doprnt(); + +int main() { + +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub__doprnt) || defined (__stub____doprnt) +choke me +#else +_doprnt(); +#endif + +; return 0; } +EOF +if { (eval echo configure:1919: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then + rm -rf conftest* + eval "ac_cv_func__doprnt=yes" +else + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -rf conftest* + eval "ac_cv_func__doprnt=no" +fi +rm -f conftest* +fi + +if eval "test \"`echo '$ac_cv_func_'_doprnt`\" = yes"; then + echo "$ac_t""yes" 1>&6 + cat >> confdefs.h <<\EOF +#define HAVE_DOPRNT 1 +EOF + +else + echo "$ac_t""no" 1>&6 +fi + +fi + +for ac_func in strdup strerror strstr +do +echo $ac_n "checking for $ac_func""... $ac_c" 1>&6 +echo "configure:1946: checking for $ac_func" >&5 +if eval "test \"`echo '$''{'ac_cv_func_$ac_func'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < +/* Override any gcc2 internal prototype to avoid an error. */ +/* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ +char $ac_func(); + +int main() { + +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined (__stub_$ac_func) || defined (__stub___$ac_func) +choke me +#else +$ac_func(); +#endif + +; return 0; } +EOF +if { (eval echo configure:1974: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_func_$ac_func=yes" else @@ -1622,7 +2107,7 @@ ac_given_srcdir=$srcdir -trap 'rm -fr `echo "Makefile src/Makefile src/helpers/Makefile" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15 +trap 'rm -fr `echo "src/helpers/Makefile src/libz/Makefile Makefile src/Makefile src/libbz2/Makefile" | sed "s/:[^ ]*//g"` conftest*; exit 1' 1 2 15 EOF cat >> $CONFIG_STATUS <> $CONFIG_STATUS <> $CONFIG_STATUS <<\EOF for ac_file in .. $CONFIG_FILES; do if test "x$ac_file" != x..; then diff --git a/configure3 b/configure3 new file mode 100755 index 0000000..0c0b687 --- /dev/null +++ b/configure3 @@ -0,0 +1,43 @@ +#!/bin/sh + +cd src + +if [ `uname` = "Linux" ] + then + echo "Linux detected, configuring makefiles for 64-bit fileio support..." + for BIGF in Makefile libz/Makefile libbz2/Makefile helpers/Makefile ; + do + cat $BIGF | sed 's/\(^CFLAGS =.*$\)/\1 $(BIGFILES)/' >$BIGF.tmp + mv $BIGF.tmp $BIGF + done + fi + +if [ `uname` = "AIX" ] + then + echo "AIX detected, configuring for > 256MB memory usage..." + cat Makefile | sed 's/\(^CFLAGS =.*$\)/\1 $(AIXFLAGS)/' >Makefile.tmp + mv Makefile.tmp Makefile + fi + +if [ `uname` = "FreeBSD" ] + then + echo "FreeBSD detected, configuring for thread usage (currently disabled)..." + cat Makefile | sed 's/^PTHLIB =.*$/PTHLIB = /' >Makefile.tmp + mv Makefile.tmp Makefile + cat helpers/Makefile | sed 's/-lpthread//' >helpers/Makefile.tmp + mv helpers/Makefile.tmp helpers/Makefile + fi + +# +# if you don't know what ae2 is, you shouldn't be using it, sorry... +# +for AETLIB in /afs/awd/projects/simarama/releases/latest/libae2rw.a /afs/awd/projects/simarama/releases/latest/libae2rw.so; +do +if [ -e $AETLIB ] + then + echo "AET2 library found at "$AETLIB", configuring for use..." + cat Makefile | sed 's/\(^CFLAGS =.*$\)/\1 -DAET2_IS_PRESENT/' | sed "s#AET2LIB =#AET2LIB = $AETLIB#" >Makefile.tmp + mv Makefile.tmp Makefile + exit + fi +done diff --git a/doc/LXT_Explained.html b/doc/LXT_Explained.html index d67e332..0376fff 100644 --- a/doc/LXT_Explained.html +++ b/doc/LXT_Explained.html @@ -921,7 +921,7 @@
-
31Dec02 bybell@linux-workshop.com
+

diff --git a/doc/wave.html b/doc/wave.html index f2e9575..18e5796 100644 --- a/doc/wave.html +++ b/doc/wave.html @@ -19,16 +19,10 @@ -

Future development -and maintenance of GTKWave is now continuing at the AMULET Group -. This has been a very fun and rewarding project, but due to purported -conflicts of interest at work and other reasons, the time to pass on the -torch has arrived. This is the last official release in the 1.3.x series -and will be the last release in which I am the maintainer. Thanks for all -the constructive feedback from everyone since the initial release in 1998. - With that being said, the information and source/binaries available on -this page exist solely for historical reasons.

+

+Future development and maintenance of the 1.3 branch is still ongoing at this website. The 2.0 branch at APT is currently not being +developed. The website there exists for historical reasons. +

@@ -40,15 +34,10 @@ -

GTKWave is a fully featured GTK+ -v1.2 based wave viewer for Unix and Win32 which reads LXT files as well as standard Verilog VCD/EVCD -files and allows their viewing. You can grab version 1.3.21 here .

- -

If you have difficulty in downloading the GTKWave tarball properly, get -it from here and rename the file -so it doesn't have the ".bin" extension.

+

GTKWave is a fully featured GTK+ based wave viewer for Unix and Win32 which reads LXT, LXT2, and VZT files as well as standard Verilog VCD/EVCD +files and allows their viewing. You can grab version 1.3.61 here .

The Win32 version is now available (and has been for quite some time) on color_back steel blue), but don't put them in quotation marks as spaces are handled properly:

  • color_back- background color
  • +
  • color_baseline- middle mouse button marker +color
  • color_grid- grid color (use Alt-G/Shift-Alt-G to show/hide grid)
  • color_trans- trace @@ -1183,6 +1174,12 @@ not work properly. This should not be an issue if atomic_vectors are enabled. Default for vcd_explicit_zero_subscripts is disabled.
  • + +
  • vcd_preserve_glitches- indicates that any repeat equal values +for a net spanning different time values in the vcd file are not to be compressed into a single value change but should +remain in order to allow glitches to be present for this case. +Default for vcd_preserve_glitches is disabled. +
  • vector_padding- indicates the number of pixels of extra whitespace that should be added to any strings for the purpose of calculating text in vectors. Permissible values are 0 to @@ -1271,7 +1268,7 @@

    -
    21nov03bybell@linux-workshop.com
    +
    20jun05bybell@nc.rr.com

    diff --git a/man/gtkwave.1 b/man/gtkwave.1 index 6114e1f..3108c21 100644 --- a/man/gtkwave.1 +++ b/man/gtkwave.1 @@ -1,31 +1,51 @@ -.TH "GTKWAVE" "1" "1.3.34" "Anthony Bybell" "Simulation Wave Viewer" +.TH "GTKWAVE" "1" "1.3.59" "Anthony Bybell" "Simulation Wave Viewer" .SH "NAME" .LP -gtkwave \- Visualization tool for VCD and LXT files +gtkwave \- Visualization tool for VCD, LXT, and VZT files .SH "SYNTAX" .LP gtkwave [\fIoption\fP]... [\fIDUMPFILE\fP] [\fISAVEFILE\fP] [\fIRCFILE\fP] .SH "DESCRIPTION" .LP -Visualization tool for VCD, LXT, and LXT2 files. VCD is an industry standard simulation dump format, LXT and LXT2 have been designed specifically for use with gtkwave. Native dumpers exist in Icarus Verilog for the LXT formats so conversion with \fIvcd2lxt\fP(1) or \fIvcd2lxt2\fP(1) is not necessary to take direct advantage of LXT with that simulator. +Visualization tool for VCD, LXT, LXT2, and VZT. VCD is an industry standard simulation dump format. LXT, LXT2, and VZT have been designed +specifically for use with gtkwave. Native dumpers exist in Icarus Verilog for the LXT formats so conversion with \fIvcd2lxt\fP(1) or +\fIvcd2lxt2\fP(1) is not necessary to take direct advantage of LXT with that simulator. AET2 files can also be processed provided +that libae2rw is available but this is only of interest to people who use IBM EDA toolsets. .SH "OPTIONS" .LP .TP + + +\fB\-n\fR,\fB\-\-nocli\fR <\fIdirectory name\fP> +Use file requester for dumpfile name +.TP \fB\-f\fR,\fB\-\-dump\fR <\fIfilename\fP> Specify dumpfile name. .TP \fB\-r\fR,\fB\-\-rcfile\fR <\fIfilename\fP> Specify override .gtkwaverc filename. .TP +\fB\-i\fR,\fB\-\-indirect\fR <\fIfilename\fP> +Specify indirect facs file name. The file contains a series of regular expressions used to limit what signals can be browsed. Signal names +which match any of the regular expressions will be viewable. Typically, indirect files are used to reduce memory requirements for extremely +large models containing millions of facilities or to strip out top-level hierarchy clutter from BugSpray models. +This feature is only available with the AET2 loader. +.TP \fB\-s\fR,\fB\-\-start\fR <\fItime\fP> -Specify start time for LXT2 block skip. +Specify start time for LXT2/VZT block skip. .TP \fB\-e\fR,\fB\-\-end\fR <\fItime\fP> -Specify end time for LXT2 block skip. +Specify end time for LXT2/VZT block skip. +.TP +\fB\-c\fR,\fB\-\-cpu\fR <\fInumcpus\fP> +Specify number of CPUs available for parallelizable ops (e.g., block prefetching on VZT reads). .TP \fB\-v\fR,\fB\-\-vcd\fR Use stdin as a VCD dumpfile. +.TP +\fB\-V\fR,\fB\-\-version\fR +Display version banner then exit. .TP \fB\-h\fR,\fB\-\-help\fR Display help then exit. @@ -44,10 +64,12 @@ Alternatively you can run it with a save file as: gtkwave dumpfile.vcd dumpfile.sav .LP -Command line options are not necessary for representing the dumpfile, savefile, and rcfile names. They are merely provided to allow specifying them out of order. +Command line options are not necessary for representing the dumpfile, savefile, and rcfile names. They are merely provided to allow specifying them +out of order. Note that on non-glibc systems, the long command line options will not be available and that the short ones will have to be used +instead. .SH "AUTHORS" .LP -Anthony Bybell +Anthony Bybell .SH "SEE ALSO" .LP -\fIlxt2vcd\fP(1) \fIvcd2lxt\fP(1) \fIvcd2lxt2\fP(1) +\fIlxt2vcd\fP(1) \fIvcd2lxt\fP(1) \fIvcd2lxt2\fP(1) \fIvzt2vcd\fP(1) \fIvcd2vzt\fP(1) diff --git a/man/lxt2vcd.1 b/man/lxt2vcd.1 index 9edac65..720f2bd 100644 --- a/man/lxt2vcd.1 +++ b/man/lxt2vcd.1 @@ -7,16 +7,21 @@ lxt2vcd <\fIfilename\fP> .SH "DESCRIPTION" .LP -Converts LXT2 files to VCD files on stdout. Note that "regular" LXT2 files will convert to VCD files with monotonically increasing time values. LXT2 files which are dumped with the "partial" option (to speed up access in wave viewers) will dump with monotonically increasing time values per 2k block of nets. This may be fixed in later versions of \fIlxt2vcd\fP. +Converts LXT2 files to VCD files on stdout. Note that "regular" LXT2 files will convert to VCD files with monotonically increasing time values. LXT2 +files which are dumped with the "partial" option (to speed up access in wave viewers) will dump with monotonically increasing time values per 2k block +of nets. This may be fixed in later versions of \fIlxt2vcd\fP. .SH "EXAMPLES" .LP To run this program the standard way type: .TP lxt2vcd filename.lxt The VCD conversion is emitted to stdout. +.SH "LIMITATIONS" +\fIlxt2vcd\fP does not re-create glitches as these are coalesced together into one value change during the writing of the LXT2 file. +.LP .SH "AUTHORS" .LP -Anthony Bybell +Anthony Bybell .SH "SEE ALSO" .LP \fIvcd2lxt2\fP(1) \fIvcd2lxt\fP(1) \fIgtkwave\fP(1) diff --git a/man/mvl2lxt.1 b/man/mvl2lxt.1 index a9deb08..1188c71 100644 --- a/man/mvl2lxt.1 +++ b/man/mvl2lxt.1 @@ -10,7 +10,7 @@ Converts AET files to LXT. This is experimental as it is not a complete implementation and is not intended for general use. .SH "AUTHORS" .LP -Anthony Bybell +Anthony Bybell .SH "SEE ALSO" .LP \fItex2vcd\fP(1) \fImvl2vcd\fP(1) \fIlxt2vcd\fP(1) \fIvcd2lxt2\fP(1) \fIvcd2lxt\fP(1) \fIgtkwave\fP(1) diff --git a/man/mvl2vcd.1 b/man/mvl2vcd.1 index 61f9888..0b2073b 100644 --- a/man/mvl2vcd.1 +++ b/man/mvl2vcd.1 @@ -10,7 +10,7 @@ Converts AET files to VCD on stdout. This is experimental as it is not a complete implementation and is not intended for general use. .SH "AUTHORS" .LP -Anthony Bybell +Anthony Bybell .SH "SEE ALSO" .LP \fItex2vcd\fP(1) \fImvl2lxt\fP(1) \fIlxt2vcd\fP(1) \fIvcd2lxt2\fP(1) \fIvcd2lxt\fP(1) \fIgtkwave\fP(1) diff --git a/man/tex2vcd.1 b/man/tex2vcd.1 index 30c2731..71de2c4 100644 --- a/man/tex2vcd.1 +++ b/man/tex2vcd.1 @@ -10,7 +10,7 @@ Converts AET files to VCD on stdout. This is experimental as it is not a complete implementation and is not intended for general use. .SH "AUTHORS" .LP -Anthony Bybell +Anthony Bybell .SH "SEE ALSO" .LP \fImvl2vcd\fP(1) \fImvl2lxt\fP(1) \fIlxt2vcd\fP(1) \fIvcd2lxt2\fP(1) \fIvcd2lxt\fP(1) \fIgtkwave\fP(1) diff --git a/man/vcd2lxt.1 b/man/vcd2lxt.1 index de16aa3..1ad60ab 100644 --- a/man/vcd2lxt.1 +++ b/man/vcd2lxt.1 @@ -36,7 +36,7 @@ Uses linear mode for even smaller files. .SH "AUTHORS" .LP -Anthony Bybell +Anthony Bybell .SH "SEE ALSO" .LP \fIlxt2vcd\fP(1) \fIvcd2lxt2\fP(1) \fIgtkwave\fP(1) diff --git a/man/vcd2lxt2.1 b/man/vcd2lxt2.1 index a73159a..c67c598 100644 --- a/man/vcd2lxt2.1 +++ b/man/vcd2lxt2.1 @@ -1,25 +1,59 @@ -.TH "VCD2LXT2" "1" "1.3.34" "Anthony Bybell" "Filetype Conversion" +.TH "VCD2LXT2" "1" "1.3.42" "Anthony Bybell" "Filetype Conversion" .SH "NAME" .LP -vcd2lxt2 \- Coverts VCD files to regular LXT2 files +vcd2lxt2 \- Converts VCD files to LXT2 files .SH "SYNTAX" .LP -vcd2lxt2 <\fIfilename.vcd\fP> <\fIfilename.lxt\fP> +vcd2lxt2 [\fIoption\fP]... [\fIVCDFILE\fP] [\fILXTFILE\fP] .SH "DESCRIPTION" .LP -Converts VCD files to regular LXT2 files. Note that specifying "\-" as an input filename implies stdin. +Converts VCD files to LXT2 files. +.SH "OPTIONS" +.LP +.TP +\fB\-v,--vcdname\fR <\fIfilename\fP> +Specify VCD input filename. +.TP +\fB\-l,--lxtname\fR <\fIfilename\fP> +Specify LXT2 output filename. +.TP +\fB\-d,--depth\fR <\fIvalue\fP> +Specify 0..9 gzip compression depth, default is 4. +.TP +\fB\-m,--maxgranule\fR <\fIvalue\fP> +Specify number of granules per section, default is 8. One granule is equal to 32 timsteps. +.TP +\fB\-b,--break\fR <\fIvalue\fP> +Specify break size (default = 0 = off). When the break size is exceeded, the LXT2 dumper will +dump all state information at the next convenient granule plus dictionary boundary. +.TP +\fB\-p,--partialmode\fR <\fImode\fP> +Specify partial zip mode 0 = monolithic, 1 = separation. Using a value of 1 expands LXT2 filesize but provides +fast access for very large traces. Note that the default mode is neither monolithic nor separation: partial zip is disabled. +.TP +\fB\-c,--checkpoint\fR <\fImode\fP> +Specify checkpoint mode. 0 is on which is default, and 1 is off. This is disabled when the +break size is active. +.TP +\fB\-h,--help\fR +Show help screen. +.TP + .SH "EXAMPLES" .LP -To run this program the standard way type: -.LP -vcd2lxt2 filename.vcd filename.lxt -.LP -Alternatively, use stdin for the input file: -.LP -vcd2lxt2 \- filename.lxt +Note that you should specify dumpfile.vcd directly or use "\-" for stdin. +.TP +vcd2lxt dumpfile.vcd dumpfile.lxt --depth 9 --break 1073741824 +This sets the compression level to 9 and sets the break size to 1GB. +.TP +vcd2lxt dumpfile.vcd dumpfile.lxt --depth 9 --maxgranule 256 +Allows more granules per section which allows for greater compression. +.SH "LIMITATIONS" +\fIvcd2lxt2\fP does not store glitches as these are coalesced together into one value change during the writing of the LXT2 file. +.LP .SH "AUTHORS" .LP -Anthony Bybell +Anthony Bybell .SH "SEE ALSO" .LP -\fIlxt2vcd\fP(1) \fIvcd2lxt\fP(1) \fIgtkwave\fP(1) +\fIlxt2vcd\fP(1) \fIvcd2lxt2\fP(1) \fIgtkwave\fP(1) diff --git a/man/vcd2vzt.1 b/man/vcd2vzt.1 new file mode 100644 index 0000000..b050769 --- /dev/null +++ b/man/vcd2vzt.1 @@ -0,0 +1,64 @@ +.TH "VCD2VZT" "1" "1.3.48" "Anthony Bybell" "Filetype Conversion" +.SH "NAME" +.LP +vcd2vzt \- Converts VCD files to VZT files +.SH "SYNTAX" +.LP +vcd2vzt [\fIoption\fP]... [\fIVCDFILE\fP] [\fIVZTFILE\fP] +.SH "DESCRIPTION" +.LP +Converts VCD files to VZT files. +.SH "OPTIONS" +.LP +.TP +\fB\-v,--vcdname\fR <\fIfilename\fP> +Specify VCD input filename. +.TP +\fB\-l,--vztname\fR <\fIfilename\fP> +Specify VZT output filename. +.TP +\fB\-d,--depth\fR <\fIvalue\fP> +Specify 0..9 gzip compression depth, default is 4. +.TP +\fB\-m,--maxgranule\fR <\fIvalue\fP> +Specify number of granules per section, default is 8. One granule is equal to 32 timesteps. +.TP +\fB\-b,--break\fR <\fIvalue\fP> +Specify break size (default = 0 = off). When the break size is exceeded, the VZT dumper will +dump all state information at the next convenient granule plus dictionary boundary. +.TP +\fB\-z,--ziptype\fR <\fIvalue\fP> +Specify zip type (default = 0 gzip, 1 = bzip2). This allows you to override the default compression +algorithm to use a more effective one at the expense of greater runtime. Note that bzip2 does not +decompress as fast as gzip so the viewer will be about two times slower when decompressing blocks. +.TP +\fB\-t,--twostate\fR +Forces MVL2 twostate mode (default is MVL4). When enabled, the trace will only store 0/1 values +for binary facilities. This is useful for functional simulation and will speed up dumping as well as make traces somewhat smaller. +.TP +\fB\-r, --rle\fR +Uses an bitwise RLE compression on the value table. Default is off. When enabled, this causes the trace data table to be stored using an +alternate representation which can improve compression in many cases. +.TP +\fB\-h,--help\fR +Show help screen. +.TP + +.SH "EXAMPLES" +.LP +Note that you should specify dumpfile.vcd directly or use "\-" for stdin. +.TP +vcd2vzt dumpfile.vcd dumpfile.lxt --depth 9 --break 1073741824 +This sets the compression level to 9 and sets the break size to 1GB. +.TP +vcd2vzt dumpfile.vcd dumpfile.lxt --depth 9 --maxgranule 512 +Allows more granules per section which allows for greater compression at the expense of memory usage. +.SH "LIMITATIONS" +\fIvcd2vzt\fP does not store glitches as these are coalesced together into one value change during the writing of the VZT file. +.LP +.SH "AUTHORS" +.LP +Anthony Bybell +.SH "SEE ALSO" +.LP +\fIvzt2vcd\fP(1) \fIlxt2vcd\fP(1) \fIvcd2lxt2\fP(1) \fIgtkwave\fP(1) diff --git a/man/vzt2vcd.1 b/man/vzt2vcd.1 new file mode 100644 index 0000000..f104584 --- /dev/null +++ b/man/vzt2vcd.1 @@ -0,0 +1,25 @@ +.TH "VZT2VCD" "1" "1.3.44" "Anthony Bybell" "Filetype Conversion" +.SH "NAME" +.LP +vzt2vcd \- Coverts VZT files to VCD +.SH "SYNTAX" +.LP +vzt2vcd <\fIfilename\fP> +.SH "DESCRIPTION" +.LP +Converts VZT files to VCD files on stdout. +.SH "EXAMPLES" +.LP +To run this program the standard way type: +.TP +vzt2vcd filename.vzt +The VCD conversion is emitted to stdout. +.SH "LIMITATIONS" +\fIvzt2vcd\fP does not re-create glitches as these are coalesced together into one value change during the writing of the VZT file. +.LP +.SH "AUTHORS" +.LP +Anthony Bybell +.SH "SEE ALSO" +.LP +\fIvcd2lxt2\fP(1) \fIvcd2lxt\fP(1) \fIlxt2vcd\fP(1) \fIgtkwave\fP(1) diff --git a/src/Makefile_GTK1.in b/src/Makefile_GTK1.in index 9c05f84..f5ee899 100644 --- a/src/Makefile_GTK1.in +++ b/src/Makefile_GTK1.in @@ -1,7 +1,11 @@ CC = @CC@ -CFLAGS = -O2 + AIXFLAGS = -bmaxdata:0x80000000 -D_WAVE_BE32 +BIGFILES = -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 +CFLAGS = -O2 -I./libz -I./libbz2 DEBUGS = -DDEBUG_FACILITIES -DDEBUG_PRINTF -DDEBUG_MALLOC -DSTRICT_VCD_ONLY -DDEBUG_MALLOC_LINES +AET2LIB = +PTHLIB = -lpthread SRCS = menu.c main.c status.c zoombuttons.c pagebuttons.c \ fetchbuttons.c shiftbuttons.c pixmaps.c \ @@ -12,7 +16,8 @@ markerbox.c print.c strace.c \ simplereq.c help.c vcd.c debug.c rc.c \ color.c hiersearch.c renderopt.c \ - rgb.c regex.c fonts.c lxt.c lx2.c lxt2_read.c + rgb.c regex.c fonts.c lxt.c lx2.c lxt2_read.c \ + ae2.c vzt_read.c vzt.c baseconvert.c OBJS = menu.o main.o status.o zoombuttons.o pagebuttons.o \ fetchbuttons.o shiftbuttons.o pixmaps.o \ @@ -23,16 +28,25 @@ markerbox.o print.o strace.o \ simplereq.o help.o vcd.o debug.o rc.o \ color.o hiersearch.o renderopt.o \ - rgb.o regex.o fonts.o lxt.o lx2.o lxt2_read.o + rgb.o regex.o fonts.o lxt.o lx2.o lxt2_read.o \ + ae2.o vzt_read.o vzt.o baseconvert.o all: gtkwave cp gtkwave ../bin -gtkwave:$(OBJS) - $(CC) $(CFLAGS) `gtk-config --libs` $(OBJS) -lz -lbz2 -o gtkwave +gtkwave:$(OBJS) libz/libz.a libbz2/libbz2.a + $(CC) $(CFLAGS) $(OBJS) `gtk-config --libs` $(AET2LIB) libz/libz.a libbz2/libbz2.a -o gtkwave $(PTHLIB) + +libz/libz.a: + cd libz ; make + +libbz2/libbz2.a: + cd libbz2 ; make .c.o: $(H_FILES) $(CC) $(CFLAGS) `gtk-config --cflags` -c -o $@ $< clean: rm -f core *.core *.o gtkwave ../bin/gtkwave + cd libz ; make clean + cd libbz2 ; make clean diff --git a/src/Makefile_GTK2.in b/src/Makefile_GTK2.in index 2161e89..37ff1f5 100644 --- a/src/Makefile_GTK2.in +++ b/src/Makefile_GTK2.in @@ -1,7 +1,10 @@ CC = @CC@ -CFLAGS = -O2 -DGTK_ENABLE_BROKEN -DWAVE_USE_GTK2 AIXFLAGS = -bmaxdata:0x80000000 -D_WAVE_BE32 +BIGFILES = -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 +CFLAGS = -O2 -DGTK_ENABLE_BROKEN -DWAVE_USE_GTK2 -I./libz -I./libbz2 DEBUGS = -DDEBUG_FACILITIES -DDEBUG_PRINTF -DDEBUG_MALLOC -DSTRICT_VCD_ONLY -DDEBUG_MALLOC_LINES +AET2LIB = +PTHLIB = -lpthread SRCS = menu.c main.c status.c zoombuttons.c pagebuttons.c \ fetchbuttons.c shiftbuttons.c pixmaps.c \ @@ -12,7 +15,8 @@ markerbox.c print.c strace.c \ simplereq.c help.c vcd.c debug.c rc.c \ color.c hiersearch.c renderopt.c \ - rgb.c regex.c fonts.c lxt.c lx2.c lxt2_read.c + rgb.c regex.c fonts.c lxt.c lx2.c lxt2_read.c \ + ae2.c vzt_read.c vzt.c baseconvert.c OBJS = menu.o main.o status.o zoombuttons.o pagebuttons.o \ fetchbuttons.o shiftbuttons.o pixmaps.o \ @@ -23,16 +27,26 @@ markerbox.o print.o strace.o \ simplereq.o help.o vcd.o debug.o rc.o \ color.o hiersearch.o renderopt.o \ - rgb.o regex.o fonts.o lxt.o lx2.o lxt2_read.o + rgb.o regex.o fonts.o lxt.o lx2.o lxt2_read.o \ + ae2.o vzt_read.o vzt.o baseconvert.o all: gtkwave cp gtkwave ../bin -gtkwave:$(OBJS) - $(CC) $(CFLAGS) `pkg-config gtk+-2.0 --libs` $(OBJS) -lz -lbz2 -o gtkwave +gtkwave:$(OBJS) libz/libz.a libbz2/libbz2.a + $(CC) $(CFLAGS) $(OBJS) `pkg-config gtk+-2.0 --libs` $(AET2LIB) libz/libz.a libbz2/libbz2.a -o gtkwave $(PTHLIB) + +libz/libz.a: + cd libz ; make + +libbz2/libbz2.a: + cd libbz2 ; make .c.o: $(H_FILES) $(CC) $(CFLAGS) `pkg-config gtk+-2.0 --cflags` -c -o $@ $< clean: rm -f core *.core *.o gtkwave ../bin/gtkwave + cd libz ; make clean + cd libbz2 ; make clean + diff --git a/src/ae2.c b/src/ae2.c new file mode 100644 index 0000000..c388d4d --- /dev/null +++ b/src/ae2.c @@ -0,0 +1,883 @@ +/* + * Copyright (c) Tony Bybell 2004. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + */ + +#include + +#ifndef _MSC_VER +#include +#endif + +#include +#include +#include +#include "ae2.h" +#include "aet.h" +#include "vcd.h" +#include "lxt.h" +#include "lxt2_read.h" +#include "fgetdynamic.h" +#include "debug.h" + +/* + * select appropriate entry points based on if aet2 + * support is available + */ +#ifndef AET2_IS_PRESENT + +static char *ae2_loader_fail_msg = "Sorry, AET2 support was not compiled into this executable, exiting.\n\n"; + +TimeType ae2_main(char *fname, char *skip_start, char *skip_end, char *indirect_fname) +{ +fprintf(stderr, ae2_loader_fail_msg); +exit(255); + +return(0); /* for vc++ */ +} + +void ae2_import_masked(void) +{ +fprintf(stderr, ae2_loader_fail_msg); +exit(255); +} + +#else + +/* + * globals + */ +static TimeType first_cycle, last_cycle, total_cycles; +static unsigned long num_sections = 0; +static struct lx2_entry *lx2_table = NULL; +static FILE *f = NULL; +static AE2_HANDLE ae2 = NULL; +static FACREF *fr = NULL; +static char **value = NULL; +static char *process_mask = NULL; +static char ae2_msg_suppress = 0; + +static struct regex_links *regex_head = NULL; +static int regex_matches = 0; + + +/* + * iter mask manipulation util functions + */ +int aet2_rd_get_fac_process_mask(unsigned int facidx) +{ +if(facidxpnt = regex; + rpnt->next = regex_head; + regex_head = rpnt; + + if(added < 31) + { + fprintf(stderr, AET2_RDLOAD"Added indirect regex '%s'\n", exp2); + } + else + if(added == 31) + { + fprintf(stderr, AET2_RDLOAD"Added indirect regex '%s', adding more quietly...\n", exp2); + } + added++; + } + } + + free_2(exp); + } + + fclose(ind_h); ind_h = NULL; + + regex_matches = 0; + if(regex_head) + { + struct regex_links *rpnt; + + for(i=0;ipnt, buf)) + { + /* fprintf(stderr, "Matched '%s'\n", buf); */ + aet2_rd_set_fac_process_mask(i); + regex_matches++; + break; + } + + rpnt=rpnt->next; + } + } + + rpnt = regex_head; + while(rpnt) + { + struct regex_links *rpnt2 = rpnt->next; + wave_regex_alloc_free(rpnt->pnt); + free_2(rpnt); + rpnt = rpnt2; + } + + regex_head=NULL; + } + + if(regex_matches) + { + fprintf(stderr, AET2_RDLOAD"Matched %d/%d facilities against indirect file.\n", regex_matches, numfacs); + } + else + { + fprintf(stderr, AET2_RDLOAD"Matched %d/%d facilities against indirect file, exiting.\n", regex_matches, numfacs); + exit(0); + } + } + } + +if(!regex_matches) + { + fr=calloc(numfacs, sizeof(FACREF)); + value = calloc(numfacs, sizeof(char *)); + lx2_table=(struct lx2_entry *)calloc(numfacs, sizeof(struct lx2_entry)); + } + else + { + fr=calloc(regex_matches, sizeof(FACREF)); + value = calloc(regex_matches, sizeof(char *)); + lx2_table=(struct lx2_entry *)calloc(regex_matches, sizeof(struct lx2_entry)); + } + +match_idx = 0; +for(i=0;i1) + { + sprintf(buf+len, "[%d:%d]", 0, fr[match_idx].length-1); + str=malloc_2(strlen(buf)+1); + if(!alt_hier_delimeter) + { + strcpy(str, buf); + } + else + { + strcpy_vcdalt(str, buf, alt_hier_delimeter); + } + s=symadd_name_exists(str,hash(str)); + prevsymroot = prevsym = NULL; + } + else + { + str=malloc_2(len+1); + if(!alt_hier_delimeter) + { + strcpy(str, buf); + } + else + { + strcpy_vcdalt(str, buf, alt_hier_delimeter); + } + s=symadd_name_exists(str,hash(str)); + prevsymroot = prevsym = NULL; + } + + if(!firstnode) + { + firstnode=curnode=s; + } + else + { + curnode->nextinaet=s; + curnode=s; + } + + n=(struct Node *)calloc_2(1,sizeof(struct Node)); + n->nname=s->name; + n->mvlfac = (struct fac *)(fr+match_idx); /* to keep from having to allocate duplicate mvlfac struct */ + /* use the info in the FACREF array instead */ + if(fr[match_idx].length>1) + { + ExtNode *ext = (ExtNode *)calloc_2(1,sizeof(struct ExtNode)); + ext->msi = 0; + ext->lsi = fr[match_idx].length-1; + n->ext = ext; + } + + n->head.time=-1; /* mark 1st node as negative time */ + n->head.v.val=1; + s->n=n; + + match_idx++; + } + +if(regex_matches) + { + free_2(process_mask); + numfacs = regex_matches; + regex_matches = 0; + process_mask = calloc(1, numfacs/8+1); + } + +facs=(struct symbol **)malloc_2(numfacs*sizeof(struct symbol *)); + +if(fast_tree_sort) + { + curnode=firstnode; + for(i=0;iname))>longestname) longestname=len; + curnode=curnode->nextinaet; + } + + fprintf(stderr, AET2_RDLOAD"Building facility hierarchy tree.\n"); + + init_tree(); + for(i=0;iname, i); + } + treeprune(treeroot); + + fprintf(stderr, AET2_RDLOAD"Sorting facility hierarchy tree.\n"); + treesort(treeroot, NULL); + order_facs_from_treesort(treeroot, &facs); + + facs_are_sorted=1; + } + else + { + curnode=firstnode; + for(i=0;iname))>longestname) longestname=len; + curnode=curnode->nextinaet; + while((ch=(*subst))) + { + if(ch==hier_delimeter) { *subst=0x01; } /* forces sort at hier boundaries */ + subst++; + } + } + + fprintf(stderr, AET2_RDLOAD"Sorting facilities at hierarchy boundaries.\n"); + wave_heapsort(facs,numfacs); + + for(i=0;iname; + while((ch=(*subst))) + { + if(ch==0x01) { *subst=hier_delimeter; } /* restore back to normal */ + subst++; + } + } + + facs_are_sorted=1; + + fprintf(stderr, AET2_RDLOAD"Building facility hierarchy tree.\n"); + + init_tree(); + for(i=0;iname, i); + } + treeprune(treeroot); + } + +min_time = first_cycle; max_time=last_cycle; +is_lx2 = LXT2_IS_AET2; + +if(skip_start || skip_end) + { + TimeType b_start, b_end; + + if(!skip_start) b_start = min_time; else b_start = unformat_time(skip_start, time_dimension); + if(!skip_end) b_end = max_time; else b_end = unformat_time(skip_end, time_dimension); + + if(b_startmax_time) b_start = max_time; + + if(b_endmax_time) b_end = max_time; + + if(b_start > b_end) + { + TimeType tmp_time = b_start; + b_start = b_end; + b_end = tmp_time; + } + + min_time = b_start; + max_time = b_end; + } + +fprintf(stderr, AET2_RDLOAD"["TTFormat"] start time.\n"AET2_RDLOAD"["TTFormat"] end time.\n", min_time, max_time); +return(max_time); +} + + +/* + * ae2 callback + */ +static void ae2_callback(uint64_t *time, unsigned int *facidx, char **value) +{ +struct HistEnt *htemp = histent_calloc(); +struct lx2_entry *l2e = lx2_table+(*facidx); +FACREF *f = fr+(*facidx); + +/* fprintf(stderr, "%Ld %d %s\n", *time, *facidx, *value); */ + +if(f->length>1) + { + htemp->v.vector = (char *)malloc_2(f->length); + memcpy(htemp->v.vector, *value, f->length); + } + else + { + switch(**value) + { + case '0': htemp->v.val = 0; break; + case '1': htemp->v.val = 3; break; + case 'H': + case 'Z': + case 'z': htemp->v.val = 2; break; + default: htemp->v.val = 1; break; + } + } + +htemp->time = (*time); + +if(l2e->histent_head) + { + l2e->histent_curr->next = htemp; + l2e->histent_curr = htemp; + } + else + { + l2e->histent_head = l2e->histent_curr = htemp; + } + +l2e->numtrans++; +} + + +int ae2_iterator(uint64_t start_cycle, uint64_t end_cycle) +{ +unsigned int i, j; +uint64_t cyc, ecyc, step_cyc; +struct ae2_ncycle_autosort *autosort[AE2_SECTION_SIZE]; +struct ae2_ncycle_autosort *deadlist=NULL; +struct ae2_ncycle_autosort *autofacs=NULL; + +ae2_msg_suppress = 1; +did_twirl = 0; + +autofacs = calloc(numfacs, sizeof(struct ae2_ncycle_autosort)); + +for(j=0;jend_cycle) break; + + for(i=0;i 1) continue; + if(!aet2_rd_get_fac_process_mask(i)) continue; + ae2_read_value(ae2, fr+i, cyc, buf); + if(strcmp(value[i], buf)) + { + strcpy(value[i], buf); + ae2_callback(&cyc, &i, &value[i]); + } + } + + for(i=0;i 1) continue; + if(!aet2_rd_get_fac_process_mask(i)) continue; + ncyc = ae2_read_next_value(ae2, fr+i, cyc, value[i]); + + if(ncyc!=cyc) + { + int offset = ncyc-cyc; + struct ae2_ncycle_autosort *t = autosort[offset]; + + autofacs[i].next = t; + autosort[offset] = autofacs+i; + } + else + { + struct ae2_ncycle_autosort *t = deadlist; + autofacs[i].next = t; + deadlist = autofacs+i; + } + } + + for(step_cyc = cyc+1 ; step_cyc <= ecyc ; step_cyc++) + { + int offset = step_cyc-cyc; + struct ae2_ncycle_autosort *t = autosort[offset]; + + if(step_cyc > end_cycle) break; + + if(t) + { + while(t) + { + uint64_t ncyc; + struct ae2_ncycle_autosort *tn = t->next; + + i = t-autofacs; + ae2_callback(&step_cyc, &i, &value[i]); + + ncyc = ae2_read_next_value(ae2, fr+i, step_cyc, value[i]); + + if(ncyc!=step_cyc) + { + int offset2 = ncyc-cyc; + struct ae2_ncycle_autosort *t = autosort[offset2]; + + autofacs[i].next = t; + autosort[offset2] = autofacs+i; + } + else + { + struct ae2_ncycle_autosort *t = deadlist; + autofacs[i].next = t; + deadlist = autofacs+i; + } + + t = tn; + } + } + } + } + + +free(autofacs); + +ae2_msg_suppress = 0; +if(did_twirl) + { + fprintf(stderr,"\n"); + did_twirl = 0; + } +return(0); +} + + +/* + * actually import an ae2 trace but don't do it if it's already been imported + */ +void import_ae2_trace(nptr np) +{ +struct HistEnt *htemp, *histent_tail; +int len, i; +FACREF *f; +int txidx; + +if(!(f=(FACREF *)(np->mvlfac))) return; /* already imported */ + +txidx = f - fr; + +/* new stuff */ +len = f->length; + +if(f->row <= 1) /* sorry, arrays not supported yet in the viewer */ + { + fprintf(stderr, "Import: %s\n", np->nname); + + aet2_rd_set_fac_process_mask(txidx); + ae2_iterator(min_time, max_time); + aet2_rd_clr_fac_process_mask(txidx); + } + else + { + fprintf(stderr, AET2_RDLOAD"Skipping array: %s (%d rows)\n", np->nname, f->row); + } + +histent_tail = htemp = histent_calloc(); +if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 2; + } + else + { + htemp->v.val = 2; /* z */ + } +htemp->time = MAX_HISTENT_TIME; + +htemp = histent_calloc(); +if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 1; + } + else + { + htemp->v.val = 1; /* x */ + } +htemp->time = MAX_HISTENT_TIME-1; +htemp->next = histent_tail; + +if(lx2_table[txidx].histent_curr) + { + lx2_table[txidx].histent_curr->next = htemp; + htemp = lx2_table[txidx].histent_head; + } + +if(len>1) + { + np->head.v.vector = (char *)malloc_2(len); + for(i=0;ihead.v.vector[i] = 1; + } + else + { + np->head.v.val = 1; /* x */ + } + +np->head.time = -2; +np->head.next = htemp; +np->numhist=lx2_table[txidx].numtrans +2 /*endcap*/ +1 /*frontcap*/; + +memset(lx2_table+txidx, 0, sizeof(struct lx2_entry)); /* zero it out */ + +np->curr = histent_tail; +np->mvlfac = NULL; /* it's imported and cached so we can forget it's an mvlfac now */ +} + + +/* + * pre-import many traces at once so function above doesn't have to iterate... + */ +void ae2_set_fac_process_mask(nptr np) +{ +FACREF *f; +int txidx; + +if(!(f=(FACREF *)(np->mvlfac))) return; /* already imported */ + +txidx = f - fr; + +if(f->row <= 1) /* sorry, arrays not supported */ + { + aet2_rd_set_fac_process_mask(txidx); + lx2_table[txidx].np = np; + } +} + + +void ae2_import_masked(void) +{ +int txidx, i, cnt=0; + +for(txidx=0;txidx100) + { + fprintf(stderr, AET2_RDLOAD"Extracting %d traces\n", cnt); + } + +ae2_iterator(min_time, max_time); + +for(txidx=0;txidxlength; + nptr np = lx2_table[txidx].np; + + histent_tail = htemp = histent_calloc(); + if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 2; + } + else + { + htemp->v.val = 2; /* z */ + } + htemp->time = MAX_HISTENT_TIME; + + htemp = histent_calloc(); + if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 1; + } + else + { + htemp->v.val = 1; /* x */ + } + htemp->time = MAX_HISTENT_TIME-1; + htemp->next = histent_tail; + + if(lx2_table[txidx].histent_curr) + { + lx2_table[txidx].histent_curr->next = htemp; + htemp = lx2_table[txidx].histent_head; + } + + if(len>1) + { + np->head.v.vector = (char *)malloc_2(len); + for(i=0;ihead.v.vector[i] = 1; + } + else + { + np->head.v.val = 1; /* x */ + } + + np->head.time = -2; + np->head.next = htemp; + np->numhist=lx2_table[txidx].numtrans +2 /*endcap*/ +1 /*frontcap*/; + + memset(lx2_table+txidx, 0, sizeof(struct lx2_entry)); /* zero it out */ + + np->curr = histent_tail; + np->mvlfac = NULL; /* it's imported and cached so we can forget it's an mvlfac now */ + aet2_rd_clr_fac_process_mask(txidx); + } + } +} + +#endif +/* ...of AET2_IS_PRESENT */ diff --git a/src/ae2.h b/src/ae2.h new file mode 100644 index 0000000..a9efcf2 --- /dev/null +++ b/src/ae2.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) Tony Bybell 2004. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + */ + +#ifndef WAVE_AE2RDR_H +#define WAVE_AE2RDR_H + +#ifndef _MSC_VER +#include +#endif +#include "vcd.h" +#include "lx2.h" + +#define AET2_RDLOAD "AE2LOAD | " + +struct ae2_ncycle_autosort +{ +struct ae2_ncycle_autosort *next; +}; + +struct regex_links +{ +struct regex_links *next; +void *pnt; +}; + + +TimeType ae2_main(char *fname, char *skip_start, char *skip_end, char *indirect_fname); +void import_ae2_trace(nptr np); +void ae2_set_fac_process_mask(nptr np); +void ae2_import_masked(void); + +#ifndef _MSC_VER +/* + * texsim prototypes/libae2rw interfacing... + */ +#define MAXFACLEN 65536 +#define AE2_SECTION_SIZE 256 +typedef unsigned long FACIDX; + +struct facref +{ +FACIDX s; /* symbol table key */ +char *facname; /* ptr to facility name */ +int offset; /* offset of reference */ +int length; /* length of reference */ +unsigned int row; /* row number for arrays */ +unsigned int row_high; /* row number for arrays */ +}; +typedef struct facref FACREF; + +typedef void* AE2_HANDLE; +typedef unsigned long AE2_SYMBOL; +typedef void (*AE2_SEVERROR) (const char*, ...); +typedef void (*AE2_MSG) (int, const char*, ...); +typedef void* (*AE2_ALLOC) (size_t size); +typedef void (*AE2_FREE) (void* ptr, size_t size); + +void ae2_initialize(AE2_SEVERROR error_fn, AE2_MSG msg_fn, AE2_ALLOC alloc_fn, AE2_FREE free_fn); +AE2_HANDLE ae2_read_initialize(FILE* file); +uint64_t ae2_read_start_cycle(AE2_HANDLE handle); +uint64_t ae2_read_end_cycle(AE2_HANDLE handle); +unsigned long ae2_read_num_sections(AE2_HANDLE handle); +uint64_t* ae2_read_ith_section_range(AE2_HANDLE handle, unsigned long section_idx); +unsigned long ae2_read_num_symbols(AE2_HANDLE handle); +unsigned long ae2_read_symbol_name(AE2_HANDLE handle, unsigned long symbol_idx, char* name); +unsigned long ae2_read_symbol_rows(AE2_HANDLE handle, unsigned long symbol_idx); +unsigned long ae2_read_symbol_length(AE2_HANDLE handle, unsigned long symbol_idx); +unsigned long ae2_read_value(AE2_HANDLE handle, FACREF* fr, uint64_t cycle, char* value); +uint64_t ae2_read_next_value(AE2_HANDLE handle, FACREF* fr, uint64_t cycle, char* value); +void ae2_read_close(AE2_HANDLE handle); +#endif + +#endif diff --git a/src/aet.c b/src/aet.c index 73a16fb..f001cd2 100644 --- a/src/aet.c +++ b/src/aet.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 2001. + * Copyright (c) Tony Bybell 2001-2004 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -11,7 +11,9 @@ #ifndef _MSC_VER #include +#ifndef __MINGW32__ #include +#endif #else #include #endif @@ -83,6 +85,17 @@ return(s); } +struct symbol *symadd_name_exists(char *name, int hv) +{ +struct symbol *s; + +s=(struct symbol *)calloc_2(1,sizeof(struct symbol)); +s->name = name; +s->next=sym[hv]; +sym[hv]=s; +return(s); +} + /* * find a slot already in the table... diff --git a/src/aet.h b/src/aet.h index 4c61a8d..baf39db 100644 --- a/src/aet.h +++ b/src/aet.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -21,8 +21,8 @@ #include "alloca.h" #include "analyzer.h" #include "currenttime.h" +#include "tree.h" #include "debug.h" -#include "tree.h" #define SYMPRIME 65519 #define WAVE_DECOMPRESSOR "gzip -cd " /* zcat alone doesn't cut it for AIX */ @@ -65,6 +65,7 @@ struct symbol *symfind(char *); struct symbol *symadd(char *, int); +struct symbol *symadd_name_exists(char *name, int hv); int hash(char *s); void facsplit(char *, int *, int *); diff --git a/src/alloca.h b/src/alloca.h index 9c16286..19c5cca 100644 --- a/src/alloca.h +++ b/src/alloca.h @@ -24,7 +24,7 @@ #ifndef __FreeBSD__ #ifndef __NetBSD__ -#ifndef __sun__ +#if !defined __sun__ && !defined _AIX #ifndef alloca #define alloca __alloca #endif diff --git a/src/analyzer.c b/src/analyzer.c index 747b47b..22e9867 100644 --- a/src/analyzer.c +++ b/src/analyzer.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -21,7 +21,7 @@ unsigned int default_flags=TR_RJUSTIFY; Times tims = {0, 0, 0, 0, 0, 0, 0}; -Traces traces = {0, NULL, NULL, NULL, NULL, 0}; +Traces traces = {0, 0, NULL, NULL, NULL, NULL, 0}; /* * extract last n levels of hierarchy @@ -86,14 +86,14 @@ { if( traces.first == NULL ) { - t->next = t->prev = NULL; + t->t_next = t->t_prev = NULL; traces.first = traces.last = t; } else { - t->next = NULL; - t->prev = traces.last; - traces.last->next = t; + t->t_next = NULL; + t->t_prev = traces.last; + traces.last->t_next = t; traces.last = t; } traces.total++; @@ -109,7 +109,6 @@ shadow_string = NULL; shadow_straces = st; - } } @@ -146,7 +145,7 @@ return( 0 ); } AddTrace(t); -t->flags=TR_BLANK; +t->flags = TR_BLANK | (default_flags & TR_COLLAPSED); if((comment=precondition_string(commentname))) { @@ -173,6 +172,7 @@ return( 0 ); } t->flags=TR_BLANK; + if((comm=precondition_string(comment))) { @@ -404,19 +404,19 @@ traces.total--; if( t == traces.first ) { - traces.first = t->next; - if( t->next ) - t->next->prev = NULL; + traces.first = t->t_next; + if( t->t_next ) + t->t_next->t_prev = NULL; else traces.last = NULL; } else { - t->prev->next = t->next; - if( t->next ) - t->next->prev = t->prev; + t->t_prev->t_next = t->t_next; + if( t->t_next ) + t->t_next->t_prev = t->t_prev; else - traces.last = t->prev; + traces.last = t->t_prev; } if(dofree) @@ -437,7 +437,7 @@ while(t) { - t2=t->next; + t2=t->t_next; FreeTrace(t); t=t2; } @@ -463,18 +463,54 @@ while(t) { if((t->flags)&(TR_HIGHLIGHT)) break; - t=t->next; + t=t->t_next; } if(!t) return(NULL); /* keeps a double cut from blowing out the buffer */ signalwindow_width_dirty=1; FreeCutBuffer(); + +/* + * propagate cut for whole comment group if comment selected and collapsed... + */ t=traces.first; - while(t) { - tnext=t->next; + top_of_cut: + if( (t->name) && ((t->flags&(TR_BLANK|TR_HIGHLIGHT))==(TR_BLANK|TR_HIGHLIGHT)) ) + { + if(t->flags&TR_COLLAPSED) + { + t=t->t_next; + while(t) + { + if(t->flags & TR_BLANK) goto top_of_cut; + t->flags |= TR_HIGHLIGHT; + t=t->t_next; + } + break; + } + else + { + t=t->t_next; /* for sanity, ensure we're uncollapsed */ + while(t) + { + if(t->flags & TR_BLANK) goto top_of_cut; + t->flags &= ~TR_COLLAPSED; + t=t->t_next; + } + break; + } + } + + t=t->t_next; + } + +t=traces.first; +while(t) + { + tnext=t->t_next; if(t->flags&TR_HIGHLIGHT) { traces.bufferlast=t; @@ -485,15 +521,15 @@ if(!current) { first=current=t; - t->prev=NULL; - t->next=NULL; + t->t_prev=NULL; + t->t_next=NULL; } else { - current->next=t; - t->prev=current; + current->t_next=t; + t->t_prev=current; current=t; - t->next=NULL; + t->t_next=NULL; } } t=tnext; @@ -522,7 +558,7 @@ { traces.last=t; traces.total++; - t=t->next; + t=t->t_next; } traces.buffer=traces.bufferlast=NULL; @@ -533,15 +569,35 @@ while(t) { - if(t->flags&TR_HIGHLIGHT) tinsert=t; - t=t->next; + if(t->flags&TR_HIGHLIGHT) + { + if((t->flags & (TR_BLANK|TR_COLLAPSED)) && (t->name)) + { + tinsert=t; + t=t->t_next; + while(t) + { + if(t->flags & TR_BLANK) goto nxtl; + tinsert=t; + t=t->t_next; + } + break; + } + else + { + tinsert=t; + } + } + +nxtl: t=t->t_next; } if(!tinsert) tinsert=traces.last; -tinsertnext=tinsert->next; -tinsert->next=traces.buffer; -traces.buffer->prev=tinsert; -traces.bufferlast->next=tinsertnext; + +tinsertnext=tinsert->t_next; +tinsert->t_next=traces.buffer; +traces.buffer->t_prev=tinsert; +traces.bufferlast->t_next=tinsertnext; traces.total+=traces.buffercount; if(!tinsertnext) @@ -550,7 +606,7 @@ } else { - tinsertnext->prev=traces.bufferlast; + tinsertnext->t_prev=traces.bufferlast; } traces.buffer=traces.bufferlast=NULL; @@ -579,13 +635,13 @@ prev=t; t->flags&=(~TR_HIGHLIGHT); traces.total++; - t=t->next; - } - -if((prev->next=traces.first)) + t=t->t_next; + } + +if((prev->t_next=traces.first)) { /* traces.last current value is ok as it stays the same */ - traces.first->prev=prev; /* but we need the reverse link back up */ + traces.first->t_prev=prev; /* but we need the reverse link back up */ } else { @@ -623,7 +679,7 @@ } *(tsort_pnt++)=t; - t=t->next; + t=t->t_next; } traces.first=*(--tsort_pnt); @@ -634,21 +690,21 @@ if(i==traces.total-1) { - t->prev=NULL; + t->t_prev=NULL; } else { - t->prev=*(tsort_pnt+1); + t->t_prev=*(tsort_pnt+1); } if(i) { - t->next=*(--tsort_pnt); + t->t_next=*(--tsort_pnt); } } traces.last=*tsort; -traces.last->next=NULL; +traces.last->t_next=NULL; return(1); } @@ -748,7 +804,7 @@ */ int TracesAlphabetize(int mode) { -Trptr t, prev; +Trptr t, prev = NULL; Trptr *tsort, *tsort_pnt; char *subst, ch; int i; @@ -774,7 +830,7 @@ subst++; } - t=t->next; + t=t->t_next; } switch(mode) @@ -794,12 +850,12 @@ if(!i) { traces.first=t; - t->prev=NULL; + t->t_prev=NULL; } else { - prev->next=t; - t->prev=prev; + prev->t_next=t; + t->t_prev=prev; } prev=t; @@ -813,8 +869,154 @@ } traces.last=prev; -prev->next=NULL; +prev->t_next=NULL; return(1); } + +/* + * trace traversal with collapsed groups + */ +Trptr GiveNextTrace(Trptr t) +{ +if((t->name)&&((t->flags & TR_ISCOLLAPSED)==TR_ISCOLLAPSED)) + { + t=t->t_next; + while(t) + { + if(t->flags & TR_BLANK) break; + t=t->t_next; + } + } + else + { + t=t->t_next; + } + +return(t); +} + + +Trptr GivePrevTrace(Trptr t) +{ +Trptr t2 = t; +int iter = 0; + +while(t2) + { + if((t2->flags & TR_COLLAPSED) && (!(t2->flags & TR_BLANK))) + { + if(!iter) + { + t2=t2->t_prev; + iter=1; + continue; + } + else + { + break; + } + } + else + { + if(iter) break; + return(t2->t_prev); + } + } + +return(t2); +} + + +int CollapseTrace(Trptr t) +{ +int rc; +int flg; + +if((rc=((t->name)&&(t->flags&TR_BLANK)))) + { + Trptr t2 = t; + + t2->flags ^= TR_COLLAPSED; + flg = t2->flags & TR_COLLAPSED; + t2->flags &= ~TR_HIGHLIGHT; + + t2=t->t_next; + while(t2) + { + if(t2->flags & TR_BLANK) break; + t2->flags &= ~(TR_COLLAPSED|TR_HIGHLIGHT); + t2->flags |= flg; + t2=t2->t_next; + } + + UpdateTracesVisible(); + } + +return(rc); +} + + +int UpdateTracesVisible(void) +{ +Trptr t = traces.first; +int cnt = 0; + +while(t) + { + if( (t->flags & TR_BLANK) || (!(t->flags & TR_COLLAPSED)) ) + { + cnt++; + } + + t=t->t_next; + } + +traces.visible = cnt; +return(cnt); +} + + +void CollapseAllGroups(void) +{ +Trptr t = traces.first; +int mode = 0; + +while(t) + { + t->flags &= ~TR_HIGHLIGHT; + + if(t->flags & TR_BLANK) + { + mode = (t->name != NULL); + } + + if(mode) + { + t->flags |= TR_COLLAPSED; + } + else + { + t->flags &= ~TR_COLLAPSED; + } + + t=t->t_next; + } + +UpdateTracesVisible(); +} + + +void ExpandAllGroups(void) +{ +Trptr t = traces.first; + +while(t) + { + t->flags &= ~(TR_HIGHLIGHT|TR_COLLAPSED); + t=t->t_next; + } + +UpdateTracesVisible(); +} diff --git a/src/analyzer.h b/src/analyzer.h index 315a6e8..eada96a 100644 --- a/src/analyzer.h +++ b/src/analyzer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -137,6 +137,7 @@ TimeType lmbcache; /* initial marker pos */ TimeType timecache; /* to get around floating pt limitation */ TimeType laststart; /* caches last set value */ + TimeType baseline; /* baseline (center button) marker */ gdouble zoom; /* current zoom */ gdouble prevzoom; /* for zoom undo */ @@ -147,6 +148,7 @@ typedef struct { int total; /* total number of traces */ + int visible; /* total number of (uncollapsed) traces */ Trptr first; /* ptr. to first trace in list */ Trptr last; /* end of list of traces */ Trptr buffer; /* cut/copy buffer of traces */ @@ -164,14 +166,20 @@ typedef struct TraceEnt { - Trptr next; /* doubly linked list of traces */ - Trptr prev; + Trptr t_next; /* doubly linked list of traces */ + Trptr t_prev; + + Trptr t_group; + char *t_group_name; + char *name; /* name stripped of path */ char *asciivalue; /* value that marker points to */ TimeType asciitime; /* time this value corresponds with */ TimeType shift; /* offset added to all entries in the trace */ - char is_alias; /* set when it's an alias (safe to free t->name then) */ - short vector; /* 1 if bit vector, 0 if node */ + + unsigned is_alias : 1; /* set when it's an alias (safe to free t->name then) */ + unsigned vector : 1; /* 1 if bit vector, 0 if node */ + unsigned int flags; /* see def below in TraceEntFlagBits */ union { @@ -184,7 +192,7 @@ enum TraceEntFlagBits { TR_HIGHLIGHT_B, TR_HEX_B, TR_DEC_B, TR_BIN_B, TR_OCT_B, TR_RJUSTIFY_B, TR_INVERT_B, TR_REVERSE_B, TR_EXCLUDE_B, - TR_BLANK_B, TR_SIGNED_B, TR_ASCII_B + TR_BLANK_B, TR_SIGNED_B, TR_ASCII_B, TR_COLLAPSED_B }; #define TR_HIGHLIGHT (1<flags; +nbits=t->n.vec->nbits; +bits=v->v; + +if(flags&TR_INVERT) + { + memcpy(xtab,xrev,4); + } + else + { + memcpy(xtab,xfwd,4); + } + +newbuff=(char *)malloc_2(nbits+6); /* for justify */ +if(flags&TR_REVERSE) + { + char *fwdpnt, *revpnt; + + fwdpnt=bits; + revpnt=newbuff+nbits+6; + for(i=0;i<3;i++) *(--revpnt)=xtab[0]; + for(i=0;i 0x7f || !isprint(val)) *pnt++ = '.'; else *pnt++ = val; + found=1; + } + + parse+=8; + } + if (!found && !show_base) { + *(pnt++)='"'; + *(pnt++)='"'; + } + + if(show_base) { *(pnt++)='"'; } + *(pnt++)=0x00; + } +else if((flags&TR_HEX)||((flags&(TR_DEC|TR_SIGNED))&&(nbits>64))) + { + char *parse; + + len=(nbits/4)+2+1; /* $xxxxx */ + os=pnt=(char *)calloc_2(1,len); + if(show_base) { *(pnt++)='$'; } + + parse=(flags&TR_RJUSTIFY)?(newbuff+((nbits+3)&3)):(newbuff+3); + + for(i=0;in.nd->ext->msi-t->n.nd->ext->lsi; + if(nbits<0)nbits=-nbits; + nbits++; + res = 3; + for (i = 0; i < nbits; i++) + switch (*vec) { + case 1: + case 'x': + case 'X': + return(1); + case 2: + case 'z': + case 'Z': + if (res == 0) return(1); vec++; res = 2; break; + default: if (res == 2) return(1); vec++; res = 0; break; + } + + return(res); +} + +int vtype2(Trptr t, vptr v) +{ + int i, nbits, res; + char *vec=v->v; + + if (vec == NULL) + return(1); + nbits=t->n.vec->nbits; + res = 3; + for (i = 0; i < nbits; i++) + { + switch (*vec) + { + case 1: + case 'x': + case 'X': + return(1); + case 2: + case 'z': + case 'Z': + if (res == 0) return(1); vec++; res = 2; break; + default: if (res == 2) return(1); vec++; res = 0; break; + } + } + + return(res); +} + +/* + * convert trptr+hptr vectorstring into an ascii string + */ +char *convert_ascii_vec(Trptr t, char *vec) +{ +Ulong flags; +int nbits; +char *bits; +char *os, *pnt, *newbuff; +int i, j, len; +char xtab[4]; + +static char xfwd[4]={0,1,2,3}; +static char xrev[4]={3,1,2,0}; + +flags=t->flags; + +nbits=t->n.nd->ext->msi-t->n.nd->ext->lsi; +if(nbits<0)nbits=-nbits; +nbits++; + +if(vec) + { + bits=vec; + if(*vec>3) /* convert as needed */ + for(i=0;i 0x7f || !isprint(val)) *pnt++ = '.'; else *pnt++ = val; + found=1; + } + + parse+=8; + } + if (!found && !show_base) { + *(pnt++)='"'; + *(pnt++)='"'; + } + + if(show_base) { *(pnt++)='"'; } + *(pnt++)=0x00; + } +else if((flags&TR_HEX)||((flags&(TR_DEC|TR_SIGNED))&&(nbits>64))) + { + char *parse; + + len=(nbits/4)+2+1; /* $xxxxx */ + os=pnt=(char *)calloc_2(1,len); + if(show_base) { *(pnt++)='$'; } + + parse=(flags&TR_RJUSTIFY)?(newbuff+((nbits+3)&3)):(newbuff+3); + + for(i=0;i extern int color_back; +extern int color_baseline; extern int color_grid; extern int color_high; extern int color_low; diff --git a/src/currenttime.c b/src/currenttime.c index d86b1dc..fd02e07 100644 --- a/src/currenttime.c +++ b/src/currenttime.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -15,12 +15,15 @@ char use_maxtime_display=1; static GtkWidget *max_or_marker_label=NULL; +static GtkWidget *base_or_curtime_label=NULL; +static TimeType cached_currenttimeval=0; TimeType currenttime=0; TimeType max_time=0; TimeType min_time=-1; char display_grid=~0; /* default to displaying grid */ -char time_dimension='n'; +TimeType time_scale=1; /* multiplier is 1, 10, 100 */ +char time_dimension='n'; /* nsec, psec, etc... */ static char *time_prefix=" munpf"; static GtkWidget *maxtimewid; static GtkWidget *curtimewid; @@ -44,10 +47,11 @@ } } -TimeType unformat_time(char *buf, char dim) +TimeType unformat_time(const char *buf, char dim) { TimeType rval; -char *pnt, *offs=NULL, *doffs; +const char *pnt; +char *offs=NULL, *doffs; char ch; int i, ich, delta; @@ -158,14 +162,27 @@ { if(val>=0) { - if(tims.lmbcache>=0) val-=tims.lmbcache; /* do delta instead */ - - if((tims.lmbcache>=0)&&(val>=0)) + if(tims.baseline>=0) { + val-=tims.baseline; /* do delta instead */ + *maxtext='B'; + if(val>=0) + { + *(maxtext+1)='+'; + reformat_time(maxtext+2, val, time_dimension); + } + else + { + reformat_time(maxtext+1, val, time_dimension); + } + } + else if(tims.lmbcache>=0) + { + val-=tims.lmbcache; /* do delta instead */ *maxtext='+'; reformat_time(maxtext+1, val, time_dimension); } - else + else { reformat_time(maxtext, val, time_dimension); } @@ -180,6 +197,23 @@ } +void update_basetime(TimeType val) +{ +if(val>=0) + { + gtk_label_set(GTK_LABEL(base_or_curtime_label), "Base Marker"); + reformat_time(curtext, val, time_dimension); + } + else + { + gtk_label_set(GTK_LABEL(base_or_curtime_label), "Current Time"); + reformat_time_blackout(curtext, cached_currenttimeval, time_dimension); + } + +gtk_label_set(GTK_LABEL(curtimewid), curtext); +} + + void update_maxtime(TimeType val) { max_time=val; @@ -194,9 +228,14 @@ void update_currenttime(TimeType val) { -currenttime=val; -reformat_time_blackout(curtext, val, time_dimension); -gtk_label_set(GTK_LABEL(curtimewid), curtext); +cached_currenttimeval = val; + +if(tims.baseline<0) + { + currenttime=val; + reformat_time_blackout(curtext, val, time_dimension); + gtk_label_set(GTK_LABEL(curtimewid), curtext); + } } @@ -204,7 +243,6 @@ GtkWidget * create_time_box(void) { -GtkWidget *label2; GtkWidget *mainbox; max_or_marker_label=(use_maxtime_display) @@ -223,19 +261,29 @@ maxtimewid=gtk_label_new(maxtext); -label2=gtk_label_new("Current Time"); curtext=(char *)malloc_2(40); -reformat_time(curtext, (currenttime=min_time), time_dimension); - -curtimewid=gtk_label_new(curtext); +if(tims.baseline<0) + { + base_or_curtime_label=gtk_label_new("Current Time"); + reformat_time(curtext, (currenttime=min_time), time_dimension); + curtimewid=gtk_label_new(curtext); + } + else + { + base_or_curtime_label=gtk_label_new("Base Marker"); + reformat_time(curtext, tims.baseline, time_dimension); + curtimewid=gtk_label_new(curtext); + } mainbox=gtk_vbox_new(FALSE, 0); + gtk_box_pack_start(GTK_BOX(mainbox), max_or_marker_label, TRUE, FALSE, 0); gtk_widget_show(max_or_marker_label); gtk_box_pack_start(GTK_BOX(mainbox), maxtimewid, TRUE, FALSE, 0); gtk_widget_show(maxtimewid); -gtk_box_pack_start(GTK_BOX(mainbox), label2, TRUE, FALSE, 0); -gtk_widget_show(label2); + +gtk_box_pack_start(GTK_BOX(mainbox), base_or_curtime_label, TRUE, FALSE, 0); +gtk_widget_show(base_or_curtime_label); gtk_box_pack_start(GTK_BOX(mainbox), curtimewid, TRUE, FALSE, 0); gtk_widget_show(curtimewid); @@ -278,3 +326,34 @@ } +/* + * called by lxt/lxt2/vzt reader inits + */ +void exponent_to_time_scale(signed char scale) +{ +switch(scale) + { + case 0: time_dimension = 's'; break; + + case -1: time_scale = LLDescriptor(100); time_dimension = 'm'; break; + case -2: time_scale = LLDescriptor(10); + case -3: time_dimension = 'm'; break; + + case -4: time_scale = LLDescriptor(100); time_dimension = 'u'; break; + case -5: time_scale = LLDescriptor(10); + case -6: time_dimension = 'u'; break; + + case -10: time_scale = LLDescriptor(100); time_dimension = 'p'; break; + case -11: time_scale = LLDescriptor(10); + case -12: time_dimension = 'p'; break; + + case -13: time_scale = LLDescriptor(100); time_dimension = 'f'; break; + case -14: time_scale = LLDescriptor(10); + case -15: time_dimension = 'f'; break; + + case -7: time_scale = LLDescriptor(100); time_dimension = 'n'; break; + case -8: time_scale = LLDescriptor(10); + case -9: + default: time_dimension = 'n'; break; + } +} diff --git a/src/currenttime.h b/src/currenttime.h index c73c12c..a403eb5 100644 --- a/src/currenttime.h +++ b/src/currenttime.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2001 + * Copyright (c) Tony Bybell 1999-2005 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -16,7 +16,7 @@ #include #include "analyzer.h" -#define WAVE_VERSION_INFO "GTKWave Analyzer v1.3.34 (w)1999-2003 BSI" +#define WAVE_VERSION_INFO "GTKWave Analyzer v1.3.63 (w)1999-2005 BSI" struct blackout_region_t { @@ -26,6 +26,7 @@ extern struct blackout_region_t *blackout_regions; +extern int num_cpus; /* specify number of CPUs for parallelizable ops */ extern char is_vcd; extern char is_lxt; extern char lxt_clock_compress_to_z; @@ -57,6 +58,7 @@ extern char zoom_was_explicitly_set; /* set on '*' .sav file read */ extern char use_full_precision; +extern TimeType time_scale; extern char time_dimension; extern char do_resize_signals; extern char do_zoom_center; @@ -102,6 +104,7 @@ void update_markertime(TimeType val); void update_maxtime(TimeType val); +void update_basetime(TimeType val); void update_currenttime(TimeType val); void update_maxmarker_labels(void); void UpdateSigValue(Trptr t); @@ -113,6 +116,7 @@ void service_zoom_in(GtkWidget *text, gpointer data); void service_zoom_out(GtkWidget *text, gpointer data); void service_zoom_fit(GtkWidget *text, gpointer data); +void service_zoom_full(GtkWidget *text, gpointer data); void service_zoom_undo(GtkWidget *text, gpointer data); void service_zoom_left(GtkWidget *text, gpointer data); void service_zoom_right(GtkWidget *text, gpointer data); @@ -129,7 +133,7 @@ gint signalarea_configure_event(GtkWidget *widget, GdkEventConfigure *event); gint wavearea_configure_event(GtkWidget *widget, GdkEventConfigure *event); void entrybox(char *title, int width, char *default_text, int maxch, GtkSignalFunc func); -void fileselbox(char *title, char **filesel_path, GtkSignalFunc func); +void fileselbox(char *title, char **filesel_path, GtkSignalFunc ok_func, GtkSignalFunc notok_func); void status_text(char *str); void searchbox(char *title, GtkSignalFunc func); void showchange(char *title, Trptr t, GtkSignalFunc func); @@ -150,7 +154,7 @@ int hier_searchbox_is_active(void); void simplereqbox(char *title, int width, char *default_text, - char *oktext, char *canceltext, GtkSignalFunc func); + char *oktext, char *canceltext, GtkSignalFunc func, int is_alert); void helpbox(char *title, int width, char *default_text); void help_text(char *str); @@ -161,13 +165,21 @@ void dnd_error(void); void reformat_time(char *buf, TimeType val, char dim); -TimeType unformat_time(char *buf, char dim); +TimeType unformat_time(const char *buf, char dim); void time_trunc_set(void); TimeType time_trunc(TimeType t); +void exponent_to_time_scale(signed char scale); int wave_regex_compile(char *regex); int wave_regex_match(char *str); +void *wave_regex_alloc_compile(char *regex); +int wave_regex_alloc_match(void *mreg, char *str); +void wave_regex_alloc_free(void *pnt); + void load_all_fonts(void); #endif + + + diff --git a/src/debug.c b/src/debug.c index d4229fb..68d6b89 100644 --- a/src/debug.c +++ b/src/debug.c @@ -158,9 +158,9 @@ * y/on default to '1' * n/nonnum default to '0' */ -char *atoi_cont_ptr=NULL; - -TimeType atoi_64(char *str) +const char *atoi_cont_ptr=NULL; + +TimeType atoi_64(const char *str) { TimeType val=0; unsigned char ch, nflag=0; diff --git a/src/debug.h b/src/debug.h index 4606461..b1aadd0 100644 --- a/src/debug.h +++ b/src/debug.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -32,12 +32,16 @@ #ifdef G_HAVE_GINT64 typedef gint64 TimeType; typedef guint64 UTimeType; - #ifndef _MSC_VER #define LLDescriptor(x) x##LL #define ULLDescriptor(x) x##ULL - #define TTFormat "%lld" - #define UTTFormat "%llu" + #ifdef __MINGW32__ + #define TTFormat "%I64d" + #define UTTFormat "%I64u" + #else + #define TTFormat "%lld" + #define UTTFormat "%llu" + #endif #else #define LLDescriptor(x) x##i64 #define ULLDescriptor(x) x##i64 @@ -49,7 +53,6 @@ #else typedef long TimeType; typedef unsigned long UTimeType; - #define TTFormat "%d" #define UTTFormat "%u" @@ -92,8 +95,8 @@ void *realloc_2(void *ptr, size_t size); void *calloc_2(size_t nmemb, size_t size); -TimeType atoi_64(char *str); -extern char *atoi_cont_ptr; /* for unformat_time()'s parse continue for the time unit */ +TimeType atoi_64(const char *str); +extern const char *atoi_cont_ptr; /* for unformat_time()'s parse continue for the time unit */ void gtk_tooltips_set_tip_2(GtkTooltips *tooltips, GtkWidget *widget, const gchar *tip_text, const gchar *tip_private); diff --git a/src/entry.c b/src/entry.c index 8278917..5960ac0 100644 --- a/src/entry.c +++ b/src/entry.c @@ -8,6 +8,7 @@ */ #include +#include "gtk12compat.h" #include "debug.h" #include @@ -18,7 +19,7 @@ static void enter_callback(GtkWidget *widget, GtkWidget *nothing) { - gchar *entry_text; + G_CONST_RETURN gchar *entry_text; int len; entry_text = gtk_entry_get_text(GTK_ENTRY(entry)); DEBUG(printf("Entry contents: %s\n", entry_text)); diff --git a/src/file.c b/src/file.c index 00dbd9a..98f347e 100644 --- a/src/file.c +++ b/src/file.c @@ -8,17 +8,18 @@ */ #include +#include "gtk12compat.h" #include "debug.h" #include static GtkWidget *fs; char **fileselbox_text=NULL; char filesel_ok=0; -static GtkSignalFunc cleanup; +static GtkSignalFunc cleanup, bad_cleanup; static void enter_callback(GtkWidget *widget, GtkFileSelection *fw) { -char *allocbuf; +G_CONST_RETURN char *allocbuf; int alloclen; allocbuf=gtk_file_selection_get_filename(GTK_FILE_SELECTION(fs)); @@ -41,18 +42,21 @@ DEBUG(printf("Filesel Entry Cancel\n")); gtk_grab_remove(fs); gtk_widget_destroy(fs); + if(bad_cleanup) bad_cleanup(); } static void destroy_callback(GtkWidget *widget, GtkWidget *nothing) { DEBUG(printf("Filesel Destroy\n")); + if(bad_cleanup) bad_cleanup(); } -void fileselbox(char *title, char **filesel_path, GtkSignalFunc func) +void fileselbox(char *title, char **filesel_path, GtkSignalFunc ok_func, GtkSignalFunc notok_func) { fileselbox_text=filesel_path; filesel_ok=0; -cleanup=func; +cleanup=ok_func; +bad_cleanup=notok_func; fs=gtk_file_selection_new(title); gtk_signal_connect(GTK_OBJECT(fs), "destroy", (GtkSignalFunc) destroy_callback, NULL); diff --git a/src/getopt.c b/src/getopt.c new file mode 100644 index 0000000..6725a46 --- /dev/null +++ b/src/getopt.c @@ -0,0 +1,123 @@ +/* + * getopt.c -- + * + * Standard UNIX getopt function. Code is from BSD. + * + * Copyright (c) 1987-2001 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: + * + * A. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * B. 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. + * C. Neither the names of the copyright holders 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 COPYRIGHT HOLDERS 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. + */ + +/* #if !defined(lint) + * static char sccsid[] = "@(#)getopt.c 8.2 (Berkeley) 4/2/94"; + * #endif + */ + +#include +#include +#include + +/* declarations to provide consistent linkage */ +extern char *optarg; +extern int optind; +extern int opterr; + +int opterr = 1, /* if error message should be printed */ + optind = 1, /* index into parent argv vector */ + optopt, /* character checked for validity */ + optreset; /* reset getopt */ +char *optarg; /* argument associated with option */ + +#define BADCH (int)'?' +#define BADARG (int)':' +#define EMSG "" + +/* + * getopt -- + * Parse argc/argv argument vector. + */ +int +getopt(nargc, nargv, ostr) + int nargc; + char * const *nargv; + const char *ostr; +{ + static char *place = EMSG; /* option letter processing */ + char *oli; /* option letter list index */ + + if (optreset || !*place) { /* update scanning pointer */ + optreset = 0; + if (optind >= nargc || *(place = nargv[optind]) != '-') { + place = EMSG; + return (EOF); + } + if (place[1] && *++place == '-') { /* found "--" */ + ++optind; + place = EMSG; + return (EOF); + } + } /* option letter okay? */ + if ((optopt = (int)*place++) == (int)':' || + !(oli = strchr(ostr, optopt))) { + /* + * if the user didn't specify '-' as an option, + * assume it means EOF. + */ + if (optopt == (int)'-') + return (EOF); + if (!*place) + ++optind; + if (opterr && *ostr != ':') + (void)fprintf(stderr, + "%s: illegal option -- %c\n", __FILE__, optopt); + return (BADCH); + } + if (*++oli != ':') { /* don't need argument */ + optarg = NULL; + if (!*place) + ++optind; + } + else { /* need an argument */ + if (*place) /* no white space */ + optarg = place; + else if (nargc <= ++optind) { /* no arg */ + place = EMSG; + if (*ostr == ':') + return (BADARG); + if (opterr) + (void)fprintf(stderr, + "%s: option requires an argument -- %c\n", + __FILE__, optopt); + return (BADCH); + } + else /* white space */ + optarg = nargv[optind]; + place = EMSG; + ++optind; + } + return (optopt); /* dump back option letter */ +} + diff --git a/src/gtk12compat.h b/src/gtk12compat.h index 5960847..9eb8200 100644 --- a/src/gtk12compat.h +++ b/src/gtk12compat.h @@ -3,7 +3,7 @@ #if WAVE_USE_GTK2 -#define WAVE_GTKIFE(a,b,c,d,e) a,b,c,d,e,NULL +#define WAVE_GTKIFE(a,b,c,d,e) {a,b,c,d,e,NULL} #define WAVE_GDK_GET_POINTER(a,b,c,bi,ci,d) gdk_window_get_pointer(a,bi,ci,d) #define WAVE_GDK_GET_POINTER_COPY x=xi; y=yi; #define WAVE_GTK_SIGFONT gdk_font_load("-*-courier-*-r-*-*-14-*-*-*-*-*-*-*"); \ @@ -14,7 +14,13 @@ #else -#define WAVE_GTKIFE(a,b,c,d,e) a,b,c,d,e +#if !defined __MINGW32__ && !defined _MSC_VER +#ifndef G_CONST_RETURN +#define G_CONST_RETURN +#endif +#endif + +#define WAVE_GTKIFE(a,b,c,d,e) {a,b,c,d,e} #define WAVE_GDK_GET_POINTER(a,b,c,bi,ci,d) gdk_input_window_get_pointer(a, event->deviceid, b, c, NULL, NULL, NULL, d) #define WAVE_GDK_GET_POINTER_COPY #define WAVE_GTK_SIGFONT wavearea->style->font diff --git a/src/helpers/Makefile.in b/src/helpers/Makefile.in index b5c4a44..410a12d 100644 --- a/src/helpers/Makefile.in +++ b/src/helpers/Makefile.in @@ -1,32 +1,48 @@ CC = @CC@ -CFLAGS = -O2 -lz -lbz2 +BIGFILES = -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 AIXFLAGS = -bmaxdata:0x80000000 +CFLAGS = -O2 -I../libz -I../libbz2 DEBUGS = all: mvlbin clean: rm -rf mvl2vcd mvl2lxt tex2vcd vcd2lxt *.core core ../../bin/mvl2vcd ../../bin/mvl2lxt ../../bin/tex2vcd ../../bin/vcd2lxt - rm -rf lxt2vcd vcd2lxt2 ../../bin/lxt2vcd ../../bin/vcd2lxt2 + rm -rf lxt2vcd vcd2lxt2 vzt2vcd vcd2vzt ../../bin/lxt2vcd ../../bin/vcd2lxt2 ../../bin/vzt2vcd ../../bin/vcd2vzt + cd ../libz ; make clean + cd ../libbz2 ; make clean -mvlbin: mvl2vcd mvl2lxt tex2vcd vcd2lxt lxt2vcd vcd2lxt2 - cp mvl2vcd ../../bin; cp tex2vcd ../../bin; cp mvl2lxt ../../bin; cp vcd2lxt ../../bin; cp lxt2vcd ../../bin; cp vcd2lxt2 ../../bin +mvlbin: mvl2vcd mvl2lxt tex2vcd vcd2lxt lxt2vcd vcd2lxt2 vzt2vcd vcd2vzt + cp mvl2vcd ../../bin; cp tex2vcd ../../bin; cp mvl2lxt ../../bin; cp vcd2lxt ../../bin; + cp lxt2vcd ../../bin; cp vcd2lxt2 ../../bin; cp vzt2vcd ../../bin; cp vcd2vzt ../../bin; mvl2vcd: mvl2vcd.c $(CC) $(CFLAGS) -o mvl2vcd mvl2vcd.c -mvl2lxt: mvl2lxt.c lxt_write.c lxt_write.h - $(CC) $(CFLAGS) -o mvl2lxt mvl2lxt.c lxt_write.c +mvl2lxt: mvl2lxt.c lxt_write.c lxt_write.h ../libz/libz.a ../libbz2/libbz2.a + $(CC) $(CFLAGS) -o mvl2lxt mvl2lxt.c lxt_write.c ../libz/libz.a ../libbz2/libbz2.a tex2vcd: tex2vcd.c $(CC) $(CFLAGS) -o tex2vcd tex2vcd.c -vcd2lxt: vcd2lxt.c lxt_write.c lxt_write.h v2l_debug.c v2l_debug.h v2l_analyzer.h - $(CC) $(CFLAGS) -o vcd2lxt vcd2lxt.c lxt_write.c v2l_debug.c +vcd2lxt: vcd2lxt.c lxt_write.c lxt_write.h v2l_debug.c v2l_debug.h v2l_analyzer.h ../libz/libz.a ../libbz2/libbz2.a + $(CC) $(CFLAGS) -o vcd2lxt vcd2lxt.c lxt_write.c v2l_debug.c ../libz/libz.a ../libbz2/libbz2.a -lxt2vcd: lxt2_read.c lxt2_read.h lxt2vcd.c - $(CC) $(CFLAGS) -o lxt2vcd lxt2vcd.c lxt2_read.c +lxt2vcd: lxt2_read.c lxt2_read.h lxt2vcd.c scopenav.c ../libz/libz.a + $(CC) $(CFLAGS) -o lxt2vcd lxt2vcd.c lxt2_read.c scopenav.c ../libz/libz.a -vcd2lxt2: vcd2lxt2.c lxt2_write.c lxt2_write.h v2l_debug_lxt2.c v2l_debug_lxt2.h v2l_analyzer_lxt2.h - $(CC) $(CFLAGS) -o vcd2lxt2 vcd2lxt2.c lxt2_write.c v2l_debug_lxt2.c +vcd2lxt2: vcd2lxt2.c lxt2_write.c lxt2_write.h v2l_debug_lxt2.c v2l_debug_lxt2.h v2l_analyzer_lxt2.h ../libz/libz.a + $(CC) $(CFLAGS) -o vcd2lxt2 vcd2lxt2.c lxt2_write.c v2l_debug_lxt2.c ../libz/libz.a +vzt2vcd: vzt_read.c vzt_read.h vzt2vcd.c scopenav.c ../libz/libz.a + $(CC) $(CFLAGS) -o vzt2vcd vzt2vcd.c vzt_read.c scopenav.c ../libz/libz.a ../libbz2/libbz2.a -lpthread + +vcd2vzt: vcd2vzt.c vzt_write.c vzt_write.h v2l_debug_lxt2.c v2l_debug_lxt2.h v2l_analyzer_lxt2.h ../libz/libz.a + $(CC) $(CFLAGS) -o vcd2vzt vcd2vzt.c vzt_write.c v2l_debug_lxt2.c ../libz/libz.a ../libbz2/libbz2.a + +../libz/libz.a: + cd ../libz ; make + +../libbz2/libbz2.a: + cd ../libbz2 ; make + diff --git a/src/helpers/lxt2_read.c b/src/helpers/lxt2_read.c index 845430b..092ccff 100644 --- a/src/helpers/lxt2_read.c +++ b/src/helpers/lxt2_read.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003 Tony Bybell. + * Copyright (c) 2003-2004 Tony Bybell. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -48,7 +48,7 @@ * of a big-endian integer. x86 specific version... */ -#ifdef __i386__ +#if defined(__i386__) || defined(__x86_64__) #define lxt2_rd_get_byte(mm,offset) ((unsigned int)(*((unsigned char *)(mm)+(offset)))) @@ -834,7 +834,7 @@ { int rc; char *m; - long pos, fend; + off_t pos, fend; int t; struct lxt2_rd_block *b; @@ -847,7 +847,7 @@ fread(<->timescale, 1, 1, lt->handle); /* no swap necessary */ fprintf(stderr, LXT2_RDLOAD"%d facilities\n", lt->numfacs); - pos = ftell(lt->handle); + pos = ftello(lt->handle); /* fprintf(stderr, LXT2_RDLOAD"gzip facnames start at pos %d (zsize=%d)\n", pos, lt->zfacnamesize); */ lt->process_mask = calloc(1, lt->numfacs/8+1); @@ -875,7 +875,7 @@ lt->faccache->bufcurr = malloc(lt->longestname+1); lt->faccache->bufprev = malloc(lt->longestname+1); - fseek(lt->handle, pos = pos+lt->zfacnamesize, SEEK_SET); + fseeko(lt->handle, pos = pos+lt->zfacnamesize, SEEK_SET); /* fprintf(stderr, LXT2_RDLOAD"seeking to geometry at %d (0x%08x)\n", pos, pos); */ lt->zhandle = gzdopen(dup(fileno(lt->handle)), "rb"); @@ -910,7 +910,14 @@ lt->lsb[i] = lxt2_rd_get_32(m+i*16, 8); lt->flags[i] = lxt2_rd_get_32(m+i*16, 12); - lt->len[i] = (lt->msb[i] <= lt->lsb[i]) ? (lt->lsb[i] - lt->msb[i] + 1) : (lt->msb[i] - lt->lsb[i] + 1); + if(!(lt->flags[i] & LXT2_RD_SYM_F_INTEGER)) + { + lt->len[i] = (lt->msb[i] <= lt->lsb[i]) ? (lt->lsb[i] - lt->msb[i] + 1) : (lt->msb[i] - lt->lsb[i] + 1); + } + else + { + lt->len[i] = 32; + } lt->value[i] = calloc(lt->len[i] + 1, sizeof(char)); } @@ -931,11 +938,11 @@ for(;;) { - fseek(lt->handle, 0L, SEEK_END); - fend=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + fend=ftello(lt->handle); if(pos>=fend) break; - fseek(lt->handle, pos, SEEK_SET); + fseeko(lt->handle, pos, SEEK_SET); /* fprintf(stderr, LXT2_RDLOAD"seeking to block at %d (0x%08x)\n", pos, pos); */ b=calloc(1, sizeof(struct lxt2_rd_block)); @@ -944,8 +951,8 @@ fread(&b->compressed_siz, 4, 1, lt->handle); b->compressed_siz = lxt2_rd_get_32(&b->compressed_siz,0); fread(&b->start, 8, 1, lt->handle); b->start = lxt2_rd_get_64(&b->start,0); fread(&b->end, 8, 1, lt->handle); b->end = lxt2_rd_get_64(&b->end,0); - pos = ftell(lt->handle); - fseek(lt->handle, pos, SEEK_SET); + pos = ftello(lt->handle); + fseeko(lt->handle, pos, SEEK_SET); /* fprintf(stderr, LXT2_RDLOAD"block gzip start at pos %d (0x%08x)\n", pos, pos); */ if(pos>=fend) { @@ -959,7 +966,7 @@ if((b->uncompressed_siz)&&(b->compressed_siz)&&(b->end)) { /* fprintf(stderr, LXT2_RDLOAD"block [%d] %lld / %lld\n", lt->numblocks, b->start, b->end); */ - fseek(lt->handle, b->compressed_siz, SEEK_CUR); + fseeko(lt->handle, b->compressed_siz, SEEK_CUR); lt->numblocks++; if(lt->block_curr) @@ -1186,7 +1193,7 @@ } else { - return(~0); + return(~((lxtint32_t)0)); } } @@ -1473,16 +1480,16 @@ processed++; - fseek(lt->handle, b->filepos, SEEK_SET); + fseeko(lt->handle, b->filepos, SEEK_SET); gzid[0]=gzid[1]=0; fread(&gzid, 2, 1, lt->handle); - fseek(lt->handle, b->filepos, SEEK_SET); + fseeko(lt->handle, b->filepos, SEEK_SET); if((striped_kill = (gzid[0]!=0x1f)||(gzid[1]!=0x8b))) { lxtint32_t clen, unclen, iter=0; char *pnt; - long fspos = b->filepos; + off_t fspos = b->filepos; int rc; char *zbuff=NULL; @@ -1539,7 +1546,7 @@ else { fspos += clen; - fseek(lt->handle, fspos, SEEK_SET); + fseeko(lt->handle, fspos, SEEK_SET); } } diff --git a/src/helpers/lxt2_read.h b/src/helpers/lxt2_read.h index b947e7a..24aa71a 100644 --- a/src/helpers/lxt2_read.h +++ b/src/helpers/lxt2_read.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003 Tony Bybell. + * Copyright (c) 2003-2004 Tony Bybell. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -28,8 +28,21 @@ #include #include #include + +#ifndef _MSC_VER #include #include +#else +typedef long off_t; +#include +#include +#endif + +#if defined _MSC_VER || defined __MINGW32__ +#define fseeko fseek +#define ftello ftell +#endif + #include #ifdef __GNUC__ @@ -52,30 +65,37 @@ #define LXT2_RD_MAX_BLOCK_MEM_USAGE (64*1024*1024) /* 64MB */ +#ifndef _MSC_VER typedef uint8_t lxtint8_t; typedef uint16_t lxtint16_t; typedef uint32_t lxtint32_t; typedef uint64_t lxtint64_t; - -#ifndef _MSC_VER - #define LXT2_RD_LLD "%lld" - #define LXT2_RD_LLDESC(x) x##LL - #define LXT2_RD_ULLDESC(x) x##ULL -#else - #define LXT2_RD_LLD "%I64d" - #define LXT2_RD_LLDESC(x) x##i64 - #define LXT2_RD_ULLDESC(x) x##i64 +#ifndef __MINGW32__ +#define LXT2_RD_LLD "%lld" +#else +#define LXT2_RD_LLD "%I64d" +#endif +#define LXT2_RD_LLDESC(x) x##LL +#define LXT2_RD_ULLDESC(x) x##ULL +#else +typedef unsigned __int8 lxtint8_t; +typedef unsigned __int16 lxtint16_t; +typedef unsigned __int32 lxtint32_t; +typedef unsigned __int64 lxtint64_t; +#define LXT2_RD_LLD "%I64d" +#define LXT2_RD_LLDESC(x) x##i64 +#define LXT2_RD_ULLDESC(x) x##i64 #endif #if LXT2_RD_GRANULE_SIZE > 32 -typedef unsigned long long granmsk_t; -typedef unsigned int granmsk_smaller_t; +typedef lxtint64_t granmsk_t; +typedef lxtint32_t granmsk_smaller_t; #define LXT2_RD_GRAN_0VAL (LXT2_RD_ULLDESC(0)) #define LXT2_RD_GRAN_1VAL (LXT2_RD_ULLDESC(1)) #define get_fac_msk lxt2_rd_get_64 #define get_fac_msk_smaller lxt2_rd_get_32 #else -typedef unsigned int granmsk_t; +typedef lxtint32_t granmsk_t; #define LXT2_RD_GRAN_0VAL (0) #define LXT2_RD_GRAN_1VAL (1) #define get_fac_msk lxt2_rd_get_32 @@ -130,7 +150,7 @@ LXT2_RD_ENC_BLACKOUT, - LXT2_RD_DICT_START, + LXT2_RD_DICT_START }; @@ -149,7 +169,7 @@ char **string_pointers; /* based inside dict_start */ unsigned int *string_lens; -long filepos; /* where block starts in file if we have to reload */ +off_t filepos; /* where block starts in file if we have to reload */ unsigned short_read_ignore : 1; /* tried to read once and it was corrupt so ignore next time */ unsigned exclude_block : 1; /* user marked this block off to be ignored */ @@ -250,8 +270,8 @@ /* null value_change_callback calls an empty dummy function */ int lxt2_rd_iter_blocks(struct lxt2_rd_trace *lt, - void (*value_change_callback)(struct lxt2_rd_trace **lt, lxtint64_t *time, lxtint32_t *facidx, char **value), - void *user_callback_data_pointer); + void (*value_change_callback)(struct lxt2_rd_trace **lt, lxtint64_t *time, lxtint32_t *facidx, char **value), + void *user_callback_data_pointer); _LXT2_RD_INLINE void * lxt2_rd_get_user_callback_data_pointer(struct lxt2_rd_trace *lt); /* time (un)/restricted read ops */ diff --git a/src/helpers/lxt2_write.c b/src/helpers/lxt2_write.c index 60e8143..af74568 100644 --- a/src/helpers/lxt2_write.c +++ b/src/helpers/lxt2_write.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003 Tony Bybell. + * Copyright (c) 2003-2005 Tony Bybell. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -539,7 +539,7 @@ if((lt)&&(lt->numfacs)) { struct lxt2_wr_symbol *s = lt->symchain; - struct lxt2_wr_symbol **aliascache = calloc(lt->numalias, sizeof(struct lxt2_wr_symbol *)); + struct lxt2_wr_symbol **aliascache = calloc(lt->numalias ? lt->numalias : 1, sizeof(struct lxt2_wr_symbol *)); int aliases_encountered, facs_encountered; lt->sorted_facs = (struct lxt2_wr_symbol **)calloc(lt->numfacs, sizeof(struct lxt2_wr_symbol *)); @@ -645,8 +645,8 @@ lt->zfacname_predec_size = lt->zpackcount; gzflush_buffered(lt, 1); - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); lt->zfacname_size = lt->position - lt->zfacname_size; lt->zhandle = gzdopen(dup(fileno(lt->handle)), "wb9"); @@ -671,11 +671,12 @@ } gzflush_buffered(lt, 1); - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); + lt->break_header_size = lt->position; /* in case we need to emit multiple lxt2s with same header */ lt->zfacgeometry_size = lt->position - lt->facgeometry_offset; - fseek(lt->handle, lt->facname_offset + 12, SEEK_SET); + fseeko(lt->handle, lt->facname_offset + 12, SEEK_SET); lxt2_wr_emit_u32(lt, lt->zfacname_size); /* backpatch sizes... */ lxt2_wr_emit_u32(lt, lt->zfacname_predec_size); lxt2_wr_emit_u32(lt, lt->zfacgeometry_size); @@ -689,19 +690,21 @@ /* - * initialize the trace and get back and lt context + * initialize the trace and get back an lt context */ struct lxt2_wr_trace *lxt2_wr_init(const char *name) { struct lxt2_wr_trace *lt=(struct lxt2_wr_trace *)calloc(1, sizeof(struct lxt2_wr_trace)); -if(!(lt->handle=fopen(name, "wb"))) +if((!name)||(!(lt->handle=fopen(name, "wb")))) { free(lt); lt=NULL; } else { + lt->lxtname = strdup(name); + lxt2_wr_emit_u16(lt, LXT2_WR_HDRID); lxt2_wr_emit_u16(lt, LXT2_WR_VERSION); lxt2_wr_emit_u8 (lt, LXT2_WR_GRANULE_SIZE); /* currently 32 or 64 */ @@ -716,6 +719,18 @@ /* + * setting break size + */ +void lxt2_wr_set_break_size(struct lxt2_wr_trace *lt, off_t siz) +{ +if(lt) + { + lt->break_size = siz; + } +} + + +/* * enable/disable partial dump mode (for faster reads) */ void lxt2_wr_set_partial_off(struct lxt2_wr_trace *lt) @@ -938,6 +953,72 @@ } +/* + * file size limiting/header cloning... + */ +static void lxt2_wr_emit_do_breakfile(struct lxt2_wr_trace *lt) +{ +unsigned int len = strlen(lt->lxtname); +int i; +char *tname = malloc(len + 30); +FILE *f2, *clone; +off_t cnt, seg; +char buf[32768]; + +for(i=len;i>0;i--) + { + if(lt->lxtname[i]=='.') break; + } + +if(!i) + { + sprintf(tname, "%s_%03d.lxt", lt->lxtname, ++lt->break_number); + } + else + { + memcpy(tname, lt->lxtname, i); + sprintf(tname+i, "_%03d.lxt", ++lt->break_number); + } + +f2 = fopen(tname, "wb"); +if(!f2) /* if error, keep writing to same output file...sorry */ + { + free(tname); + return; + } + +clone = fopen(lt->lxtname, "rb"); +if(!clone) + { /* this should never happen */ + fclose(f2); + unlink(tname); + free(tname); + return; + } + +/* clone original header */ +for(cnt = 0; cnt < lt->break_header_size; cnt += sizeof(buf)) + { + seg = lt->break_header_size - cnt; + if(seg > sizeof(buf)) + { + seg = sizeof(buf); + } + + fread(buf, seg, 1, clone); + fwrite(buf, seg, 1, f2); + } + +fclose(clone); +fclose(lt->handle); +lt->handle = f2; +free(tname); +} + + +/* + * emit granule + */ void lxt2_wr_flush_granule(struct lxt2_wr_trace *lt, int do_finalize) { unsigned int idx_nbytes, map_nbytes, i, j; @@ -945,7 +1026,8 @@ unsigned int partial_iter; unsigned int iter, iter_hi; unsigned char using_partial, using_partial_zip=0; -unsigned int current_iter_pos=0; +off_t current_iter_pos=0; +int early_flush; if(lt->flush_valid) { @@ -969,11 +1051,25 @@ partial_iter = lt->numfacs; } - if(!lt->timegranule) { - fseek(lt->handle, 0L, SEEK_END); - lt->current_chunk=lt->position = ftell(lt->handle); + int attempt_break_state = 2; + + do { + fseeko(lt->handle, 0L, SEEK_END); + lt->current_chunk=lt->position = ftello(lt->handle); + + if((lt->break_size)&&(attempt_break_state==2)&&(lt->position >= lt->break_size)&&(lt->position != lt->break_header_size)) + { + lxt2_wr_emit_do_breakfile(lt); + attempt_break_state--; + } + else + { + attempt_break_state = 0; + } + } while(attempt_break_state); + /* fprintf(stderr, "First chunk position is %d (0x%08x)\n", lt->current_chunk, lt->current_chunk); */ lxt2_wr_emit_u32(lt, 0); /* size of this section (uncompressed) */ lxt2_wr_emit_u32(lt, 0); /* size of this section (compressed) */ @@ -1060,8 +1156,8 @@ if(using_partial_zip) { - fseek(lt->handle, 0L, SEEK_END); - current_iter_pos = ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + current_iter_pos = ftello(lt->handle); lxt2_wr_emit_u32(lt, 0); /* size of this section (compressed) */ lxt2_wr_emit_u32(lt, partial_length+9); /* size of this section (uncompressed) */ lxt2_wr_emit_u32(lt, iter); /* begin iter of section */ @@ -1130,14 +1226,14 @@ if(using_partial_zip) { - unsigned int clen; + off_t clen; gzflush_buffered(lt, 1); - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); clen = lt->position - current_iter_pos - 12; - fseek(lt->handle, current_iter_pos, SEEK_SET); + fseeko(lt->handle, current_iter_pos, SEEK_SET); lt->zpackcount_cumulative+=lt->zpackcount; @@ -1152,16 +1248,26 @@ lt->timepos = 0; lt->timegranule++; -if((lt->timegranule>=lt->maxgranule)||(do_finalize)) - { - unsigned int unclen, clen; + +if(lt->break_size) + { + early_flush = (ftello(lt->handle) >= lt->break_size); + } + else + { + early_flush = 0; + } + +if((lt->timegranule>=lt->maxgranule)||(do_finalize)||(early_flush)) + { + off_t unclen, clen; lxt2_wr_ds_Tree *dt, *dt2; lxt2_wr_dslxt_Tree *ds, *ds2; if(using_partial_zip) { - fseek(lt->handle, 0L, SEEK_END); - current_iter_pos = ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + current_iter_pos = ftello(lt->handle); lxt2_wr_emit_u32(lt, 0); /* size of this section (compressed) */ lxt2_wr_emit_u32(lt, 0); /* size of this section (uncompressed) */ lxt2_wr_emit_u32(lt, ~0); /* control section */ @@ -1233,14 +1339,14 @@ if(using_partial_zip) { - unsigned int clen; + off_t clen; gzflush_buffered(lt, 1); - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); clen = lt->position - current_iter_pos - 12; - fseek(lt->handle, current_iter_pos, SEEK_SET); + fseeko(lt->handle, current_iter_pos, SEEK_SET); lt->zpackcount_cumulative+=lt->zpackcount; lxt2_wr_emit_u32(lt, clen); @@ -1251,8 +1357,8 @@ gzflush_buffered(lt, 1); } - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); /* fprintf(stderr, "file position after dumping dict: %d 0x%08x\n", lt->position, lt->position); */ unclen = lt->zpackcount; @@ -1260,7 +1366,7 @@ /* fprintf(stderr, "%d/%d un/compressed bytes in section\n", unclen, clen); */ - fseek(lt->handle, lt->current_chunk, SEEK_SET); + fseeko(lt->handle, lt->current_chunk, SEEK_SET); if(using_partial_zip) { lxt2_wr_emit_u32(lt, lt->zpackcount_cumulative); @@ -1434,7 +1540,7 @@ len--; -for(i=0;isymchain; while(s) { - if((s->msk & (LXT2_WR_GRAN_1VAL<timepos)) == LXT2_WR_GRAN_0VAL) - { - s->msk |= (LXT2_WR_GRAN_1VAL<timepos); - s->chg[s->chgpos] = LXT2_WR_ENC_BLACKOUT; - - s->chgpos++; - } - else - { - s->chg[s->chgpos-1] = LXT2_WR_ENC_BLACKOUT; + if(!(s->flags&LXT2_WR_SYM_F_ALIAS)) + { + if((s->msk & (LXT2_WR_GRAN_1VAL<timepos)) == LXT2_WR_GRAN_0VAL) + { + s->msk |= (LXT2_WR_GRAN_1VAL<timepos); + s->chg[s->chgpos] = LXT2_WR_ENC_BLACKOUT; + + s->chgpos++; + } + else + { + s->chg[s->chgpos-1] = LXT2_WR_ENC_BLACKOUT; + } } s=s->symchain; @@ -1900,26 +2009,29 @@ s = lt->symchain; while(s) { - if(s->flags&LXT2_WR_SYM_F_DOUBLE) - { - free(s->value); - s->value = strdup("0"); /* will cause mismatch then flush */ - } - else - { - if(!(s->flags&LXT2_WR_SYM_F_STRING)) - { - s->value[0] = '-'; /* will cause mismatch then flush */ - for(i=1;ilen;i++) - { - s->value[i] = 'x'; /* initial value */ - } - s->value[i]=0; + if(!(s->flags&LXT2_WR_SYM_F_ALIAS)) + { + if(s->flags&LXT2_WR_SYM_F_DOUBLE) + { + free(s->value); + s->value = strdup("0"); /* will cause mismatch then flush */ } - else - { - free(s->value); - s->value = calloc(1, 1*sizeof(char)); + else + { + if(!(s->flags&LXT2_WR_SYM_F_STRING)) + { + s->value[0] = '-'; /* will cause mismatch then flush */ + for(i=1;ilen;i++) + { + s->value[i] = 'x'; /* initial value */ + } + s->value[i]=0; + } + else + { + free(s->value); + s->value = calloc(1, 1*sizeof(char)); + } } } @@ -2001,6 +2113,7 @@ lt->symchain=NULL; } + free(lt->lxtname); free(lt->sorted_facs); fclose(lt->handle); free(lt); diff --git a/src/helpers/lxt2_write.h b/src/helpers/lxt2_write.h index d375368..91b5d66 100644 --- a/src/helpers/lxt2_write.h +++ b/src/helpers/lxt2_write.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003 Tony Bybell. + * Copyright (c) 2003-2004 Tony Bybell. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -32,6 +32,12 @@ #include #include +#if defined _MSC_VER || defined __MINGW32__ +#define fseeko fseek +#define ftello ftell +#endif + + #define LXT2_WR_HDRID (0x1380) #define LXT2_WR_VERSION (0x0001) @@ -50,7 +56,11 @@ #ifndef _MSC_VER - #define LXT2_WR_LLD "%lld" + #ifdef __MINGW32__ + #define LXT2_WR_LLD "%I64d" + #else + #define LXT2_WR_LLD "%lld" + #endif #define LXT2_WR_LLDESC(x) x##LL #define LXT2_WR_ULLDESC(x) x##ULL #else @@ -94,7 +104,7 @@ LXT2_WR_ENC_BLACKOUT, - LXT2_WR_DICT_START, + LXT2_WR_DICT_START }; /* @@ -137,10 +147,10 @@ lxt2_wr_ds_Tree *mapdict_head; lxt2_wr_ds_Tree *mapdict_curr; -unsigned int position; -unsigned int zfacname_predec_size, zfacname_size, zfacgeometry_size; -unsigned int zpackcount, zpackcount_cumulative; -unsigned int current_chunk, current_chunkz; +off_t position; +off_t zfacname_predec_size, zfacname_size, zfacgeometry_size; +off_t zpackcount, zpackcount_cumulative; +off_t current_chunk, current_chunkz; struct lxt2_wr_symbol *sym[LXT2_WR_SYMPRIME]; struct lxt2_wr_symbol **sorted_facs; @@ -150,7 +160,7 @@ int longestname; int numsections, numblock; -unsigned int facname_offset, facgeometry_offset; +off_t facname_offset, facgeometry_offset; lxttime_t mintime, maxtime; unsigned int timegranule; @@ -184,6 +194,11 @@ char zmode[4]; /* fills in with "wb0".."wb9" */ unsigned int gzbufpnt; unsigned char gzdest[LXT2_WR_GZWRITE_BUFFER + 4]; /* enough for zlib buffering */ + +char *lxtname; +off_t break_size; +off_t break_header_size; +unsigned int break_number; }; @@ -242,6 +257,9 @@ void lxt2_wr_flush(struct lxt2_wr_trace *lt); void lxt2_wr_close(struct lxt2_wr_trace *lt); + /* for dealing with very large traces, split into multiple files approximately "siz" in length */ +void lxt2_wr_set_break_size(struct lxt2_wr_trace *lt, off_t siz); + /* 0 = no compression, 9 = best compression, 4 = default */ void lxt2_wr_set_compression_depth(struct lxt2_wr_trace *lt, unsigned int depth); @@ -261,7 +279,7 @@ struct lxt2_wr_symbol * lxt2_wr_symbol_alias(struct lxt2_wr_trace *lt, const char *existing_name, const char *alias, int msb, int lsb); void lxt2_wr_symbol_bracket_stripping(struct lxt2_wr_trace *lt, int doit); - /* each granule is LXT2_WR_GRANULE_SIZE (32 or 64) timesteps, default is 8 per section */ + /* each granule is LXT2_WR_GRANULE_SIZE (32 or 64) timesteps, default is 256 per section */ void lxt2_wr_set_maxgranule(struct lxt2_wr_trace *lt, unsigned int maxgranule); /* time ops */ diff --git a/src/helpers/lxt2vcd.c b/src/helpers/lxt2vcd.c index 4d60cf9..1f97f77 100644 --- a/src/helpers/lxt2vcd.c +++ b/src/helpers/lxt2vcd.c @@ -21,6 +21,12 @@ */ #include "lxt2_read.h" +#include + +int flat_earth = 0; +extern void free_hier(void); +extern char *output_hier(char *name); + /* * generate a vcd identifier for a given facindx @@ -124,17 +130,12 @@ } -int main(int argc, char **argv) +int process_lxt(char *fname) { struct lxt2_rd_trace *lt; - -if(argc!=2) - { - fprintf(stderr, "usage:\n------\n%s filename\n", argv[0]); - exit(0); - } - -lt=lxt2_rd_init(argv[1]); +char *netname; + +lt=lxt2_rd_init(fname); if(lt) { int i; @@ -181,14 +182,23 @@ struct lxt2_rd_geometry *g = lxt2_rd_get_fac_geometry(lt, i); lxtint32_t newindx = lxt2_rd_get_alias_root(lt, i); + if(!flat_earth) + { + netname = output_hier(lxt2_rd_get_facname(lt, i)); + } + else + { + netname = lxt2_rd_get_facname(lt, i); + } + if(g->flags & LXT2_RD_SYM_F_DOUBLE) { - printf("$var real 1 %s %s $end\n", vcdid(newindx), lxt2_rd_get_facname(lt, i)); + printf("$var real 1 %s %s $end\n", vcdid(newindx), netname); } else if(g->flags & LXT2_RD_SYM_F_STRING) { - printf("$var real 1 %s %s $end\n", vcdid(newindx), lxt2_rd_get_facname(lt, i)); + printf("$var real 1 %s %s $end\n", vcdid(newindx), netname); } else @@ -197,18 +207,24 @@ { if((g->msb!=-1)&&(g->msb!=0)) { - printf("$var wire 1 %s %s[%d] $end\n", vcdid(newindx), lxt2_rd_get_facname(lt, i), g->msb); + printf("$var wire 1 %s %s[%d] $end\n", vcdid(newindx), netname, g->msb); } else { - printf("$var wire 1 %s %s $end\n", vcdid(newindx), lxt2_rd_get_facname(lt, i)); + printf("$var wire 1 %s %s $end\n", vcdid(newindx), netname); } } else { - printf("$var wire %d %s %s[%d:%d] $end\n", g->len, vcdid(newindx), lxt2_rd_get_facname(lt, i), g->msb, g->lsb); + printf("$var wire %d %s %s[%d:%d] $end\n", g->len, vcdid(newindx), netname, g->msb, g->lsb); } } + } + + if(!flat_earth) + { + output_hier(""); /* flush any remaining hierarchy if not back to toplevel */ + free_hier(); } printf("$enddefinitions $end\n"); @@ -228,9 +244,115 @@ else { fprintf(stderr, "lxt2_rd_init failed\n"); - } + return(255); + } + +return(0); +} + +/*******************************************************************************/ + +void print_help(char *nam) +{ +#ifdef __linux__ +printf( +"Usage: %s [OPTION]... [LXT2FILE]\n\n" +" -l, --lxtname=FILE specify LXT2 input filename\n" +" -f, --flatearth emit flattened hierarchies\n" +" -h, --help display this help then exit\n\n" +"VCD is emitted to stdout.\n\n" +"Report bugs to .\n",nam); +#else +printf( +"Usage: %s [OPTION]... [LXT2FILE]\n\n" +" -l specify LXT2 input filename\n" +" -f emit flattened hierarchies\n" +" -h display this help then exit\n\n" + +"VCD is emitted to stdout.\n\n" +"Report bugs to .\n",nam); +#endif exit(0); } -/****************************************************************************/ + +int main(int argc, char **argv) +{ +char opt_errors_encountered=0; +char *lxname=NULL; +int c; +int rc; + +while (1) + { + int option_index = 0; + +#ifdef __linux__ + static struct option long_options[] = + { + {"lxtname", 1, 0, 'l'}, + {"flatearth", 0, 0, 'g'}, + {"help", 0, 0, 'h'}, + {0, 0, 0, 0} + }; + + c = getopt_long (argc, argv, "l:fh", long_options, &option_index); +#else + c = getopt (argc, argv, "l:fh"); +#endif + + if (c == -1) break; /* no more args */ + + switch (c) + { + case 'l': + if(lxname) free(lxname); + lxname = malloc(strlen(optarg)+1); + strcpy(lxname, optarg); + break; + + case 'f': flat_earth=1; + break; + + case 'h': + print_help(argv[0]); + break; + + case '?': + opt_errors_encountered=1; + break; + + default: + /* unreachable */ + break; + } + } + +if(opt_errors_encountered) + { + print_help(argv[0]); + } + +if (optind < argc) + { + while (optind < argc) + { + if(!lxname) + { + lxname = malloc(strlen(argv[optind])+1); + strcpy(lxname, argv[optind++]); + } + } + } + +if(!lxname) + { + print_help(argv[0]); + } + +rc=process_lxt(lxname); +free(lxname); + +return(rc); +} diff --git a/src/helpers/lxt_write.c b/src/helpers/lxt_write.c index 5fec5d7..86b795c 100644 --- a/src/helpers/lxt_write.c +++ b/src/helpers/lxt_write.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001-3 Tony Bybell. + * Copyright (c) 2001-5 Tony Bybell. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -655,8 +655,8 @@ lt->zfacname_predec_size = lt->zpackcount; gzclose(lt->zhandle); - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); lt->zfacname_size = lt->position - lt->zfacname_size; lt->zhandle = gzdopen(dup(fileno(lt->handle)), "wb9"); @@ -681,8 +681,8 @@ } gzclose(lt->zhandle); - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); lt->zfacgeometry_size = lt->position - lt->facgeometry_offset; if(is_interlaced_trace) @@ -696,8 +696,8 @@ } gzclose(lt->zhandle); lt->zhandle = NULL; - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); lt->zsync_table_size = lt->position - lt->sync_table_offset; } } @@ -706,7 +706,7 @@ /* - * initialize the trace and get back and lt context + * initialize the trace and get back an lt context */ struct lt_trace *lt_init(const char *name) { @@ -1002,8 +1002,8 @@ } gzclose(lt->zhandle); -fseek(lt->handle, 0L, SEEK_END); -lt->position=ftell(lt->handle); +fseeko(lt->handle, 0L, SEEK_END); +lt->position=ftello(lt->handle); lt->zdictionary_size = lt->position - lt->zdictionary_size; free(lt->sorted_dict); lt->sorted_dict = NULL; @@ -1057,8 +1057,8 @@ case LT_ZMODE_BZIP2: BZ2_bzclose(lt->zhandle); break; } lt->zhandle = NULL; - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); lt_set_zmode(lt, LT_ZMODE_NONE); lt->zchg_table_size = lt->position - lt->change_field_offset; @@ -1132,8 +1132,8 @@ } gzclose(lt->zhandle); lt->zhandle = NULL; - fseek(lt->handle, 0L, SEEK_END); - lt->position=ftell(lt->handle); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); lt->ztime_table_size = lt->position - lt->ztime_table_size; } @@ -1609,7 +1609,7 @@ len--; -for(i=0;i1)&&(len<=32)) { int ivalue = value; + int delta1, delta2; s->clk_mask <<= 1; s->clk_mask |= 1; if( ((s->clk_mask&0x1f)==0x1f) && - ( ((ivalue - s->clk_prevval1) & lt_optimask[s->len]) == ((s->clk_prevval1 - s->clk_prevval3) & lt_optimask[s->len]) ) && - ( ((s->clk_prevval - s->clk_prevval2) & lt_optimask[s->len]) == ((s->clk_prevval2 - s->clk_prevval4) & lt_optimask[s->len]) ) + ( (delta1=(ivalue - s->clk_prevval1) & lt_optimask[s->len]) == ((s->clk_prevval1 - s->clk_prevval3) & lt_optimask[s->len]) ) && + ( (delta2=(s->clk_prevval - s->clk_prevval2) & lt_optimask[s->len]) == ((s->clk_prevval2 - s->clk_prevval4) & lt_optimask[s->len]) ) && + ( (delta1==delta2) || ((!delta1)&&(!delta2)) ) ) { if(s->clk_prevtrans==ULLDescriptor(~0)) @@ -2249,6 +2251,7 @@ int ivalue = 0; int i; char *pnt = value; + int delta1, delta2; for(i=0;iclk_mask |= legal; if( ((s->clk_mask&0x1f)==0x1f) && - ( ((ivalue - s->clk_prevval1) & lt_optimask[s->len]) == ((s->clk_prevval1 - s->clk_prevval3) & lt_optimask[s->len]) ) && - ( ((s->clk_prevval - s->clk_prevval2) & lt_optimask[s->len]) == ((s->clk_prevval2 - s->clk_prevval4) & lt_optimask[s->len]) ) + ( (delta1=(ivalue - s->clk_prevval1) & lt_optimask[s->len]) == ((s->clk_prevval1 - s->clk_prevval3) & lt_optimask[s->len]) ) && + ( (delta2=(s->clk_prevval - s->clk_prevval2) & lt_optimask[s->len]) == ((s->clk_prevval2 - s->clk_prevval4) & lt_optimask[s->len]) ) && + ( (delta1==delta2) || ((!delta1)&&(!delta2)) ) ) { if(s->clk_prevtrans==ULLDescriptor(~0)) diff --git a/src/helpers/mvl2lxt.c b/src/helpers/mvl2lxt.c index 6d817d4..717a6d7 100644 --- a/src/helpers/mvl2lxt.c +++ b/src/helpers/mvl2lxt.c @@ -139,15 +139,15 @@ * find the most recent valuechange that corresponds with * an arbitrary timevalue. */ -static int max_compare_time_tc, max_compare_pos_tc; +static long max_compare_time_tc, max_compare_pos_tc; static int compar_timechain(const void *s1, const void *s2) { -int key, obj, delta; -int cpos; +long key, obj, delta; +long cpos; int rv; -key=(int)s1; -obj=get_32(cpos=(int)s2); +key=(long)s1; +obj=get_32(cpos=(long)s2); if((obj<=key)&&(obj>max_compare_time_tc)) { @@ -167,7 +167,7 @@ { max_compare_time_tc=-1; max_compare_pos_tc=-1; -bsearch((void *)key, (void *)tableposition, total_cycles, 8, compar_timechain); +bsearch((void *)(long)key, (void *)(long)tableposition, total_cycles, 8, compar_timechain); if((!max_compare_pos_tc)||(max_compare_time_tc<0)) { max_compare_pos_tc=tableposition; /* aix bsearch fix */ diff --git a/src/helpers/mvl2vcd.c b/src/helpers/mvl2vcd.c index 0863e44..569167c 100644 --- a/src/helpers/mvl2vcd.c +++ b/src/helpers/mvl2vcd.c @@ -296,15 +296,15 @@ * find the most recent valuechange that corresponds with * an arbitrary timevalue. */ -static int max_compare_time_tc, max_compare_pos_tc; +static long max_compare_time_tc, max_compare_pos_tc; static int compar_timechain(const void *s1, const void *s2) { -int key, obj, delta; -int cpos; +long key, obj, delta; +long cpos; int rv; -key=(int)s1; -obj=get_32(cpos=(int)s2); +key=(long)s1; +obj=get_32(cpos=(long)s2); if((obj<=key)&&(obj>max_compare_time_tc)) { @@ -324,7 +324,7 @@ { max_compare_time_tc=-1; max_compare_pos_tc=-1; -bsearch((void *)key, (void *)tableposition, total_cycles, 8, compar_timechain); +bsearch((void *)(long)key, (void *)(long)tableposition, total_cycles, 8, compar_timechain); if((!max_compare_pos_tc)||(max_compare_time_tc<0)) { max_compare_pos_tc=tableposition; /* aix bsearch fix */ diff --git a/src/helpers/mvlsimaet.html b/src/helpers/mvlsimaet.html index dafbf4c..a79ce73 100644 --- a/src/helpers/mvlsimaet.html +++ b/src/helpers/mvlsimaet.html @@ -310,7 +310,7 @@
    02jun01 -bybell@linux-workshop.com / +bybell@nc.rr.com / bybell@xxedgexx.com
    diff --git a/src/helpers/scopenav.c b/src/helpers/scopenav.c new file mode 100644 index 0000000..dd6967a --- /dev/null +++ b/src/helpers/scopenav.c @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2004 Tony Bybell. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include +#include + +struct namehier +{ +struct namehier *next; +char *name; +char not_final; +}; + +static struct namehier *nhold=NULL; + + +void free_hier(void) +{ +struct namehier *nhtemp; + +while(nhold) + { + nhtemp=nhold->next; + free(nhold->name); + free(nhold); + nhold=nhtemp; + } +} + +/* + * navigate up and down the scope hierarchy and + * emit the appropriate vcd scope primitives + */ +static void diff_hier(struct namehier *nh1, struct namehier *nh2) +{ +struct namehier *nhtemp; + +if(!nh2) + { + while((nh1)&&(nh1->not_final)) + { + printf("$scope module %s $end\n", nh1->name); + nh1=nh1->next; + } + return; + } + +for(;;) + { + if((nh1->not_final==0)&&(nh2->not_final==0)) /* both are equal */ + { + break; + } + + if(nh2->not_final==0) /* old hier is shorter */ + { + nhtemp=nh1; + while((nh1)&&(nh1->not_final)) + { + printf("$scope module %s $end\n", nh1->name); + nh1=nh1->next; + } + break; + } + + if(nh1->not_final==0) /* new hier is shorter */ + { + nhtemp=nh2; + while((nh2)&&(nh2->not_final)) + { + printf("$upscope $end\n"); + nh2=nh2->next; + } + break; + } + + if(strcmp(nh1->name, nh2->name)) + { + nhtemp=nh2; /* prune old hier */ + while((nh2)&&(nh2->not_final)) + { + printf("$upscope $end\n"); + nh2=nh2->next; + } + + nhtemp=nh1; /* add new hier */ + while((nh1)&&(nh1->not_final)) + { + printf("$scope module %s $end\n", nh1->name); + nh1=nh1->next; + } + break; + } + + nh1=nh1->next; + nh2=nh2->next; + } +} + + +/* + * output scopedata for a given name if needed, return pointer to name string + */ +char *output_hier(char *name) +{ +char *pnt, *pnt2; +char *s; +int len; +struct namehier *nh_head=NULL, *nh_curr=NULL, *nhtemp; + +pnt=pnt2=name; + +for(;;) +{ +while((*pnt2!='.')&&(*pnt2)) pnt2++; +s=(char *)calloc(1,(len=pnt2-pnt)+1); +memcpy(s, pnt, len); +nhtemp=(struct namehier *)calloc(1,sizeof(struct namehier)); +nhtemp->name=s; + +if(!nh_curr) + { + nh_head=nh_curr=nhtemp; + } + else + { + nh_curr->next=nhtemp; + nh_curr->not_final=1; + nh_curr=nhtemp; + } + +if(!*pnt2) break; +pnt=(++pnt2); +} + +diff_hier(nh_head, nhold); +free_hier(); +nhold=nh_head; + +return(nh_curr->name); +} diff --git a/src/helpers/v2l_analyzer_lxt2.h b/src/helpers/v2l_analyzer_lxt2.h index 6daf0c3..a2ecc07 100644 --- a/src/helpers/v2l_analyzer_lxt2.h +++ b/src/helpers/v2l_analyzer_lxt2.h @@ -31,8 +31,8 @@ #include #include #include +#include #include "v2l_debug_lxt2.h" -#include "lxt2_write.h" #ifndef _MSC_VER #include @@ -110,7 +110,7 @@ struct vcdsymbol { struct vcdsymbol *next; -struct lxt2_wr_symbol *ltsym; +void *ltsym; char *name; char *id; unsigned int nid; diff --git a/src/helpers/vcd2lxt.c b/src/helpers/vcd2lxt.c index 5cdf755..cc71dc3 100644 --- a/src/helpers/vcd2lxt.c +++ b/src/helpers/vcd2lxt.c @@ -219,6 +219,55 @@ return(strcmp(v1->id, v2->id)); } +/* + * alias vs normal symbol adding + */ +static void alias_vs_normal_symadd(struct vcdsymbol *v, struct vcdsymbol *root_v) +{ +if(!root_v) + { + if((v->vartype==V_INTEGER)||(v->vartype==V_REAL)) + { + v->ltsym = lt_symbol_add(lt, v->name, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?LT_SYM_F_INTEGER:((v->vartype==V_REAL)?LT_SYM_F_DOUBLE:LT_SYM_F_BITS)); + } + else + { + char buf[65537]; + if(v->msi==v->lsi) + { + sprintf(buf, "%s[%d]", v->name, v->msi); + } + else + { + sprintf(buf, "%s[%d:%d]", v->name, v->msi, v->lsi); + } + v->ltsym = lt_symbol_add(lt, buf, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?LT_SYM_F_INTEGER:((v->vartype==V_REAL)?LT_SYM_F_DOUBLE:LT_SYM_F_BITS)); + } + } + else + { + if((v->vartype==V_INTEGER)||(v->vartype==V_REAL)) + { + lt_symbol_alias(lt, root_v->name, v->name, v->msi, v->lsi); + } + else + { + char bufold[65537], buf[65537]; + if(v->msi==v->lsi) + { + sprintf(bufold, "%s[%d]", root_v->name, root_v->msi); + sprintf(buf, "%s[%d]", v->name, v->msi); + } + else + { + sprintf(bufold, "%s[%d:%d]", root_v->name, root_v->msi, root_v->lsi); + sprintf(buf, "%s[%d:%d]", v->name, v->msi, v->lsi); + } + lt_symbol_alias(lt, bufold, buf, v->msi, v->lsi); + } + } +} + /* * create sorted (by id) table @@ -228,37 +277,51 @@ struct vcdsymbol *v; struct vcdsymbol **pnt; unsigned int vcd_distance; - +struct vcdsymbol *root_v; +int i; + if(numsyms) - { - vcd_distance = vcd_maxid - vcd_minid + 1; - - if(vcd_distance <= 2 * 1024 * 1024) - { - indexed = (struct vcdsymbol **)calloc_2(vcd_distance, sizeof(struct vcdsymbol *)); - - printf("%d symbols span ID range of %d, using indexing...\n", numsyms, vcd_distance); - - v=vcdsymroot; - while(v) - { - if(!indexed[v->nid - vcd_minid]) indexed[v->nid - vcd_minid] = v; - v=v->next; - } - } - else - { - pnt=sorted=(struct vcdsymbol **)calloc_2(numsyms, sizeof(struct vcdsymbol *)); - v=vcdsymroot; - while(v) - { - *(pnt++)=v; - v=v->next; - } - - qsort(sorted, numsyms, sizeof(struct vcdsymbol *), vcdsymcompare); - } - } + { + vcd_distance = vcd_maxid - vcd_minid + 1; + + if(vcd_distance <= 4 * 1024 * 1024) + { + indexed = (struct vcdsymbol **)calloc_2(vcd_distance, sizeof(struct vcdsymbol *)); + + printf("%d symbols span ID range of %d, using indexing...\n", numsyms, vcd_distance); + + v=vcdsymroot; + while(v) + { + if(!(root_v=indexed[v->nid - vcd_minid])) + { + indexed[v->nid - vcd_minid] = v; + } + alias_vs_normal_symadd(v, root_v); + + v=v->next; + } + } + else + { + pnt=sorted=(struct vcdsymbol **)calloc_2(numsyms, sizeof(struct vcdsymbol *)); + v=vcdsymroot; + while(v) + { + *(pnt++)=v; + v=v->next; + } + + qsort(sorted, numsyms, sizeof(struct vcdsymbol *), vcdsymcompare); + + root_v = NULL; + for(i=0;ivartype==V_INTEGER)||(v->vartype==V_REAL)) { v->ltsym = lt_symbol_add(lt, v->name, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?LT_SYM_F_INTEGER:((v->vartype==V_REAL)?LT_SYM_F_DOUBLE:LT_SYM_F_BITS)); @@ -1221,6 +1285,7 @@ } v->ltsym = lt_symbol_add(lt, buf, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?LT_SYM_F_INTEGER:((v->vartype==V_REAL)?LT_SYM_F_DOUBLE:LT_SYM_F_BITS)); } +#endif DEBUG(fprintf(stderr,"VAR %s %d %s %s[%d:%d]\n", vartypes[v->vartype], v->size, v->id, v->name, diff --git a/src/helpers/vcd2lxt2.c b/src/helpers/vcd2lxt2.c index 46aa175..175092b 100644 --- a/src/helpers/vcd2lxt2.c +++ b/src/helpers/vcd2lxt2.c @@ -30,6 +30,7 @@ */ #include "v2l_analyzer_lxt2.h" +#include "lxt2_write.h" #undef VCD_BSEARCH_IS_PERFECT /* bsearch is imperfect under linux, but OK under AIX */ @@ -37,6 +38,12 @@ int numfacs=0; int deadcnt=0; + +int opt_depth = 4; +unsigned long long opt_break_size = 0; +int opt_partial_mode = -1; +int opt_checkpoint_disable = 0; +int opt_maxgranule = 8; struct symbol **sym=NULL; struct symbol **facs=NULL; @@ -1533,10 +1540,19 @@ exit(255); } -/* lxt2_wr_set_partial_on(lt, 1); */ -/* lxt2_wr_set_checkpoint_off(lt); */ -lxt2_wr_set_compression_depth(lt, 9); - +if(opt_partial_mode>=0) + { + lxt2_wr_set_partial_on(lt, opt_partial_mode); + } + +if((opt_checkpoint_disable)&&(!opt_break_size)) + { + lxt2_wr_set_checkpoint_off(lt); + } + +lxt2_wr_set_compression_depth(lt, opt_depth); +lxt2_wr_set_break_size(lt, (off_t)opt_break_size); +lxt2_wr_set_maxgranule(lt, opt_maxgranule); lxt2_wr_symbol_bracket_stripping(lt, 1); /* this is intentional */ sym=(struct symbol **)calloc_2(SYMPRIME,sizeof(struct symbol *)); @@ -1765,17 +1781,160 @@ /*******************************************************************************/ +void print_help(char *nam) +{ +#ifdef __linux__ +printf( +"Usage: %s [OPTION]... [VCDFILE] [LXT2FILE]\n\n" +" -v, --vcdname=FILE specify VCD input filename\n" +" -l, --lxtname=FILE specify LXT2 output filename\n" +" -d, --depth=value specify 0..9 compression depth (default = 4)\n" +" -m, --maxgranule=value specify number of granules per section (def = 8)\n" +" -b, --break=value specify break size (default = 0 = off)\n" +" -p, --partialmode=mode specify partial zip mode 0=monolithic/1=separate\n" +" -c, --checkpoint=mode specify checkpoint mode (0 = on [def], 1 = off)\n" +" -h, --help display this help then exit\n\n" + +"VCD files may be compressed with zip or gzip. Note that VCDFILE and LXTFILE\n" +"are optional provided the --vcdname and --lxtname options are specified.\n" +"Use \"-\" as a VCD filename to accept uncompressed input from stdin.\n\n" +"Report bugs to .\n",nam); +#else +printf( +"Usage: %s [OPTION]... [VCDFILE] [LXT2FILE]\n\n" +" -v FILE specify VCD input filename\n" +" -l FILE specify LXT2 output filename\n" +" -d value specify 0..9 compression depth (default = 4)\n" +" -m value specify number of granules per section (def = 8)\n" +" -b value specify break size (default = 0 = off)\n" +" -p mode specify partial zip mode 0=monolithic/1=separate\n" +" -c mode specify checkpoint mode (0 = on [def], 1 = off)\n" +" -h display this help then exit\n\n" + +"VCD files may be compressed with zip or gzip. Note that VCDFILE and LXTFILE\n" +"are optional provided the --vcdname and --lxtname options are specified.\n" +"Use \"-\" as a VCD filename to accept uncompressed input from stdin.\n\n" +"Report bugs to .\n",nam); +#endif + +exit(0); +} + + int main(int argc, char **argv) { -if(argc==3) - { - vcd_main(argv[1], argv[2]); - } - else - { - printf("Usage:\n------\n%s filename.vcd[.gz] filename.lxt\n" - "Use \"-\" as a filename to accept uncompressed input from stdin.\n",argv[0]); - } +char opt_errors_encountered=0; +char *vname=NULL, *lxname=NULL; +int c; + +while (1) + { + int option_index = 0; + +#ifdef __linux__ + static struct option long_options[] = + { + {"vcdname", 1, 0, 'v'}, + {"lxtname", 1, 0, 'l'}, + {"depth", 1, 0, 'd'}, + {"maxgranule", 1, 0, 'm'}, + {"break", 1, 0, 'b'}, + {"partialmode", 1, 0, 'p'}, + {"checkpoint", 1, 0, 'c'}, + {"help", 0, 0, 'h'}, + {0, 0, 0, 0} + }; + + c = getopt_long (argc, argv, "v:l:d:m:b:p:c:h", long_options, &option_index); +#else + c = getopt (argc, argv, "v:l:d:m:b:p:c:h"); +#endif + + if (c == -1) break; /* no more args */ + + switch (c) + { + case 'v': + if(vname) free(vname); + vname = malloc_2(strlen(optarg)+1); + strcpy(vname, optarg); + break; + + case 'l': + if(lxname) free(lxname); + lxname = malloc_2(strlen(optarg)+1); + strcpy(lxname, optarg); + break; + + case 'd': + opt_depth = atoi(optarg); + if(opt_depth<0) opt_depth = 0; + if(opt_depth>9) opt_depth = 9; + break; + + case 'm': + opt_maxgranule = atoi(optarg); + if(opt_maxgranule<1) opt_maxgranule=1; + break; + + case 'b': + sscanf(optarg, "%lld", &opt_break_size); + break; + + case 'p': + opt_partial_mode = atoi(optarg); + if(opt_depth<0) opt_partial_mode = 0; + if(opt_depth>1) opt_partial_mode = 1; + break; + + case 'c': + opt_checkpoint_disable = atoi(optarg); + break; + + case 'h': + print_help(argv[0]); + break; + + case '?': + opt_errors_encountered=1; + break; + + default: + /* unreachable */ + break; + } + } + +if(opt_errors_encountered) + { + print_help(argv[0]); + } + +if (optind < argc) + { + while (optind < argc) + { + if(!vname) + { + vname = malloc_2(strlen(argv[optind])+1); + strcpy(vname, argv[optind++]); + } + else if(!lxname) + { + lxname = malloc_2(strlen(argv[optind])+1); + strcpy(lxname, argv[optind++]); + } + } + } + +if((!vname)||(!lxname)) + { + print_help(argv[0]); + } + +vcd_main(vname, lxname); + +free(vname); free(lxname); return(0); } diff --git a/src/helpers/vcd2vzt.c b/src/helpers/vcd2vzt.c new file mode 100644 index 0000000..dc3323b --- /dev/null +++ b/src/helpers/vcd2vzt.c @@ -0,0 +1,1944 @@ +/* + * Copyright (c) 1999-2005 Tony Bybell. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/* + * vcd.c 23jan99ajb + * evcd parts 29jun99ajb + * profiler optimizations 15jul99ajb + * stripped out of gtkwave 21jul99ajb + * fix for duplicate nets 19dec00ajb + * lxt conversion added 20nov01ajb + */ + +#include "v2l_analyzer_lxt2.h" +#include "vzt_write.h" + +#undef VCD_BSEARCH_IS_PERFECT /* bsearch is imperfect under linux, but OK under AIX */ + +struct vzt_wr_trace *lt=NULL; + +int numfacs=0; +int deadcnt=0; +int ziptype=0; + +int opt_depth = 4; +unsigned long long opt_break_size = 0; +int opt_maxgranule = 8; +int opt_twostate = 0; +int opt_rle = 0; + +struct symbol **sym=NULL; +struct symbol **facs=NULL; +struct symbol *firstnode=NULL; +struct symbol *curnode=NULL; +TimeType min_time=-1, max_time=-1; +char hier_delimeter='.'; +char deadchar='X'; + +int vcd_explicit_zero_subscripts=-1; /* 0=yes, -1=no */ +char atomic_vectors=1; + +static FILE *vcd_handle=NULL; +static char vcd_is_compressed=0; + +static void add_histent(TimeType time, struct Node *n, char ch, int regadd, char *vector); +static void add_tail_histents(void); +static void evcd_strcpy(char *dst, char *src); + +static int vcdlineno=1; +static int header_over=0; +static int dumping_off=0; +static TimeType start_time=-1; +static TimeType end_time=-1; +static TimeType current_time=-1; +static TimeType time_scale=1; /* multiplier is 1, 10, 100 */ + +static char vcd_hier_delimeter[2]={0, 0}; /* fill in after rc reading code */ + +/******************************************************************/ + +static struct slist *slistroot=NULL, *slistcurr=NULL; +static char *slisthier=NULL; +static int slisthier_len=0; + +/******************************************************************/ + +enum Tokens { T_VAR, T_END, T_SCOPE, T_UPSCOPE, + T_COMMENT, T_DATE, T_DUMPALL, T_DUMPOFF, T_DUMPON, + T_DUMPVARS, T_ENDDEFINITIONS, + T_DUMPPORTS, T_DUMPPORTSOFF, T_DUMPPORTSON, T_DUMPPORTSALL, + T_TIMESCALE, T_VERSION, + T_EOF, T_STRING, T_UNKNOWN_KEY }; + +char *tokens[]={ "var", "end", "scope", "upscope", + "comment", "date", "dumpall", "dumpoff", "dumpon", + "dumpvars", "enddefinitions", + "dumpports", "dumpportsoff", "dumpportson", "dumpportsall", + "timescale", "version", + "", "", "" }; + +#define NUM_TOKENS 17 + +static int T_MAX_STR=1024; /* was originally a const..now it reallocs */ +static char *yytext=NULL; +static int yylen=0, yylen_cache=0; + +#define T_GET tok=get_token();if((tok==T_END)||(tok==T_EOF))break; + +/******************************************************************/ + +static struct vcdsymbol *vcdsymroot=NULL, *vcdsymcurr=NULL; +static struct vcdsymbol **sorted=NULL; +static struct vcdsymbol **indexed=NULL; + +enum VarTypes { V_EVENT, V_PARAMETER, + V_INTEGER, V_REAL, V_REG, V_SUPPLY0, + V_SUPPLY1, V_TIME, V_TRI, V_TRIAND, V_TRIOR, + V_TRIREG, V_TRI0, V_TRI1, V_WAND, V_WIRE, V_WOR, V_PORT, + V_END, V_LB, V_COLON, V_RB, V_STRING }; + +char *vartypes[]={ "event", "parameter", + "integer", "real", "reg", "supply0", + "supply1", "time", "tri", "triand", "trior", + "trireg", "tri0", "tri1", "wand", "wire", "wor", "port", + "$end", "", "", "", ""}; + +#define NUM_VTOKENS 19 + +static int numsyms=0; + +/******************************************************************/ + +static struct queuedevent *queuedevents=NULL; + +/******************************************************************/ + +static unsigned int vcd_minid = ~0; +static unsigned int vcd_maxid = 0; + +static unsigned int vcdid_hash(char *s, int len) +{ +unsigned int val=0; +int i; + +s+=(len-1); + +for(i=0;iid)); +} + + +/* + * actual bsearch + */ +static struct vcdsymbol *bsearch_vcd(char *key, int len) +{ +struct vcdsymbol **v; +struct vcdsymbol *t; + +if(indexed) + { + unsigned int hsh = vcdid_hash(key, len); + if((hsh>=vcd_minid)&&(hsh<=vcd_maxid)) + { + return(indexed[hsh-vcd_minid]); + } + } + +v=(struct vcdsymbol **)bsearch(key, sorted, numsyms, + sizeof(struct vcdsymbol *), vcdsymbsearchcompare); + +if(v) + { +#ifndef VCD_BSEARCH_IS_PERFECT + for(;;) + { + t=*v; + + if((v==sorted)||(strcmp((*(--v))->id, key))) + { + return(t); + } + } +#else + return(*v); +#endif + } + else + { + return(NULL); + } +} + + +/* + * sort on vcdsymbol pointers + */ +static int vcdsymcompare(const void *s1, const void *s2) +{ +struct vcdsymbol *v1, *v2; + +v1=*((struct vcdsymbol **)s1); +v2=*((struct vcdsymbol **)s2); + +return(strcmp(v1->id, v2->id)); +} + +/* + * alias vs normal symbol adding + */ +static void alias_vs_normal_symadd(struct vcdsymbol *v, struct vcdsymbol *root_v) +{ +if(!root_v) + { + if((v->vartype==V_INTEGER)||(v->vartype==V_REAL)) + { + v->ltsym = vzt_wr_symbol_add(lt, v->name, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?VZT_WR_SYM_F_INTEGER:((v->vartype==V_REAL)?VZT_WR_SYM_F_DOUBLE:VZT_WR_SYM_F_BITS)); + } + else + { + char buf[65537]; + if(v->msi==v->lsi) + { + sprintf(buf, "%s[%d]", v->name, v->msi); + } + else + { + sprintf(buf, "%s[%d:%d]", v->name, v->msi, v->lsi); + } + v->ltsym = vzt_wr_symbol_add(lt, buf, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?VZT_WR_SYM_F_INTEGER:((v->vartype==V_REAL)?VZT_WR_SYM_F_DOUBLE:VZT_WR_SYM_F_BITS)); + } + } + else + { + if((v->vartype==V_INTEGER)||(v->vartype==V_REAL)) + { + vzt_wr_symbol_alias(lt, root_v->name, v->name, v->msi, v->lsi); + } + else + { + char bufold[65537], buf[65537]; + if(v->msi==v->lsi) + { + sprintf(bufold, "%s[%d]", root_v->name, root_v->msi); + sprintf(buf, "%s[%d]", v->name, v->msi); + } + else + { + sprintf(bufold, "%s[%d:%d]", root_v->name, root_v->msi, root_v->lsi); + sprintf(buf, "%s[%d:%d]", v->name, v->msi, v->lsi); + } + vzt_wr_symbol_alias(lt, bufold, buf, v->msi, v->lsi); + } + } +} + +/* + * create sorted (by id) table + */ +static void create_sorted_table(void) +{ +struct vcdsymbol *v; +struct vcdsymbol **pnt; +unsigned int vcd_distance; +struct vcdsymbol *root_v; +int i; + +if(numsyms) + { + vcd_distance = vcd_maxid - vcd_minid + 1; + + if(vcd_distance <= 4 * 1024 * 1024) + { + indexed = (struct vcdsymbol **)calloc_2(vcd_distance, sizeof(struct vcdsymbol *)); + + printf("%d symbols span ID range of %d, using indexing...\n", numsyms, vcd_distance); + + v=vcdsymroot; + while(v) + { + if(!(root_v=indexed[v->nid - vcd_minid])) + { + indexed[v->nid - vcd_minid] = v; + } + alias_vs_normal_symadd(v, root_v); + + v=v->next; + } + } + else + { + pnt=sorted=(struct vcdsymbol **)calloc_2(numsyms, sizeof(struct vcdsymbol *)); + v=vcdsymroot; + while(v) + { + *(pnt++)=v; + v=v->next; + } + + qsort(sorted, numsyms, sizeof(struct vcdsymbol *), vcdsymcompare); + + root_v = NULL; + for(i=0;ilen+(s->next?1:0); + s=s->next; + } + +if(slisthier) + { + free_2(slisthier); + } + +slisthier=(char *)malloc_2((slisthier_len=len)+1); +s=slistroot; len=0; +while(s) + { + strcpy(slisthier+len,s->str); + len+=s->len; + if(s->next) + { + strcpy(slisthier+len,vcd_hier_delimeter); + len++; + } + s=s->next; + } +return(slisthier); +} + + +void append_vcd_slisthier(char *str) +{ +struct slist *s; +s=(struct slist *)calloc_2(1,sizeof(struct slist)); +s->len=strlen(str); +s->str=(char *)malloc_2(s->len+1); +strcpy(s->str,str); + +if(slistcurr) + { + slistcurr->next=s; + slistcurr=s; + } + else + { + slistcurr=slistroot=s; + } + +build_slisthier(); +DEBUG(fprintf(stderr, "SCOPE: %s\n",slisthier)); +} + + +static void parse_valuechange(void) +{ +struct vcdsymbol *v; +char *vector; +int vlen; + +switch(yytext[0]) + { + case '0': + case '1': + case 'x': + case 'X': + case 'z': + case 'Z': + if(yylen>1) + { + v=bsearch_vcd(yytext+1, yylen-1); + if(!v) + { + fprintf(stderr,"Near line %d, Unknown VCD identifier: '%s'\n",vcdlineno,yytext+1); + } + else + { + if(v->vartype!=V_EVENT) + { + char vl[2]; + vl[0]=yytext[0]; vl[1]=0; + vzt_wr_emit_value_bit_string(lt, v->ltsym, 0, vl); + + v->value[0]=yytext[0]; + DEBUG(fprintf(stderr,"%s = '%c'\n",v->name,v->value[0])); + add_histent(current_time,v->narray[0],v->value[0],1, NULL); + } + else + { + char vl[2]; + + v->value[0]=(dumping_off)?'x':'1'; /* only '1' is relevant */ + if(current_time!=(v->ev->last_event_time+1)) + { + /* dump degating event */ + DEBUG(fprintf(stderr,"#"TTFormat" %s = '%c' (event)\n",v->ev->last_event_time+1,v->name,'0')); + add_histent(v->ev->last_event_time+1,v->narray[0],'0',1, NULL); + } + DEBUG(fprintf(stderr,"%s = '%c' (event)\n",v->name,v->value[0])); + add_histent(current_time,v->narray[0],v->value[0],1, NULL); + + vl[0]='1'; vl[1]=0; + vzt_wr_emit_value_bit_string(lt, v->ltsym, 0, vl); + vl[0]='0'; vl[1]=0; + vzt_wr_emit_value_bit_string(lt, v->ltsym, 0, vl); + + v->ev->last_event_time=current_time; + } + } + } + else + { + fprintf(stderr,"Near line %d, Malformed VCD identifier\n", vcdlineno); + } + break; + + case 'b': + case 'B': + /* extract binary number then.. */ + vector=malloc_2(yylen_cache=yylen); + strcpy(vector,yytext+1); + vlen=yylen-1; + + get_strtoken(); + v=bsearch_vcd(yytext, yylen); + if(!v) + { + fprintf(stderr,"Near line %d, Unknown identifier: '%s'\n",vcdlineno, yytext); + free_2(vector); + } + else + { + if(vlensize) /* fill in left part */ + { + char extend; + int i, fill; + + extend=(vector[0]=='1')?'0':vector[0]; + + fill=v->size-vlen; + for(i=0;ivalue[i]=extend; + } + strcpy(v->value+fill,vector); + } + else if(vlen==v->size) /* straight copy */ + { + strcpy(v->value,vector); + } + else /* too big, so copy only right half */ + { + int skip; + + skip=vlen-v->size; + strcpy(v->value,vector+skip); + } + DEBUG(fprintf(stderr,"%s = '%s'\n",v->name, v->value)); + vzt_wr_emit_value_bit_string(lt, v->ltsym, 0, v->value); + + if((v->size==1)||(!atomic_vectors)) + { + int i; + for(i=0;isize;i++) + { + add_histent(current_time, v->narray[i],v->value[i],1, NULL); + } + free_2(vector); + } + else + { + if(yylen_cache!=(v->size+1)) + { + free_2(vector); + vector=malloc_2(v->size+1); + } + strcpy(vector,v->value); + add_histent(current_time, v->narray[0],0,1,vector); + free_2(vector); + } + + } + + break; + + + case 'p': + /* extract port dump value.. */ + vector=malloc_2(yylen_cache=yylen); + strcpy(vector,yytext+1); + vlen=yylen-1; + + get_strtoken(); /* throw away 0_strength_component */ + get_strtoken(); /* throw away 0_strength_component */ + get_strtoken(); /* this is the id */ + v=bsearch_vcd(yytext, yylen); + if(!v) + { + fprintf(stderr,"Near line %d, Unknown identifier: '%s'\n",vcdlineno, yytext); + free_2(vector); + } + else + { + if(vlensize) /* fill in left part */ + { + char extend; + int i, fill; + + extend='0'; + + fill=v->size-vlen; + for(i=0;ivalue[i]=extend; + } + evcd_strcpy(v->value+fill,vector); + } + else if(vlen==v->size) /* straight copy */ + { + evcd_strcpy(v->value,vector); + } + else /* too big, so copy only right half */ + { + int skip; + + skip=vlen-v->size; + evcd_strcpy(v->value,vector+skip); + } + DEBUG(fprintf(stderr,"%s = '%s'\n",v->name, v->value)); + vzt_wr_emit_value_bit_string(lt, v->ltsym, 0, v->value); + + if((v->size==1)||(!atomic_vectors)) + { + int i; + for(i=0;isize;i++) + { + add_histent(current_time, v->narray[i],v->value[i],1, NULL); + } + free_2(vector); + } + else + { + if(yylen_cachesize) + { + free_2(vector); + vector=malloc_2(v->size+1); + } + strcpy(vector,v->value); + add_histent(current_time, v->narray[0],0,1,vector); + free_2(vector); + } + } + break; + + + case 'r': + case 'R': + { + double *d; + + d=malloc_2(sizeof(double)); + sscanf(yytext+1,"%lg",d); + + get_strtoken(); + v=bsearch_vcd(yytext, yylen); + if(!v) + { + fprintf(stderr,"Near line %d, Unknown identifier: '%s'\n",vcdlineno, yytext); + free_2(d); + } + else + { + vzt_wr_emit_value_double(lt, v->ltsym, 0, *d); + add_histent(current_time, v->narray[0],'g',1,(char *)d); + free_2(d); + } + + break; + } + + case 's': + case 'S': + { + get_strtoken(); /* simply skip for now */ + break; + } + } + +} + + +static void evcd_strcpy(char *dst, char *src) +{ +static char *evcd="DUNZduLHXTlh01?FAaBbCcf"; +static char *vcd="01xz0101xz0101xzxxxxxxx"; + +char ch; +int i; + +while((ch=*src)) + { + for(i=0;i<23;i++) + { + if(evcd[i]==ch) + { + *dst=vcd[i]; + break; + } + } + if(i==23) *dst='x'; + + src++; + dst++; + } + +*dst=0; /* null terminate destination */ +} + + +static void vcd_parse(void) +{ +int tok; + +for(;;) + { + switch(tok=get_token()) + { + case T_COMMENT: + sync_end("COMMENT:"); + break; + case T_DATE: + sync_end("DATE:"); + break; + case T_VERSION: + sync_end("VERSION:"); + break; + case T_TIMESCALE: + { + int vtok; + int i; + char prefix=' '; + int timelogadjust = 0; + + vtok=get_token(); + if((vtok==T_END)||(vtok==T_EOF)) break; + time_scale=atoi_64(yytext); + if(!time_scale) time_scale=1; + switch(time_scale) + { + case 10: timelogadjust = +1; break; + case 100: timelogadjust = +2; break; + } + + for(i=0;i'9')) + { + prefix=yytext[i]; + break; + } + } + if(prefix==' ') + { + vtok=get_token(); + if((vtok==T_END)||(vtok==T_EOF)) break; + prefix=yytext[0]; + } + switch(prefix) + { + case 's': + case ' ': vzt_wr_set_timescale(lt, 0+timelogadjust); break; + case 'm': vzt_wr_set_timescale(lt, -3+timelogadjust); break; + case 'u': vzt_wr_set_timescale(lt, -6+timelogadjust); break; + case 'n': vzt_wr_set_timescale(lt, -9+timelogadjust); break; + case 'p': vzt_wr_set_timescale(lt, -12+timelogadjust); break; + case 'f': vzt_wr_set_timescale(lt, -15+timelogadjust); break; + default: /* unknown */ + vzt_wr_set_timescale(lt, -9+timelogadjust); break; + } + + sync_end(NULL); + } + break; + case T_SCOPE: + T_GET; + T_GET; + if(tok==T_STRING) + { + struct slist *s; + s=(struct slist *)calloc_2(1,sizeof(struct slist)); + s->len=yylen; + s->str=(char *)malloc_2(yylen+1); + strcpy(s->str,yytext); + + if(slistcurr) + { + slistcurr->next=s; + slistcurr=s; + } + else + { + slistcurr=slistroot=s; + } + + build_slisthier(); + DEBUG(fprintf(stderr, "SCOPE: %s\n",slisthier)); + } + sync_end(NULL); + break; + case T_UPSCOPE: + if(slistroot) + { + struct slist *s; + + s=slistroot; + if(!s->next) + { + free_2(s->str); + free_2(s); + slistroot=slistcurr=NULL; + } + else + for(;;) + { + if(!s->next->next) + { + free_2(s->next->str); + free_2(s->next); + s->next=NULL; + slistcurr=s; + break; + } + s=s->next; + } + build_slisthier(); + DEBUG(fprintf(stderr, "SCOPE: %s\n",slisthier)); + } + sync_end(NULL); + break; + case T_VAR: + { + int vtok; + struct vcdsymbol *v=NULL; + + var_prevch=0; + varsplit=NULL; + vtok=get_vartoken(); + if(vtok>V_PORT) goto bail; + + v=(struct vcdsymbol *)calloc_2(1,sizeof(struct vcdsymbol)); + v->vartype=vtok; + v->msi=v->lsi=vcd_explicit_zero_subscripts; /* indicate [un]subscripted status */ + + if(vtok==V_PORT) + { + vtok=get_vartoken(); + if(vtok==V_STRING) + { + v->size=atoi_64(yytext); + if(!v->size) v->size=1; + } + else + if(vtok==V_LB) + { + vtok=get_vartoken(); + if(vtok==V_END) goto err; + if(vtok!=V_STRING) goto err; + v->msi=atoi_64(yytext); + vtok=get_vartoken(); + if(vtok==V_RB) + { + v->lsi=v->msi; + v->size=1; + } + else + { + if(vtok!=V_COLON) goto err; + vtok=get_vartoken(); + if(vtok!=V_STRING) goto err; + v->lsi=atoi_64(yytext); + vtok=get_vartoken(); + if(vtok!=V_RB) goto err; + + if(v->msi>v->lsi) + { + v->size=v->msi-v->lsi+1; + } + else + { + v->size=v->lsi-v->msi+1; + } + } + } + else goto err; + + vtok=get_strtoken(); + if(vtok==V_END) goto err; + v->id=(char *)malloc_2(yylen+1); + strcpy(v->id, yytext); + v->nid=vcdid_hash(yytext,yylen); + + if(v->nid < vcd_minid) vcd_minid = v->nid; + if(v->nid > vcd_maxid) vcd_maxid = v->nid; + + vtok=get_vartoken(); + if(vtok!=V_STRING) goto err; + if(slisthier_len) + { + v->name=(char *)malloc_2(slisthier_len+1+yylen+1); + strcpy(v->name,slisthier); + strcpy(v->name+slisthier_len,vcd_hier_delimeter); + strcpy(v->name+slisthier_len+1,yytext); + } + else + { + v->name=(char *)malloc_2(yylen+1); + strcpy(v->name,yytext); + } + } + else /* regular vcd var, not an evcd port var */ + { + vtok=get_vartoken(); + if(vtok==V_END) goto err; + v->size=atoi_64(yytext); + if(!v->size) v->size=1; + vtok=get_strtoken(); + if(vtok==V_END) goto err; + v->id=(char *)malloc_2(yylen+1); + strcpy(v->id, yytext); + v->nid=vcdid_hash(yytext,yylen); + + if(v->nid < vcd_minid) vcd_minid = v->nid; + if(v->nid > vcd_maxid) vcd_maxid = v->nid; + + vtok=get_vartoken(); + if(vtok!=V_STRING) goto err; + if(slisthier_len) + { + v->name=(char *)malloc_2(slisthier_len+1+yylen+1); + strcpy(v->name,slisthier); + strcpy(v->name+slisthier_len,vcd_hier_delimeter); + strcpy(v->name+slisthier_len+1,yytext); + } + else + { + v->name=(char *)malloc_2(yylen+1); + strcpy(v->name,yytext); + } + + vtok=get_vartoken(); + if(vtok==V_END) goto dumpv; + if(vtok!=V_LB) goto err; + vtok=get_vartoken(); + if(vtok!=V_STRING) goto err; + v->msi=atoi_64(yytext); + vtok=get_vartoken(); + if(vtok==V_RB) + { + v->lsi=v->msi; + goto dumpv; + } + if(vtok!=V_COLON) goto err; + vtok=get_vartoken(); + if(vtok!=V_STRING) goto err; + v->lsi=atoi_64(yytext); + vtok=get_vartoken(); + if(vtok!=V_RB) goto err; + } + + dumpv: + if(v->vartype==V_REAL) + { + v->size=1; /* override any data we parsed in */ + v->msi=v->lsi=0; + } + else + if((v->size>1)&&(v->msi<=0)&&(v->lsi<=0)) + { + if(v->vartype==V_EVENT) + { + v->size=1; + } + else + { + /* any criteria for the direction here? */ + v->msi=v->size-1; + v->lsi=0; + } + } + else + if((v->msi>v->lsi)&&((v->msi-v->lsi+1)!=v->size)) + { + if(v->vartype!=V_EVENT) goto err; + v->size=v->msi-v->lsi+1; + } + else + if((v->lsi>=v->msi)&&((v->lsi-v->msi+1)!=v->size)) + { + if(v->vartype!=V_EVENT) goto err; + v->size=v->msi-v->lsi+1; + } + + /* initial conditions */ + v->value=(char *)malloc_2(v->size+1); + v->value[v->size]=0; + v->narray=(struct Node **)calloc_2(v->size,sizeof(struct Node *)); + { + int i; + for(i=0;isize;i++) + { + v->value[i]='x'; + + v->narray[i]=(struct Node *)calloc_2(1,sizeof(struct Node)); + v->narray[i]->head.time=-1; + v->narray[i]->head.v.val=1; + } + } + + if(v->vartype==V_EVENT) + { + struct queuedevent *q; + v->ev=q=(struct queuedevent *)calloc_2(1,sizeof(struct queuedevent)); + q->sym=v; + q->last_event_time=-1; + q->next=queuedevents; + queuedevents=q; + } + + if(!vcdsymroot) + { + vcdsymroot=vcdsymcurr=v; + } + else + { + vcdsymcurr->next=v; + vcdsymcurr=v; + } + numsyms++; + +#if 0 + if((v->vartype==V_INTEGER)||(v->vartype==V_REAL)) + { + v->ltsym = vzt_wr_symbol_add(lt, v->name, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?VZT_WR_SYM_F_INTEGER:((v->vartype==V_REAL)?VZT_WR_SYM_F_DOUBLE:VZT_WR_SYM_F_BITS)); + } + else + { + char buf[65537]; + if(v->msi==v->lsi) + { + sprintf(buf, "%s[%d]", v->name, v->msi); + } + else + { + sprintf(buf, "%s[%d:%d]", v->name, v->msi, v->lsi); + } + v->ltsym = vzt_wr_symbol_add(lt, buf, 0, v->msi, v->lsi, (v->vartype==V_INTEGER)?VZT_WR_SYM_F_INTEGER:((v->vartype==V_REAL)?VZT_WR_SYM_F_DOUBLE:VZT_WR_SYM_F_BITS)); + } +#endif + + DEBUG(fprintf(stderr,"VAR %s %d %s %s[%d:%d]\n", + vartypes[v->vartype], v->size, v->id, v->name, + v->msi, v->lsi)); + goto bail; + err: + if(v) + { + if(v->name) free_2(v->name); + if(v->id) free_2(v->id); + if(v->value) free_2(v->value); + free_2(v); + } + + bail: + if(vtok!=V_END) sync_end(NULL); + break; + } + case T_ENDDEFINITIONS: + if(!header_over) + { + header_over=1; /* do symbol table management here */ + create_sorted_table(); + if((!sorted)&&(!indexed)) + { + fprintf(stderr, "No symbols in VCD file..nothing to do!\n"); + exit(1); + } + } + break; + case T_STRING: + if(header_over) + { + /* catchall for events when header over */ + if(yytext[0]=='#') + { + TimeType time; + time=atoi_64(yytext+1); + + if(start_time<0) + { + start_time=time; + } + current_time=time; + if(end_timecurr) + { + he=(struct HistEnt *)calloc_2(1,sizeof(struct HistEnt)); + he->time=-1; + he->v.val=1; + + n->curr=he; + n->head.next=he; + + add_histent(time,n,ch,regadd, vector); + } + else + { + if(regadd) { time*=(time_scale); } + + if(toupper(ch)!=deadchar) n->notdead=1; + n->numtrans++; + } +} +else +{ +if(ch=='g') /* real number */ + { + if(!n->curr) + { + he=(struct HistEnt *)calloc_2(1,sizeof(struct HistEnt)); + he->time=-1; + he->v.vector=NULL; + + n->curr=he; + n->head.next=he; + + add_histent(time,n,ch,regadd, vector); + } + else + { + n->notdead=1; + n->numtrans++; + } + } + else + { + if(!n->curr) + { + he=(struct HistEnt *)calloc_2(1,sizeof(struct HistEnt)); + he->time=-1; + he->v.vector=NULL; + + n->curr=he; + n->head.next=he; + + add_histent(time,n,ch,regadd, vector); + } + else + { + int i, nlen; + + nlen = strlen(vector); + if(nlen) + { + n->numtrans++; + for(i=0;inotdead=1; + return; + } + } + } + } + } +} + +} + + +static void add_tail_histents(void) +{ +/* dump out any pending events 1st */ +struct queuedevent *q; +q=queuedevents; +while(q) + { + struct vcdsymbol *v; + + v=q->sym; + if(current_time!=(v->ev->last_event_time+1)) + { + /* dump degating event */ + DEBUG(fprintf(stderr,"#"TTFormat" %s = '%c' (event)\n",v->ev->last_event_time+1,v->name,'0')); + add_histent(v->ev->last_event_time+1,v->narray[0],'0',1, NULL); + } + q=q->next; + } +} + +/*******************************************************************************/ + +TimeType vcd_main(char *fname, char *lxname) +{ +#ifdef ONLY_NEEDED_FOR_VALGRIND_CLEAN_TEST +struct vcdsymbol *v, *v2; +#endif + +vcd_hier_delimeter[0]=hier_delimeter; + +errno=0; /* reset in case it's set for some reason */ + +yytext=(char *)malloc_2(T_MAX_STR+1); + +if((strlen(fname)>2)&&(!strcmp(fname+strlen(fname)-3,".gz"))) + { + char *str; + int dlen; + dlen=strlen(WAVE_DECOMPRESSOR); + str=(char *)wave_alloca(strlen(fname)+dlen+1); + strcpy(str,WAVE_DECOMPRESSOR); + strcpy(str+dlen,fname); + vcd_handle=popen(str,"r"); + vcd_is_compressed=~0; + } + else + { + if(strcmp("-",fname)) + { + vcd_handle=fopen(fname,"rb"); + } + else + { + vcd_handle=stdin; + } + vcd_is_compressed=0; + } + +if(!vcd_handle) + { + fprintf(stderr, "Error opening %s .vcd file '%s'.\n", + vcd_is_compressed?"compressed":"", fname); + exit(1); + } + +lt=vzt_wr_init(lxname); +if(!lt) + { + fprintf(stderr, "Problem opening output file '%s'\n", lxname); + perror("Why"); + exit(255); + } + +vzt_wr_set_compression_type(lt, ziptype); + +if(opt_twostate) + { + vzt_wr_force_twostate(lt); + } + +vzt_wr_set_rle(lt, opt_rle); +vzt_wr_set_compression_depth(lt, opt_depth); +vzt_wr_set_break_size(lt, (off_t)opt_break_size); +vzt_wr_set_maxgranule(lt, opt_maxgranule); +vzt_wr_symbol_bracket_stripping(lt, 1); /* this is intentional */ + +sym=(struct symbol **)calloc_2(SYMPRIME,sizeof(struct symbol *)); +printf("\nConverting VCD File '%s' to VZT file '%s'...\n\n",(vcd_handle!=stdin)?fname:"from stdin", lxname); +build_slisthier(); +vcd_parse(); + +add_tail_histents(); + +printf("["TTFormat"] start time.\n["TTFormat"] end time.\n\n", start_time, end_time); + +vzt_wr_close(lt); +lt=NULL; + +min_time=start_time*time_scale; +max_time=end_time*time_scale; + +if((min_time==max_time)||(max_time==0)) + { + fprintf(stderr, "VCD times range is equal to zero. Exiting.\n"); + exit(1); + } + +if(vcd_handle!=stdin) + { + fclose(vcd_handle); + vcd_handle=NULL; + } + +free(yytext); yytext=NULL; +if(indexed) { free(indexed); indexed=NULL; } +if(sorted) { free(sorted); sorted=NULL; } + +#ifdef ONLY_NEEDED_FOR_VALGRIND_CLEAN_TEST +v=vcdsymroot; +while(v) + { + if(v->name) { free(v->name); v->name=NULL; } + if(v->id) { free(v->id); v->id=NULL; } + if(v->value) { free(v->value); v->value=NULL; } + + if(v->narray) + { + int i; + for(i=0;isize;i++) + { + struct HistEnt *h1, *h2; + + if((h1 = v->narray[i]->head.next)) + { + h1 = v->narray[i]->head.next; + while(h1) + { + h2 = h1->next; + free(h1); + h1 = h2; + } + } + + free(v->narray[i]); v->narray[i]=NULL; + } + + free(v->narray); v->narray=NULL; + } + + v2=v->next; + free(v); + v=v2; + } +vcdsymroot=vcdsymcurr=NULL; +#endif + +free(sym); sym=NULL; + +if(slisthier) { free(slisthier); slisthier=NULL; } + +return(max_time); +} + +/*******************************************************************************/ + +/* + * Generic hash function for symbol names... + */ +int hash(char *s) +{ +char *p; +unsigned int h=0, g; +for(p=s;*p;p++) + { + h=(h<<4)+(*p); + if((g=h&0xf0000000)) + { + h=h^(g>>24); + h=h^g; + } + } +return(h%SYMPRIME); +} + +/* + * add symbol to table. no duplicate checking + * is necessary as aet's are "correct." + */ +struct symbol *symadd(char *name, int hv) +{ +struct symbol *s; + +s=(struct symbol *)calloc_2(1,sizeof(struct symbol)); +strcpy(s->name=(char *)malloc_2(strlen(name)+1),name); +s->next=sym[hv]; +sym[hv]=s; +return(s); +} + +/* + * find a slot already in the table... + */ +struct symbol *symfind(char *s) +{ +int hv; +struct symbol *temp; + + hv=hash(s); + if(!(temp=sym[hv])) return(NULL); /* no hash entry, add here wanted to add */ + + while(temp) + { + if(!strcmp(temp->name,s)) + { + return(temp); /* in table already */ + } + if(!temp->next) break; + temp=temp->next; + } + + return(NULL); /* not found, add here if you want to add*/ +} + +int sigcmp(char *s1, char *s2) +{ +unsigned char c1, c2; +int u1, u2; + +for(;;) + { + c1=(unsigned char)*(s1++); + c2=(unsigned char)*(s2++); + + if((!c1)&&(!c2)) return(0); + if((c1<='9')&&(c2<='9')&&(c2>='0')&&(c1>='0')) + { + u1=(int)(c1&15); + u2=(int)(c2&15); + + while(((c2=(unsigned char)*s2)>='0')&&(c2<='9')) + { + u2*=10; + u2+=(unsigned int)(c2&15); + s2++; + } + + while(((c2=(unsigned char)*s1)>='0')&&(c2<='9')) + { + u1*=10; + u1+=(unsigned int)(c2&15); + s1++; + } + + if(u1==u2) continue; + else return((int)u1-(int)u2); + } + else + { + if(c1!=c2) return((int)c1-(int)c2); + } + } +} + + +int partition(struct symbol **a, int p, int r) +{ +struct symbol *x, *t; +int i,j; + +x=a[p]; +i=p-1; +j=r+1; + +while(1) + { + do + { + j--; + } while(sigcmp(a[j]->name,x->name)>0); + + do { + i++; + } while(sigcmp(a[i]->name,x->name)<0); + + if(i.\n",nam); +#else +printf( +"Usage: %s [OPTION]... [VCDFILE] [VZTFILE]\n\n" +" -v FILE specify VCD input filename\n" +" -l FILE specify VZT output filename\n" +" -d value specify 0..9 compression depth (default = 4)\n" +" -m value specify number of granules per section (def = 8)\n" +" -b value specify break size (default = 0 = off)\n" +" -z value specify zip type (default = 0 gzip, 1 = bzip2)\n" +" -t force MVL2 twostate mode (default is MVL4)\n" +" -r use bitwise RLE compression on value table\n" +" -h display this help then exit\n\n" + +"VCD files may be compressed with zip or gzip. Note that VCDFILE and LXTFILE\n" +"are optional provided the --vcdname and --vztname options are specified.\n" +"Use \"-\" as a VCD filename to accept uncompressed input from stdin.\n\n" +"Report bugs to .\n",nam); +#endif + +exit(0); +} + + +int main(int argc, char **argv) +{ +char opt_errors_encountered=0; +char *vname=NULL, *lxname=NULL; +int c; + +while (1) + { + int option_index = 0; + +#ifdef __linux__ + static struct option long_options[] = + { + {"vcdname", 1, 0, 'v'}, + {"vztname", 1, 0, 'l'}, + {"depth", 1, 0, 'd'}, + {"maxgranule", 1, 0, 'm'}, + {"break", 1, 0, 'b'}, + {"help", 0, 0, 'h'}, + {"twostate", 0, 0, 't'}, + {"rle", 0, 0, 'r'}, + {"ziptype", 1, 0, 'z'}, + {0, 0, 0, 0} + }; + + c = getopt_long (argc, argv, "v:l:d:m:b:z:htr", long_options, &option_index); +#else + c = getopt (argc, argv, "v:l:d:m:b:z:htr"); +#endif + + if (c == -1) break; /* no more args */ + + switch (c) + { + case 'v': + if(vname) free(vname); + vname = malloc_2(strlen(optarg)+1); + strcpy(vname, optarg); + break; + + case 'l': + if(lxname) free(lxname); + lxname = malloc_2(strlen(optarg)+1); + strcpy(lxname, optarg); + break; + + case 'd': + opt_depth = atoi(optarg); + if(opt_depth<0) opt_depth = 0; + if(opt_depth>9) opt_depth = 9; + break; + + case 'm': + opt_maxgranule = atoi(optarg); + if(opt_maxgranule<1) opt_maxgranule=1; + break; + + case 'b': + sscanf(optarg, "%lld", &opt_break_size); + break; + + case 'h': + print_help(argv[0]); + break; + + case 't': + opt_twostate = 1; + break; + + case 'r': + opt_rle = 1; + break; + + case 'z': + ziptype = (atoi(optarg) != 0); + break; + + case '?': + opt_errors_encountered=1; + break; + + default: + /* unreachable */ + break; + } + } + +if(opt_errors_encountered) + { + print_help(argv[0]); + } + +if (optind < argc) + { + while (optind < argc) + { + if(!vname) + { + vname = malloc_2(strlen(argv[optind])+1); + strcpy(vname, argv[optind++]); + } + else if(!lxname) + { + lxname = malloc_2(strlen(argv[optind])+1); + strcpy(lxname, argv[optind++]); + } + } + } + +if((!vname)||(!lxname)) + { + print_help(argv[0]); + } + +vcd_main(vname, lxname); + +free(vname); free(lxname); + +return(0); +} diff --git a/src/helpers/vzt2vcd.c b/src/helpers/vzt2vcd.c new file mode 100644 index 0000000..56dc8b0 --- /dev/null +++ b/src/helpers/vzt2vcd.c @@ -0,0 +1,358 @@ +/* + * Copyright (c) 2003 Tony Bybell. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include "vzt_read.h" +#include + +int flat_earth = 0; +extern void free_hier(void); +extern char *output_hier(char *name); + + +/* + * generate a vcd identifier for a given facindx + */ +static char *vcdid(int value) +{ +static char buf[16]; +int i; + +for(i=0;i<15;i++) + { + buf[i]=(char)((value%94)+33); /* for range 33..126 */ + value=value/94; + if(!value) {buf[i+1]=0; break;} + } + +return(buf); +} + +static char *vcd_truncate_bitvec(char *s) +{ +char l, r; + +r=*s; +if(r=='1') + { + return s; + } + else + { + s++; + } + +for(;;s++) + { + l=r; r=*s; + if(!r) return (s-1); + + if(l!=r) + { + return(((l=='0')&&(r=='1'))?s:s-1); + } + } +} + + +static vztint64_t vcd_prevtime; +char vcd_blackout; + +void vcd_callback(struct vzt_rd_trace **lt, vztint64_t *pnt_time, vztint32_t *pnt_facidx, char **pnt_value) +{ +struct vzt_rd_geometry *g = vzt_rd_get_fac_geometry(*lt, *pnt_facidx); + +/* fprintf(stderr, "%Ld %d %s\n", *pnt_time, *pnt_facidx, *pnt_value); */ + +if(vcd_prevtime != *pnt_time) + { + vcd_prevtime = *pnt_time; + printf("#%Ld\n", *pnt_time); + } + +if(!(*pnt_value)[0]) + { + if(!vcd_blackout) + { + vcd_blackout = 1; + printf("$dumpoff\n"); + } + + return; + } + else + { + if(vcd_blackout) + { + vcd_blackout = 0; + printf("$dumpon\n"); + } + } + +if(g->flags & VZT_RD_SYM_F_DOUBLE) + { + printf("r%s %s\n", *pnt_value, vcdid(*pnt_facidx)); + } +else +if(g->flags & VZT_RD_SYM_F_STRING) + { + printf("s%s %s\n", *pnt_value, vcdid(*pnt_facidx)); + } +else + { + if(g->len==1) + { + printf("%c%s\n", (*pnt_value)[0], vcdid(*pnt_facidx)); + } + else + { + printf("b%s %s\n", vcd_truncate_bitvec(*pnt_value), vcdid(*pnt_facidx)); + } + } +} + + +int process_vzt(char *fname) +{ +struct vzt_rd_trace *lt; +char *netname; + +lt=vzt_rd_init(fname); +if(lt) + { + int i; + int numfacs; + char time_dimension; + int time_scale = 1; + char scale; + + numfacs = vzt_rd_get_num_facs(lt); + vzt_rd_set_fac_process_mask_all(lt); + vzt_rd_set_max_block_mem_usage(lt, 0); /* no need to cache blocks */ + + scale = vzt_rd_get_timescale(lt); + switch(scale) + { + case 0: time_dimension = 's'; break; + + case -1: time_scale = 100; time_dimension = 'm'; break; + case -2: time_scale = 10; + case -3: time_dimension = 'm'; break; + + case -4: time_scale = 100; time_dimension = 'u'; break; + case -5: time_scale = 10; + case -6: time_dimension = 'u'; break; + + case -10: time_scale = 100; time_dimension = 'p'; break; + case -11: time_scale = 10; + case -12: time_dimension = 'p'; break; + + case -13: time_scale = 100; time_dimension = 'f'; break; + case -14: time_scale = 10; + case -15: time_dimension = 'f'; break; + + case -7: time_scale = 100; time_dimension = 'n'; break; + case -8: time_scale = 10; + case -9: + default: time_dimension = 'n'; break; + } + + printf("$timescale %d%c%c $end\n", time_scale, time_dimension, !scale ? ' ' : 's'); + + for(i=0;iflags & VZT_RD_SYM_F_DOUBLE) + { + printf("$var real 1 %s %s $end\n", vcdid(newindx), netname); + } + else + if(g->flags & VZT_RD_SYM_F_STRING) + { + printf("$var real 1 %s %s $end\n", vcdid(newindx), netname); + } + else + + { + if(g->len==1) + { + if((g->msb!=-1)&&(g->msb!=0)) + { + printf("$var wire 1 %s %s[%d] $end\n", vcdid(newindx), netname, g->msb); + } + else + { + printf("$var wire 1 %s %s $end\n", vcdid(newindx), netname); + } + } + else + { + printf("$var wire %d %s %s[%d:%d] $end\n", g->len, vcdid(newindx), netname, g->msb, g->lsb); + } + } + } + + if(!flat_earth) + { + output_hier(""); /* flush any remaining hierarchy if not back to toplevel */ + free_hier(); + } + + printf("$enddefinitions $end\n"); + printf("$dumpvars\n"); + + vcd_prevtime = vzt_rd_get_start_time(lt)-1; + + vzt_rd_iter_blocks(lt, vcd_callback, NULL); + + if(vcd_prevtime!=vzt_rd_get_end_time(lt)) + { + printf("#%Ld\n", vzt_rd_get_end_time(lt)); + } + + vzt_rd_close(lt); + } + else + { + fprintf(stderr, "vzt_rd_init failed\n"); + return(255); + } + +return(0); +} + +/*******************************************************************************/ + +void print_help(char *nam) +{ +#ifdef __linux__ +printf( +"Usage: %s [OPTION]... [VZTFILE]\n\n" +" -v, --vztname=FILE specify VZT input filename\n" +" -f, --flatearth emit flattened hierarchies\n" +" -h, --help display this help then exit\n\n" +"VCD is emitted to stdout.\n\n" +"Report bugs to .\n",nam); +#else +printf( +"Usage: %s [OPTION]... [VZTFILE]\n\n" +" -l specify VZT input filename\n" +" -f emit flattened hierarchies\n" +" -h display this help then exit\n\n" + +"VCD is emitted to stdout.\n\n" +"Report bugs to .\n",nam); +#endif + +exit(0); +} + + +int main(int argc, char **argv) +{ +char opt_errors_encountered=0; +char *lxname=NULL; +int c; +int rc; + +while (1) + { + int option_index = 0; + +#ifdef __linux__ + static struct option long_options[] = + { + {"vztname", 1, 0, 'v'}, + {"flatearth", 0, 0, 'g'}, + {"help", 0, 0, 'h'}, + {0, 0, 0, 0} + }; + + c = getopt_long (argc, argv, "v:fh", long_options, &option_index); +#else + c = getopt (argc, argv, "v:fh"); +#endif + + if (c == -1) break; /* no more args */ + + switch (c) + { + case 'v': + if(lxname) free(lxname); + lxname = malloc(strlen(optarg)+1); + strcpy(lxname, optarg); + break; + + case 'f': flat_earth=1; + break; + + case 'h': + print_help(argv[0]); + break; + + case '?': + opt_errors_encountered=1; + break; + + default: + /* unreachable */ + break; + } + } + +if(opt_errors_encountered) + { + print_help(argv[0]); + } + +if (optind < argc) + { + while (optind < argc) + { + if(!lxname) + { + lxname = malloc(strlen(argv[optind])+1); + strcpy(lxname, argv[optind++]); + } + } + } + +if(!lxname) + { + print_help(argv[0]); + } + +rc=process_vzt(lxname); +free(lxname); + +return(rc); +} diff --git a/src/helpers/vzt_read.c b/src/helpers/vzt_read.c new file mode 100644 index 0000000..9fd0da3 --- /dev/null +++ b/src/helpers/vzt_read.c @@ -0,0 +1,1883 @@ +/* + * Copyright (c) 2003-2005 Tony Bybell. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __CYGWIN__ +#include +#include +#endif +#include "vzt_read.h" + +#ifdef __FreeBSD__ +#include +#endif + +/****************************************************************************/ + +struct vzt_ncycle_autosort +{ +struct vzt_ncycle_autosort *next; +}; + +struct vzt_pth_args +{ +struct vzt_rd_trace *lt; +struct vzt_rd_block *b; +}; + + +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __CYGWIN__ && !defined __FreeBSD__ +_VZT_RD_INLINE static int vzt_rd_pthread_mutex_init(struct vzt_rd_trace *lt, pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr) +{ +if(lt->pthreads) { pthread_mutex_init(mutex, mutexattr); } +return(0); +} + +_VZT_RD_INLINE static void vzt_rd_pthread_mutex_lock(struct vzt_rd_trace *lt, pthread_mutex_t *mx) +{ +if(lt->pthreads) { pthread_mutex_lock(mx); } +} + +_VZT_RD_INLINE static void vzt_rd_pthread_mutex_unlock(struct vzt_rd_trace *lt, pthread_mutex_t *mx) +{ +if(lt->pthreads) { pthread_mutex_unlock(mx); } +} + +_VZT_RD_INLINE static void vzt_rd_pthread_mutex_destroy(struct vzt_rd_trace *lt, pthread_mutex_t *mutex) +{ +if(lt->pthreads) { pthread_mutex_destroy(mutex); } +} + +_VZT_RD_INLINE static void vzt_rd_pthread_create(struct vzt_rd_trace *lt, pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) +{ +if(lt->pthreads) + { + pthread_attr_init(attr); + pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED); + pthread_create(thread, attr, start_routine, arg); + } +} +#else +#define vzt_rd_pthread_mutex_init(a, b, c) +#define vzt_rd_pthread_mutex_lock(a, b) +#define vzt_rd_pthread_mutex_unlock(a, b) +#define vzt_rd_pthread_mutex_destroy(a, b) +#define vzt_rd_pthread_create(a, b, c, d, e) +#endif + +/****************************************************************************/ + +#ifdef _WAVE_BE32 + +/* + * reconstruct 8/16/32/64 bits out of the vzt's representation + * of a big-endian integer. this is for 32-bit PPC so no byte + * swizzling needs to be done at all. + */ + +#define vzt_rd_get_byte(mm,offset) ((unsigned int)(*((unsigned char *)(mm)+(offset)))) +#define vzt_rd_get_16(mm,offset) ((unsigned int)(*((unsigned short *)(((unsigned char *)(mm))+(offset))))) +#define vzt_rd_get_32(mm,offset) (*(unsigned int *)(((unsigned char *)(mm))+(offset))) +#define vzt_rd_get_64(mm,offset) ((((vztint64_t)vzt_rd_get_32((mm),(offset)))<<32)|((vztint64_t)vzt_rd_get_32((mm),(offset)+4))) + +#else + +/* + * reconstruct 8/16/24/32 bits out of the vzt's representation + * of a big-endian integer. x86 specific version... + */ + +#if defined(__i386__) || defined(__x86_64__) + +#define vzt_rd_get_byte(mm,offset) ((unsigned int)(*((unsigned char *)(mm)+(offset)))) + +_VZT_RD_INLINE static unsigned int vzt_rd_get_16(void *mm, int offset) +{ +unsigned short x = *((unsigned short *)((unsigned char *)mm+offset)); + + __asm("xchgb %b0,%h0" : + "=q" (x) : + "0" (x)); + + return (unsigned int) x; +} + +_VZT_RD_INLINE static unsigned int vzt_rd_get_32(void *mm, int offset) /* note that bswap is really 486+ */ +{ +unsigned int x = *((unsigned int *)((unsigned char *)mm+offset)); + + __asm("bswap %0": + "=r" (x) : + "0" (x)); + + return x; +} + +#define vzt_rd_get_64(mm,offset) ((((vztint64_t)vzt_rd_get_32((mm),(offset)))<<32)|((vztint64_t)vzt_rd_get_32((mm),(offset)+4))) + +#else + +/* + * reconstruct 8/16/24/32 bits out of the vzt's representation + * of a big-endian integer. this should work on all architectures. + */ +#define vzt_rd_get_byte(mm,offset) ((unsigned int)(*((unsigned char *)(mm)+(offset)))) + +static unsigned int vzt_rd_get_16(void *mm, int offset) +{ +unsigned char *nn=(unsigned char *)mm+offset; +unsigned int m1=*((unsigned char *)(nn++)); +unsigned int m2=*((unsigned char *)nn); +return((m1<<8)|m2); +} + +static unsigned int vzt_rd_get_32(void *mm, int offset) +{ +unsigned char *nn=(unsigned char *)mm+offset; +unsigned int m1=*((unsigned char *)(nn++)); +unsigned int m2=*((unsigned char *)(nn++)); +unsigned int m3=*((unsigned char *)(nn++)); +unsigned int m4=*((unsigned char *)nn); +return((m1<<24)|(m2<<16)|(m3<<8)|m4); +} + +static vztint64_t vzt_rd_get_64(void *mm, int offset) +{ +return( +(((vztint64_t)vzt_rd_get_32(mm,offset))<<32) +|((vztint64_t)vzt_rd_get_32(mm,offset+4)) +); +} + +#endif +#endif + +static unsigned int vzt_rd_get_32r(void *mm, int offset) +{ +unsigned char *nn=(unsigned char *)mm+offset; +unsigned int m4=*((unsigned char *)(nn++)); +unsigned int m3=*((unsigned char *)(nn++)); +unsigned int m2=*((unsigned char *)(nn++)); +unsigned int m1=*((unsigned char *)nn); +return((m1<<24)|(m2<<16)|(m3<<8)|m4); +} + + +static vztint32_t vzt_rd_get_v32(char **mm) +{ +signed char *c = *mm; +signed char *beg = c; +vztint32_t val; + +if(*c>=0) + { + while(*c>=0) c++; + *mm = c+1; + + val = (vztint32_t)(*c&0x7f); + do + { + val <<= 7; + val |= (vztint32_t)*(--c); + } while (c!=beg); + } + else + { + *mm = c+1; + val = (vztint32_t)(*c&0x7f); + } + +return(val); +} + +static vztint64_t vzt_rd_get_v64(char **mm) +{ +signed char *c = *mm; +signed char *beg = c; +vztint64_t val; + +if(*c>=0) + { + while(*c>=0) c++; + *mm = c+1; + + val = (vztint64_t)(*c&0x7f); + do + { + val <<= 7; + val |= (vztint64_t)*(--c); + } while (c!=beg); + } + else + { + val = (vztint64_t)(*c&0x7f); + *mm = c+1; + } + +return(val); +} + +_VZT_RD_INLINE static vztint32_t vzt_rd_get_v32_rvs(char **mm) +{ +signed char *c = *mm; +vztint32_t val; + +val = (vztint32_t)(*(c--)&0x7f); + +while(*c>=0) + { + val <<= 7; + val |= (vztint32_t)*(c--); + } + +*mm = c; +return(val); +} + + +/****************************************************************************/ + +/* + * fast SWAR ones count for 32 bits + */ +_VZT_RD_INLINE static vztint32_t +vzt_rd_ones_cnt(vztint32_t x) +{ +x -= ((x >> 1) & 0x55555555); +x = (((x >> 2) & 0x33333333) + (x & 0x33333333)); +x = (((x >> 4) + x) & 0x0f0f0f0f); +return((x * 0x01010101) >> 24); +} + +/* + * total zero count to the right of the first rightmost one bit + * encountered. its intended use is to + * "return the bitposition of the least significant 1 in vztint32_t" + * (use x &= ~(x&-x) to clear out that bit quickly) + */ +_VZT_RD_INLINE vztint32_t +vzt_rd_tzc(vztint32_t x) +{ +return (vzt_rd_ones_cnt((x & -x) - 1)); +} + +/****************************************************************************/ + +/* + * i2c utility function + */ +unsigned int vzt_rd_expand_bits_to_integer(int len, char *s) +{ +unsigned int v = 0; +int i; + +for(i=0;imutex); + +if((!b->times)&&(b->mem)) +{ +vztint64_t *times=NULL; +vztint32_t *change_dict=NULL; +vztint32_t *val_dict=NULL; +int num_time_ticks, num_sections, num_dict_entries; +char *pnt = b->mem; +int i, j, m, num_dict_words; +const char endian_word[] = { 0x01, 0x02, 0x03, 0x04 }; +/* vztint32_t *block_end = (vztint32_t *)(pnt + b->uncompressed_siz); */ +vztint32_t *val_tmp; +unsigned int num_bitplanes; +long padskip; + +num_time_ticks = vzt_rd_get_v32(&pnt); +/* fprintf(stderr, "* num_time_ticks = %d\n", num_time_ticks); */ +if(num_time_ticks != 0) + { + vztint64_t cur_time; + times = malloc(num_time_ticks * sizeof(vztint64_t)); + times[0] = cur_time = vzt_rd_get_v64(&pnt); + for(i=1;istart; + + num_time_ticks = b->end - b->start + 1; + times = malloc(num_time_ticks * sizeof(vztint64_t)); + + for(i=0;irle) + { + vztint32_t *curr_dec_dict; + vztint32_t first_bit = 0, curr_bit = 0; + vztint32_t runlen; + + val_dict = calloc(1, b->num_rle_bytes = (num_dict_words = num_sections * num_dict_entries) * sizeof(vztint32_t)); + curr_dec_dict = val_dict; + + vzt_rd_pthread_mutex_lock(lt, <->mutex); + lt->block_mem_consumed += b->num_rle_bytes; + vzt_rd_pthread_mutex_unlock(lt, <->mutex); + + for(i=0;imulti_state = (num_bitplanes > 1); +padskip = ((long)pnt)&3; pnt += (padskip) ? 4-padskip : 0; /* skip pad to next 4 byte boundary */ +b->vindex = (vztint32_t *)(pnt); + +if(*((int *)endian_word) == 0x01020304) /* have to bswap the value changes on big endian machines... */ + { + if(!b->rle) + { + for(i=0;ivindex; + for(i=0;itotal_values;j++) + { + *val_tmp = vzt_rd_get_32r(val_tmp, 0); + val_tmp++; + } + } + } + +pnt = (char *)(b->vindex + num_bitplanes * lt->total_values); +b->num_str_entries = vzt_rd_get_v32(&pnt); + +if(b->num_str_entries) + { + b->sindex = calloc(b->num_str_entries, sizeof(char *)); + for(i=0;inum_str_entries;i++) + { + b->sindex[i] = pnt; + pnt += (strlen(pnt) + 1); + } + } + +change_dict = malloc((num_dict_words = num_sections * num_dict_entries) * sizeof(vztint32_t)); +m = 0; +for(i=0;i> 31; + } + } + +b->val_dict = val_dict; +b->change_dict = change_dict; +b->times = times; +b->num_time_ticks = num_time_ticks; +b->num_dict_entries = num_dict_entries; +b->num_sections = num_sections; +} + +vzt_rd_pthread_mutex_unlock(lt, &b->mutex); +} + + +static int vzt_rd_block_vch_free(struct vzt_rd_trace *lt, struct vzt_rd_block *b, int killed) +{ +vzt_rd_pthread_mutex_lock(lt, &b->mutex); + +if(killed) b->killed = killed; /* never allocate ever again (in case we prefetch on process kill) */ + +if((b->rle) && (b->val_dict)) + { + free(b->val_dict); b->val_dict = NULL; + + vzt_rd_pthread_mutex_lock(lt, <->mutex); + lt->block_mem_consumed -= b->num_rle_bytes; + vzt_rd_pthread_mutex_unlock(lt, <->mutex); + } + +if(b->mem) { free(b->mem); b->mem = NULL; } +if(b->change_dict) { free(b->change_dict); b->change_dict = NULL; } +if(b->times) { free(b->times); b->times = NULL; } +if(b->sindex) { free(b->sindex); b->sindex = NULL; } + +vzt_rd_pthread_mutex_unlock(lt, &b->mutex); +return(1); +} + + +vztint32_t vzt_rd_next_value_chg_time(struct vzt_rd_trace *lt, struct vzt_rd_block *b, vztint32_t time_offset, vztint32_t facidx) +{ +int i; +vztint32_t len = lt->len[facidx]; +vztint32_t vindex_offset = lt->vindex_offset[facidx]; +vztint32_t vindex_offset_x = vindex_offset + lt->total_values; +vztint32_t old_time_offset = time_offset; +int word = time_offset / 32; +int bit = (time_offset & 31) + 1; +int row_size = b->num_sections; +vztint32_t *valpnt, *valpnt_x; +vztint32_t change_msk; + +if((time_offset>=(b->num_time_ticks-1))||(facidx>lt->numrealfacs)) return(time_offset); + +time_offset &= ~31; + +for(;wordmulti_state) + { + for(i=0;ichange_dict + (b->vindex[vindex_offset+i] * row_size + word); + valpnt_x = b->change_dict + (b->vindex[vindex_offset_x+i] * row_size + word); + change_msk |= *valpnt; + change_msk |= *valpnt_x; + } + } + else + { + for(i=0;ichange_dict + (b->vindex[vindex_offset+i] * row_size + word); + change_msk |= *valpnt; + } + } + + change_msk >>= bit; + if(change_msk) + { + return( (change_msk & 1 ? 0 : vzt_rd_tzc(change_msk)) + time_offset + bit ); + } + } + + time_offset += 32; + bit = 0; + } + +return(old_time_offset); +} + +int vzt_rd_fac_value(struct vzt_rd_trace *lt, struct vzt_rd_block *b, vztint32_t time_offset, vztint32_t facidx, char *value) +{ +vztint32_t len = lt->len[facidx]; +vztint32_t vindex_offset = lt->vindex_offset[facidx]; +int i; +int word = time_offset / 32; +int bit = time_offset & 31; +int row_size = b->num_sections; +vztint32_t *valpnt; +vztint32_t *val_base; + +if((time_offset>b->num_time_ticks)||(facidx>lt->numrealfacs)) return(0); + +val_base = b->val_dict + word; +if(b->multi_state) + { + vztint32_t vindex_offset_x = lt->vindex_offset[facidx] + lt->total_values; + vztint32_t *valpnt_x; + int which; + + for(i=0;ivindex[vindex_offset++] * row_size); + valpnt_x = val_base + (b->vindex[vindex_offset_x++] * row_size); + + which = (((*valpnt_x >> bit) & 1) << 1) | ((*valpnt >> bit) & 1); + value[i] = "01xz"[which]; + } + } + else + { + for(i=0;ivindex[vindex_offset++] * row_size); + value[i] = '0' | ((*valpnt >> bit) & 1); + } + } +value[i] = 0; + +return(1); +} + +static void vzt_rd_double_xdr(char *pnt, char *buf) +{ +int j; +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __CYGWIN__ +XDR x; +#endif +double d; +char xdrdata[8]; + +for(j=0;j<64;j++) + { + int byte = j/8; + int bit = 7-(j&7); + if(pnt[j]=='1') + { + xdrdata[byte] |= (1<value_current_sector, *pnt2=lt->value_previous_sector; +char buf[32]; +char *bufpnt; + +vzt_rd_block_vch_decode(lt, b); +vzt_rd_pthread_mutex_lock(lt, &b->mutex); + +for(idx=0;idxnumrealfacs;idx++) + { + int process_idx = idx/8; + int process_bit = idx&7; + + if(lt->process_mask[process_idx]&(1<prev)&&(!b->prev->exclude_block)) + { + vzt_rd_fac_value(lt, b->prev, b->prev->num_time_ticks - 1, idx, pnt2); /* get last val of prev sector */ + if(strcmp(pnt, pnt2)) + { + goto do_vch; + } + } + else + { +do_vch: if(!(lt->flags[idx] & (VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) + { + lt->value_change_callback(<, &b->times[i], &idx, &pnt); + } + else + { + if(lt->flags[idx] & VZT_RD_SYM_F_DOUBLE) + { + bufpnt = buf; + vzt_rd_double_xdr(pnt, buf); + lt->value_change_callback(<, &b->times[i], &idx, &bufpnt); + } + else + { + unsigned int spnt=vzt_rd_make_sindex(pnt); + char *msg = ((!i)&(!b->prev)) ? "UNDEF" : b->sindex[spnt]; + lt->value_change_callback(<, &b->times[i], &idx, &msg); + } + } + } + + i2 = vzt_rd_next_value_chg_time(lt, b, i, idx); + if(i==i2) break; + i=i2; + } + } + } + +vzt_rd_pthread_mutex_unlock(lt, &b->mutex); +return(1); +} + +/* + * most clients want this + */ +int vzt_rd_process_block(struct vzt_rd_trace *lt, struct vzt_rd_block *b) +{ +int i, i2; +int idx; +char *pnt=lt->value_current_sector, *pnt2=lt->value_previous_sector; +char buf[32]; +char *bufpnt; + +struct vzt_ncycle_autosort **autosort; +struct vzt_ncycle_autosort *deadlist=NULL; +struct vzt_ncycle_autosort *autofacs= calloc(lt->numrealfacs, sizeof(struct vzt_ncycle_autosort)); + +vzt_rd_block_vch_decode(lt, b); +vzt_rd_pthread_mutex_lock(lt, &b->mutex); + +autosort = calloc(b->num_time_ticks, sizeof(struct vzt_ncycle_autosort)); +for(i=0;inum_time_ticks;i++) autosort[i]=NULL; +deadlist=NULL; + +for(idx=0;idxnumrealfacs;idx++) + { + int process_idx = idx/8; + int process_bit = idx&7; + + if(lt->process_mask[process_idx]&(1<prev)&&(!b->prev->exclude_block)) + { + vzt_rd_fac_value(lt, b->prev, b->prev->num_time_ticks - 1, idx, pnt2); /* get last val of prev sector */ + if(strcmp(pnt, pnt2)) + { + goto do_vch_0; + } + } + else + { +do_vch_0: if(!(lt->flags[idx] & (VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) + { + lt->value_change_callback(<, &b->times[i], &idx, &pnt); + } + else + { + if(lt->flags[idx] & VZT_RD_SYM_F_DOUBLE) + { + bufpnt = buf; + vzt_rd_double_xdr(pnt, buf); + lt->value_change_callback(<, &b->times[i], &idx, &bufpnt); + } + else + { + unsigned int spnt=vzt_rd_make_sindex(pnt); + char *msg = ((!i)&(!b->prev)) ? "UNDEF" : b->sindex[spnt]; + lt->value_change_callback(<, &b->times[i], &idx, &msg); + } + } + } + + i2 = vzt_rd_next_value_chg_time(lt, b, i, idx); + if(i2) + { + struct vzt_ncycle_autosort *t = autosort[i2]; + + autofacs[idx].next = t; + autosort[i2] = autofacs+idx; + } + else + { + struct vzt_ncycle_autosort *t = deadlist; + autofacs[idx].next = t; + deadlist = autofacs+idx; + } + } + } + +for(i = 1; i < b->num_time_ticks; i++) + { + struct vzt_ncycle_autosort *t = autosort[i]; + + if(t) + { + while(t) + { + struct vzt_ncycle_autosort *tn = t->next; + + idx = t-autofacs; + + vzt_rd_fac_value(lt, b, i, idx, pnt); + if(!(lt->flags[idx] & (VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) + { + lt->value_change_callback(<, &b->times[i], &idx, &pnt); + } + else + { + if(lt->flags[idx] & VZT_RD_SYM_F_DOUBLE) + { + bufpnt = buf; + vzt_rd_double_xdr(pnt, buf); + lt->value_change_callback(<, &b->times[i], &idx, &bufpnt); + } + else + { + unsigned int spnt=vzt_rd_make_sindex(pnt); + char *msg = ((!i)&(!b->prev)) ? "UNDEF" : b->sindex[spnt]; + lt->value_change_callback(<, &b->times[i], &idx, &msg); + } + } + + i2 = vzt_rd_next_value_chg_time(lt, b, i, idx); + + if(i2!=i) + { + struct vzt_ncycle_autosort *t = autosort[i2]; + + autofacs[idx].next = t; + autosort[i2] = autofacs+idx; + } + else + { + struct vzt_ncycle_autosort *t = deadlist; + autofacs[idx].next = t; + deadlist = autofacs+idx; + } + + t = tn; + } + } + } + +vzt_rd_pthread_mutex_unlock(lt, &b->mutex); + +free(autofacs); +free(autosort); + +return(1); +} + +/****************************************************************************/ + +/* + * null callback used when a user passes NULL as an argument to vzt_rd_iter_blocks() + */ +void vzt_rd_null_callback(struct vzt_rd_trace **lt, vztint64_t *pnt_time, vztint32_t *pnt_facidx, char **pnt_value) +{ +/* fprintf(stderr, VZT_RDLOAD"%lld %d %s\n", *pnt_time, *pnt_facidx, *pnt_value); */ +} + +/****************************************************************************/ + +/* + * return number of facs in trace + */ +_VZT_RD_INLINE vztint32_t vzt_rd_get_num_facs(struct vzt_rd_trace *lt) +{ +return(lt ? lt->numfacs : 0); +} + + +/* + * return fac geometry for a given index + */ +struct vzt_rd_geometry *vzt_rd_get_fac_geometry(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +if((lt)&&(facidxnumfacs)) + { + lt->geometry.rows = lt->rows[facidx]; + lt->geometry.msb = lt->msb[facidx]; + lt->geometry.lsb = lt->lsb[facidx]; + lt->geometry.flags = lt->flags[facidx]; + lt->geometry.len = lt->len[facidx]; + return(<->geometry); + } + else + { + return(NULL); + } +} + + +/* + * return partial fac geometry for a given index + */ +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_rows(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +if((lt)&&(facidxnumfacs)) + { + return(lt->rows[facidx]); + } + else + { + return(0); + } +} + + +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_msb(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +if((lt)&&(facidxnumfacs)) + { + return(lt->msb[facidx]); + } + else + { + return(0); + } +} + + +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_lsb(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +if((lt)&&(facidxnumfacs)) + { + return(lt->lsb[facidx]); + } + else + { + return(0); + } +} + + +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_flags(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +if((lt)&&(facidxnumfacs)) + { + return(lt->flags[facidx]); + } + else + { + return(0); + } +} + + +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_len(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +if((lt)&&(facidxnumfacs)) + { + return(lt->len[facidx]); + } + else + { + return(0); + } +} + + +_VZT_RD_INLINE vztint32_t vzt_rd_get_alias_root(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +if((lt)&&(facidxnumfacs)) + { + while(lt->flags[facidx] & VZT_RD_SYM_F_ALIAS) + { + facidx = lt->rows[facidx]; /* iterate to next alias */ + } + return(facidx); + } + else + { + return(~((vztint32_t)0)); + } +} + + +/* + * time queries + */ +_VZT_RD_INLINE vztint64_t vzt_rd_get_start_time(struct vzt_rd_trace *lt) +{ +return(lt ? lt->start : 0); +} + + +_VZT_RD_INLINE vztint64_t vzt_rd_get_end_time(struct vzt_rd_trace *lt) +{ +return(lt ? lt->end : 0); +} + + +_VZT_RD_INLINE char vzt_rd_get_timescale(struct vzt_rd_trace *lt) +{ +return(lt ? lt->timescale : 0); +} + + +/* + * extract facname from prefix-compressed table. this + * performs best when extracting facs with monotonically + * increasing indices... + */ +char *vzt_rd_get_facname(struct vzt_rd_trace *lt, vztint32_t facidx) +{ +char *pnt; +int clone, j; + +if(lt) + { + if((facidx==(lt->faccache->old_facidx+1))||(!facidx)) + { + if(!facidx) + { + lt->faccache->n = lt->zfacnames; + lt->faccache->bufcurr[0] = 0; + lt->faccache->bufprev[0] = 0; + } + + if(facidx!=lt->numfacs) + { + pnt = lt->faccache->bufcurr; + lt->faccache->bufcurr = lt->faccache->bufprev; + lt->faccache->bufprev = pnt; + + clone=vzt_rd_get_16(lt->faccache->n, 0); lt->faccache->n+=2; + pnt=lt->faccache->bufcurr; + + for(j=0;jfaccache->bufprev[j]; + } + + while((*(pnt++)=vzt_rd_get_byte(lt->faccache->n++,0))); + lt->faccache->old_facidx = facidx; + return(lt->faccache->bufcurr); + } + else + { + return(NULL); /* no more left */ + } + } + else + { + if(facidxnumfacs) + { + int strt; + + if(facidx==lt->faccache->old_facidx) + { + return(lt->faccache->bufcurr); + } + + if(facidx>(lt->faccache->old_facidx+1)) + { + strt = lt->faccache->old_facidx+1; + } + else + { + strt=0; + } + + for(j=strt;jnumfacs) + { + int process_idx = facidx/8; + int process_bit = facidx&7; + + return( (lt->process_mask[process_idx]&(1<numfacs) + { + int idx = facidx/8; + int bitpos = facidx&7; + + lt->process_mask[idx] |= (1<numfacs) + { + int idx = facidx/8; + int bitpos = facidx&7; + + lt->process_mask[idx] &= (~(1<process_mask, 0xff, (lt->numfacs+7)/8); + rc=1; + } + +return(rc); +} + + +_VZT_RD_INLINE int vzt_rd_clr_fac_process_mask_all(struct vzt_rd_trace *lt) +{ +int rc=0; + +if(lt) + { + memset(lt->process_mask, 0x00, (lt->numfacs+7)/8); + rc=1; + } + +return(rc); +} + + +/* + * block memory set/get used to control buffering + */ +_VZT_RD_INLINE vztint64_t vzt_rd_set_max_block_mem_usage(struct vzt_rd_trace *lt, vztint64_t block_mem_max) +{ +vztint64_t rc = lt->block_mem_max; +lt->block_mem_max = block_mem_max; +return(rc); +} + + +_VZT_RD_INLINE vztint64_t vzt_rd_get_block_mem_usage(struct vzt_rd_trace *lt) +{ +vztint64_t mem; + +vzt_rd_pthread_mutex_lock(lt, <->mutex); +mem = lt->block_mem_consumed; +vzt_rd_pthread_mutex_unlock(lt, <->mutex); + +return(mem); +} + + +/* + * return total number of blocks + */ +_VZT_RD_INLINE unsigned int vzt_rd_get_num_blocks(struct vzt_rd_trace *lt) +{ +return(lt->numblocks); +} + +/* + * return number of active blocks + */ +unsigned int vzt_rd_get_num_active_blocks(struct vzt_rd_trace *lt) +{ +int blk=0; + +if(lt) + { + struct vzt_rd_block *b = lt->block_head; + + while(b) + { + if((!b->short_read_ignore)&&(!b->exclude_block)) + { + blk++; + } + + b=b->next; + } + } + +return(blk); +} + +/****************************************************************************/ + +static int vzt_rd_is_gzip_type(FILE *handle) +{ +unsigned char cbuf[2] = { 0, 0 }; + +off_t off = ftello(handle); +fread(cbuf, 1, 2, handle); +fseeko(handle, off, SEEK_SET); + +return((cbuf[0] == 0x1f) && (cbuf[1] == 0x8b)); +} + +/****************************************************************************/ + +static void vzt_rd_decompress_blk(struct vzt_rd_trace *lt, struct vzt_rd_block *b, int reopen) +{ +int rc; +void *zhandle; +FILE *handle; +if(reopen) + { + handle = fopen(lt->filename, "rb"); + } + else + { + handle = lt->handle; + } +fseeko(handle, b->filepos, SEEK_SET); + +vzt_rd_pthread_mutex_lock(lt, &b->mutex); + +if((!b->killed)&&(!b->mem)) + { + b->mem = malloc(b->uncompressed_siz); + + if(b->ztype) + { + zhandle = gzdopen(dup(fileno(handle)), "rb"); + rc=gzread(zhandle, b->mem, b->uncompressed_siz); + gzclose(zhandle); + } + else + { + zhandle = BZ2_bzdopen(dup(fileno(handle)), "rb"); + rc=BZ2_bzread(zhandle, b->mem, b->uncompressed_siz); + BZ2_bzclose(zhandle); + } + if(rc!=b->uncompressed_siz) + { + fprintf(stderr, VZT_RDLOAD"short read on block %p %d vs %d (exp), ignoring\n", b, rc, b->uncompressed_siz); + free(b->mem); b->mem=NULL; + b->short_read_ignore = 1; + } + else + { + vzt_rd_pthread_mutex_lock(lt, <->mutex); + lt->block_mem_consumed += b->uncompressed_siz; + vzt_rd_pthread_mutex_unlock(lt, <->mutex); + } + } + +vzt_rd_pthread_mutex_unlock(lt, &b->mutex); + +if(reopen) + { + fclose(handle); + } +} + + +static void *vzt_rd_decompress_blk_pth_actual(void *args) +{ +struct vzt_pth_args *vpa = (struct vzt_pth_args *)args; +vzt_rd_decompress_blk(vpa->lt, vpa->b, 1); +vzt_rd_block_vch_decode(vpa->lt, vpa->b); +free(vpa); + +return(NULL); +} + +static void vzt_rd_decompress_blk_pth(struct vzt_rd_trace *lt, struct vzt_rd_block *b) +{ +struct vzt_pth_args *vpa = malloc(sizeof(struct vzt_pth_args)); +vpa->lt = lt; +vpa->b = b; + +vzt_rd_pthread_create(lt, &b->pth, &b->pth_attr, vzt_rd_decompress_blk_pth_actual, vpa); +} + +/* + * block iteration...purge/reload code here isn't sophisticated as it + * merely caches the FIRST set of blocks which fit in lt->block_mem_max. + * n.b., returns number of blocks processed + */ +int vzt_rd_iter_blocks(struct vzt_rd_trace *lt, + void (*value_change_callback)(struct vzt_rd_trace **lt, vztint64_t *time, vztint32_t *facidx, char **value), + void *user_callback_data_pointer) +{ +struct vzt_rd_block *b, *bpre; +int blk=0, blkfinal=0; +int processed = 0; +struct vzt_rd_block *bcutoff=NULL, *bfinal=NULL; + +if(lt) + { + lt->value_change_callback = value_change_callback ? value_change_callback : vzt_rd_null_callback; + lt->user_callback_data_pointer = user_callback_data_pointer; + + b = lt->block_head; + blk=0; + + while(b) + { + if((!b->mem)&&(!b->short_read_ignore)&&(!b->exclude_block)) + { + if(processed<5) + { + int gate = (processed==4) && b->next; + + fprintf(stderr, VZT_RDLOAD"block [%d] processing "VZT_RD_LLD" / "VZT_RD_LLD"%s\n", blk, b->start, b->end, gate ? " ..." : ""); + if(gate) { bcutoff = b; } + } + + processed++; + + if(lt->pthreads) + { + int count = lt->pthreads; + /* prefetch next *empty* block(s) on an alternate thread */ + bpre = b->next; + while(bpre) + { + if((!bpre->mem)&&(!bpre->short_read_ignore)&&(!bpre->exclude_block)) + { + vzt_rd_decompress_blk_pth(lt, bpre); + count--; + if(!count) break; + } + bpre = bpre->next; + } + } + + vzt_rd_decompress_blk(lt, b, 0); + bfinal=b; + blkfinal = blk; + } + + if(b->mem) + { + if(lt->process_linear) + { + vzt_rd_process_block_linear(lt, b); + } + else + { + vzt_rd_process_block(lt, b); + } + + if(lt->numblocks > 2) /* no sense freeing up when not so many blocks */ + { + vztint64_t block_mem_consumed; + + vzt_rd_pthread_mutex_lock(lt, <->mutex); + block_mem_consumed = lt->block_mem_consumed; + vzt_rd_pthread_mutex_unlock(lt, <->mutex); + + if(block_mem_consumed > lt->block_mem_max) + { + if(b->prev) + { + vzt_rd_pthread_mutex_lock(lt, <->mutex); + lt->block_mem_consumed -= b->prev->uncompressed_siz; + vzt_rd_pthread_mutex_unlock(lt, <->mutex); + vzt_rd_block_vch_free(lt, b->prev, 0); + } + } + } + } + + blk++; + b=b->next; + } + } + +if((bcutoff)&&(bfinal!=bcutoff)) + { + fprintf(stderr, VZT_RDLOAD"block [%d] processed "VZT_RD_LLD" / "VZT_RD_LLD"\n", blkfinal, bfinal->start, bfinal->end); + } + +return(blk); +} + + +/* + * callback access to the user callback data pointer (if required) + */ +_VZT_RD_INLINE void *vzt_rd_get_user_callback_data_pointer(struct vzt_rd_trace *lt) +{ +if(lt) + { + return(lt->user_callback_data_pointer); + } + else + { + return(NULL); + } +} + + +/* + * limit access to certain timerange in file + * and return number of active blocks + */ +unsigned int vzt_rd_limit_time_range(struct vzt_rd_trace *lt, vztint64_t strt_time, vztint64_t end_time) +{ +vztint64_t tmp_time; +int blk=0; + +if(lt) + { + struct vzt_rd_block *b = lt->block_head; + struct vzt_rd_block *bprev = NULL; + int state = 0; + + if(strt_time > end_time) + { + tmp_time = strt_time; + strt_time = end_time; + end_time = tmp_time; + } + + while(b) + { + switch(state) + { + case 0: if(b->end >= strt_time) + { + state = 1; + if((b->start > strt_time) && (bprev)) + { + bprev->exclude_block = 0; + blk++; + } + } + break; + + case 1: if(b->start > end_time) state = 2; + break; + + default: break; + } + + if((state==1) && (!b->short_read_ignore)) + { + b->exclude_block = 0; + blk++; + } + else + { + b->exclude_block = 1; + } + + bprev = b; + b = b->next; + } + + } + +return(blk); +} + +/* + * unrestrict access to the whole file + * and return number of active blocks + */ +unsigned int vzt_rd_unlimit_time_range(struct vzt_rd_trace *lt) +{ +int blk=0; + +if(lt) + { + struct vzt_rd_block *b = lt->block_head; + + while(b) + { + b->exclude_block = 0; + + if(!b->short_read_ignore) + { + blk++; + } + + b=b->next; + } + } + +return(blk); +} + + +/* + * mode switch for linear accessing + */ +void vzt_rd_process_blocks_linearly(struct vzt_rd_trace *lt, int doit) +{ +if(lt) + { + lt->process_linear = (doit != 0); + } +} + +/****************************************************************************/ + +/* + * initialize the trace, get compressed facnames, get geometries, + * and get block offset/size/timestart/timeend... + */ +struct vzt_rd_trace *vzt_rd_init_smp(const char *name, unsigned int num_cpus) +{ +struct vzt_rd_trace *lt=(struct vzt_rd_trace *)calloc(1, sizeof(struct vzt_rd_trace)); +int i; +unsigned int vindex_offset; + +if(!(lt->handle=fopen(name, "rb"))) + { + vzt_rd_close(lt); + lt=NULL; + } + else + { + vztint16_t id = 0, version = 0; + + lt->filename = strdup(name); + lt->block_mem_max = VZT_RD_MAX_BLOCK_MEM_USAGE; /* cutoff after this number of bytes and force flush */ + + if(num_cpus<1) num_cpus = 1; + if(num_cpus>8) num_cpus = 8; + lt->pthreads = num_cpus - 1; + + setvbuf(lt->handle, (char *)NULL, _IONBF, 0); /* keeps gzip from acting weird in tandem with fopen */ + + fread(&id, 2, 1, lt->handle); + fread(&version, 2, 1, lt->handle); + fread(<->granule_size, 1, 1, lt->handle); + + if(vzt_rd_get_16(&id,0) != VZT_RD_HDRID) + { + fprintf(stderr, VZT_RDLOAD"*** Not a vzt file ***\n"); + vzt_rd_close(lt); + lt=NULL; + } + else + if((version=vzt_rd_get_16(&version,0)) > VZT_RD_VERSION) + { + fprintf(stderr, VZT_RDLOAD"*** Version %d vzt not supported ***\n", version); + vzt_rd_close(lt); + lt=NULL; + } + if(lt->granule_size > VZT_RD_GRANULE_SIZE) + { + fprintf(stderr, VZT_RDLOAD"*** Granule size of %d (>%d) not supported ***\n", lt->granule_size, VZT_RD_GRANULE_SIZE); + vzt_rd_close(lt); + lt=NULL; + } + else + { + int rc; + char *m; + off_t pos, fend; + int t; + struct vzt_rd_block *b; + + vzt_rd_pthread_mutex_init(lt, <->mutex, NULL); + + fread(<->numfacs, 4, 1, lt->handle); lt->numfacs = vzt_rd_get_32(<->numfacs,0); + fread(<->numfacbytes, 4, 1, lt->handle); lt->numfacbytes = vzt_rd_get_32(<->numfacbytes,0); + fread(<->longestname, 4, 1, lt->handle); lt->longestname = vzt_rd_get_32(<->longestname,0); + fread(<->zfacnamesize, 4, 1, lt->handle); lt->zfacnamesize = vzt_rd_get_32(<->zfacnamesize,0); + fread(<->zfacname_predec_size, 4, 1, lt->handle); lt->zfacname_predec_size = vzt_rd_get_32(<->zfacname_predec_size,0); + fread(<->zfacgeometrysize, 4, 1, lt->handle); lt->zfacgeometrysize = vzt_rd_get_32(<->zfacgeometrysize,0); + fread(<->timescale, 1, 1, lt->handle); /* no swap necessary */ + + fprintf(stderr, VZT_RDLOAD"%d facilities\n", lt->numfacs); + pos = ftello(lt->handle); + /* fprintf(stderr, VZT_RDLOAD"gzip facnames start at pos %d (zsize=%d)\n", pos, lt->zfacnamesize); */ + + lt->process_mask = calloc(1, lt->numfacs/8+1); + + if(vzt_rd_is_gzip_type(lt->handle)) + { + lt->zhandle = gzdopen(dup(fileno(lt->handle)), "rb"); + m=(char *)malloc(lt->zfacname_predec_size); + rc=gzread(lt->zhandle, m, lt->zfacname_predec_size); + gzclose(lt->zhandle); lt->zhandle=NULL; + } + else + { + lt->zhandle = BZ2_bzdopen(dup(fileno(lt->handle)), "rb"); + m=(char *)malloc(lt->zfacname_predec_size); + rc=BZ2_bzread(lt->zhandle, m, lt->zfacname_predec_size); + BZ2_bzclose(lt->zhandle); lt->zhandle=NULL; + } + + if(rc!=lt->zfacname_predec_size) + { + fprintf(stderr, VZT_RDLOAD"*** name section mangled %d (act) vs %d (exp)\n", rc, lt->zfacname_predec_size); + free(m); + + vzt_rd_close(lt); + lt=NULL; + return(lt); + } + + lt->zfacnames = m; + + lt->faccache = calloc(1, sizeof(struct vzt_rd_facname_cache)); + lt->faccache->old_facidx = lt->numfacs; /* causes vzt_rd_get_facname to initialize its unroll ptr as this is always invalid */ + lt->faccache->bufcurr = malloc(lt->longestname+1); + lt->faccache->bufprev = malloc(lt->longestname+1); + + fseeko(lt->handle, pos = pos+lt->zfacnamesize, SEEK_SET); + /* fprintf(stderr, VZT_RDLOAD"seeking to geometry at %d (0x%08x)\n", pos, pos); */ + + if(vzt_rd_is_gzip_type(lt->handle)) + { + lt->zhandle = gzdopen(dup(fileno(lt->handle)), "rb"); + t = lt->numfacs * 4 * sizeof(vztint32_t); + m=(char *)malloc(t); + rc=gzread(lt->zhandle, m, t); + gzclose(lt->zhandle); lt->zhandle=NULL; + } + else + { + lt->zhandle = BZ2_bzdopen(dup(fileno(lt->handle)), "rb"); + t = lt->numfacs * 4 * sizeof(vztint32_t); + m=(char *)malloc(t); + rc=BZ2_bzread(lt->zhandle, m, t); + BZ2_bzclose(lt->zhandle); lt->zhandle=NULL; + } + + if(rc!=t) + { + fprintf(stderr, VZT_RDLOAD"*** geometry section mangled %d (act) vs %d (exp)\n", rc, t); + free(m); + + vzt_rd_close(lt); + lt=NULL; + return(lt); + } + + pos = pos+lt->zfacgeometrysize; + + lt->rows = malloc(lt->numfacs * sizeof(vztint32_t)); + lt->msb = malloc(lt->numfacs * sizeof(vztint32_t)); + lt->lsb = malloc(lt->numfacs * sizeof(vztint32_t)); + lt->flags = malloc(lt->numfacs * sizeof(vztint32_t)); + lt->len = malloc(lt->numfacs * sizeof(vztint32_t)); + lt->vindex_offset = malloc(lt->numfacs * sizeof(vztint32_t)); + + for(i=0;inumfacs;i++) + { + lt->rows[i] = vzt_rd_get_32(m+i*16, 0); + lt->msb[i] = vzt_rd_get_32(m+i*16, 4); + lt->lsb[i] = vzt_rd_get_32(m+i*16, 8); + lt->flags[i] = vzt_rd_get_32(m+i*16, 12); + + if(!(lt->flags[i] & (VZT_RD_SYM_F_INTEGER|VZT_RD_SYM_F_STRING|VZT_RD_SYM_F_DOUBLE))) + { + lt->len[i] = (lt->msb[i] <= lt->lsb[i]) ? (lt->lsb[i] - lt->msb[i] + 1) : (lt->msb[i] - lt->lsb[i] + 1); + } + else + { + lt->len[i] = (lt->flags[i] & (VZT_RD_SYM_F_INTEGER|VZT_RD_SYM_F_STRING)) ? 32 : 64; + } + + if(lt->len[i] > lt->longest_len) + { + lt->longest_len = lt->len[i]; + } + } + + lt->value_current_sector = malloc(lt->longest_len + 1); + lt->value_previous_sector = malloc(lt->longest_len + 1); + + vindex_offset = 0; /* offset in value table */ + for(lt->numrealfacs=0; lt->numrealfacsnumfacs; lt->numrealfacs++) + { + if(lt->flags[lt->numrealfacs] & VZT_RD_SYM_F_ALIAS) + { + break; + } + lt->vindex_offset[lt->numrealfacs] = vindex_offset; + vindex_offset += lt->len[lt->numrealfacs]; + } + lt->total_values = vindex_offset; + fprintf(stderr, VZT_RDLOAD"Total value bits: %d\n", lt->total_values); + + if(lt->numrealfacs > lt->numfacs) lt->numrealfacs = lt->numfacs; + + free(m); + + for(;;) + { + fseeko(lt->handle, 0L, SEEK_END); + fend=ftello(lt->handle); + if(pos>=fend) break; + + fseeko(lt->handle, pos, SEEK_SET); + /* fprintf(stderr, VZT_RDLOAD"seeking to block at %d (0x%08x)\n", pos, pos); */ + + b=calloc(1, sizeof(struct vzt_rd_block)); + + fread(&b->uncompressed_siz, 4, 1, lt->handle); b->uncompressed_siz = vzt_rd_get_32(&b->uncompressed_siz,0); + fread(&b->compressed_siz, 4, 1, lt->handle); b->compressed_siz = vzt_rd_get_32(&b->compressed_siz,0); + fread(&b->start, 8, 1, lt->handle); b->start = vzt_rd_get_64(&b->start,0); + fread(&b->end, 8, 1, lt->handle); b->end = vzt_rd_get_64(&b->end,0); + pos = ftello(lt->handle); + + if((b->rle = (b->start > b->end))) + { + vztint64_t t = b->start; + b->start = b->end; + b->end = t; + } + + b->ztype = vzt_rd_is_gzip_type(lt->handle); + /* fprintf(stderr, VZT_RDLOAD"block gzip start at pos %d (0x%08x)\n", pos, pos); */ + if(pos>=fend) + { + free(b); + break; + } + + b->filepos = pos; /* mark startpos for later in case we purge it from memory */ + /* fprintf(stderr, VZT_RDLOAD"un/compressed size: %d/%d\n", b->uncompressed_siz, b->compressed_siz); */ + + if((b->uncompressed_siz)&&(b->compressed_siz)&&(b->end)) + { + /* fprintf(stderr, VZT_RDLOAD"block [%d] %lld / %lld\n", lt->numblocks, b->start, b->end); */ + fseeko(lt->handle, b->compressed_siz, SEEK_CUR); + + lt->numblocks++; + if(lt->numblocks <= lt->pthreads) + { + vzt_rd_pthread_mutex_init(lt, &b->mutex, NULL); + vzt_rd_decompress_blk_pth(lt, b); /* prefetch first block */ + } + + if(lt->block_curr) + { + b->prev = lt->block_curr; + lt->block_curr->next = b; + lt->block_curr = b; + lt->end = b->end; + } + else + { + lt->block_head = lt->block_curr = b; + lt->start = b->start; + lt->end = b->end; + } + } + else + { + free(b); + break; + } + + pos+=b->compressed_siz; + } + + if(lt->numblocks) + { + fprintf(stderr, VZT_RDLOAD"Read %d block header%s OK\n", lt->numblocks, (lt->numblocks!=1) ? "s" : ""); + + fprintf(stderr, VZT_RDLOAD"["VZT_RD_LLD"] start time\n", lt->start); + fprintf(stderr, VZT_RDLOAD"["VZT_RD_LLD"] end time\n", lt->end); + fprintf(stderr, VZT_RDLOAD"\n"); + + lt->value_change_callback = vzt_rd_null_callback; + } + else + { + vzt_rd_close(lt); + lt=NULL; + } + } + } + +return(lt); +} + + +struct vzt_rd_trace *vzt_rd_init(const char *name) +{ +return(vzt_rd_init_smp(name, 1)); +} + + +/* + * free up/deallocate any resources still left out there: + * blindly do it based on NULL pointer comparisons (ok, since + * calloc() is used to allocate all structs) as performance + * isn't an issue for this set of cleanup code + */ +void vzt_rd_close(struct vzt_rd_trace *lt) +{ +if(lt) + { + struct vzt_rd_block *b, *bt; + + if(lt->process_mask) { free(lt->process_mask); lt->process_mask=NULL; } + + if(lt->rows) { free(lt->rows); lt->rows=NULL; } + if(lt->msb) { free(lt->msb); lt->msb=NULL; } + if(lt->lsb) { free(lt->lsb); lt->lsb=NULL; } + if(lt->flags) { free(lt->flags); lt->flags=NULL; } + if(lt->len) { free(lt->len); lt->len=NULL; } + if(lt->vindex_offset) { free(lt->vindex_offset); lt->vindex_offset=NULL; } + if(lt->zfacnames) { free(lt->zfacnames); lt->zfacnames=NULL; } + + if(lt->value_current_sector) { free(lt->value_current_sector); lt->value_current_sector=NULL; } + if(lt->value_previous_sector) { free(lt->value_previous_sector); lt->value_previous_sector=NULL; } + + if(lt->faccache) + { + if(lt->faccache->bufprev) { free(lt->faccache->bufprev); lt->faccache->bufprev=NULL; } + if(lt->faccache->bufcurr) { free(lt->faccache->bufcurr); lt->faccache->bufcurr=NULL; } + + free(lt->faccache); lt->faccache=NULL; + } + + b=lt->block_head; + while(b) + { + bt=b->next; + vzt_rd_block_vch_free(lt, b, 1); + vzt_rd_pthread_mutex_destroy(lt, &b->mutex); + + free(b); + b=bt; + } + + lt->block_head=lt->block_curr=NULL; + + if(lt->zhandle) { gzclose(lt->zhandle); lt->zhandle=NULL; } + if(lt->handle) { fclose(lt->handle); lt->handle=NULL; } + if(lt->filename) { free(lt->filename); lt->filename=NULL; } + + vzt_rd_pthread_mutex_destroy(lt, <->mutex); + + free(lt); + } +} diff --git a/src/helpers/vzt_read.h b/src/helpers/vzt_read.h new file mode 100644 index 0000000..2db2611 --- /dev/null +++ b/src/helpers/vzt_read.h @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2004-2005 Tony Bybell. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#ifndef DEFS_VZTR_H +#define DEFS_VZTR_H + +#include +#include +#include +#include +#include + +#ifndef _MSC_VER +#include +#include +#else +typedef long off_t; +#include +#include +#endif + +#if defined _MSC_VER || defined __MINGW32__ +#define fseeko fseek +#define ftello ftell +typedef int pthread_t; +typedef int pthread_attr_t; +typedef int pthread_mutex_t; +typedef int pthread_mutexattr_t; +#else +#include +#endif + +#include +#include + +#ifdef __GNUC__ +#define _VZT_RD_INLINE inline +#else +#define _VZT_RD_INLINE +#endif + +#define VZT_RDLOAD "VZTLOAD | " + +#define VZT_RD_HDRID (('V' << 8) + ('Z')) +#define VZT_RD_VERSION (0x0001) + +#define VZT_RD_GRANULE_SIZE (32) + +#define VZT_RD_MAX_BLOCK_MEM_USAGE (64*1024*1024) /* 64MB */ + +#ifndef _MSC_VER +typedef uint8_t vztint8_t; +typedef uint16_t vztint16_t; +typedef uint32_t vztint32_t; +typedef uint64_t vztint64_t; +#ifndef __MINGW32__ +#define VZT_RD_LLD "%lld" +#else +#define VZT_RD_LLD "%I64d" +#endif +#define VZT_RD_LLDESC(x) x##LL +#define VZT_RD_ULLDESC(x) x##ULL +#else +typedef unsigned __int8 vztint8_t; +typedef unsigned __int16 vztint16_t; +typedef unsigned __int32 vztint32_t; +typedef unsigned __int64 vztint64_t; +#define VZT_RD_LLD "%I64d" +#define VZT_RD_LLDESC(x) x##i64 +#define VZT_RD_ULLDESC(x) x##i64 +#endif + + +#define VZT_RD_SYM_F_BITS (0) +#define VZT_RD_SYM_F_INTEGER (1<<0) +#define VZT_RD_SYM_F_DOUBLE (1<<1) +#define VZT_RD_SYM_F_STRING (1<<2) +#define VZT_RD_SYM_F_TIME (VZT_RD_SYM_F_STRING) /* user must correctly format this as a string */ +#define VZT_RD_SYM_F_ALIAS (1<<3) + +#define VZT_RD_SYM_F_SIGNED (1<<4) +#define VZT_RD_SYM_F_BOOLEAN (1<<5) +#define VZT_RD_SYM_F_NATURAL ((1<<6)|(VZT_RD_SYM_F_INTEGER)) +#define VZT_RD_SYM_F_POSITIVE ((1<<7)|(VZT_RD_SYM_F_INTEGER)) +#define VZT_RD_SYM_F_CHARACTER (1<<8) +#define VZT_RD_SYM_F_CONSTANT (1<<9) +#define VZT_RD_SYM_F_VARIABLE (1<<10) +#define VZT_RD_SYM_F_SIGNAL (1<<11) + +#define VZT_RD_SYM_F_IN (1<<12) +#define VZT_RD_SYM_F_OUT (1<<13) +#define VZT_RD_SYM_F_INOUT (1<<14) + +#define VZT_RD_SYM_F_WIRE (1<<15) +#define VZT_RD_SYM_F_REG (1<<16) + + +struct vzt_rd_block +{ +char *mem; +struct vzt_rd_block *next; +struct vzt_rd_block *prev; + +vztint32_t uncompressed_siz, compressed_siz, num_rle_bytes; +vztint64_t start, end; + +vztint32_t *vindex; +vztint64_t *times; +vztint32_t *change_dict; +vztint32_t *val_dict; +char **sindex; +int num_time_ticks, num_sections, num_dict_entries, num_str_entries; + +off_t filepos; /* where block starts in file if we have to reload */ + +unsigned short_read_ignore : 1; /* tried to read once and it was corrupt so ignore next time */ +unsigned exclude_block : 1; /* user marked this block off to be ignored */ +unsigned multi_state : 1; /* not just two state value changes */ +unsigned killed : 1; /* we're in vzt_close(), don't grab anymore blocks */ +unsigned ztype : 1; /* 1: gzip, 0: bzip2 */ +unsigned rle : 1; /* set when end < start which says that an rle depack is necessary */ + +pthread_t pth; +pthread_attr_t pth_attr; +pthread_mutex_t mutex; +}; + + +struct vzt_rd_geometry +{ +vztint32_t rows, msb, lsb, flags, len; +}; + + +struct vzt_rd_facname_cache +{ +char *n; +char *bufprev, *bufcurr; + +vztint32_t old_facidx; +}; + + +struct vzt_rd_trace +{ +vztint32_t *rows, *msb, *lsb, *flags, *len, *vindex_offset; + +char *value_current_sector; +char *value_previous_sector; +vztint32_t longest_len; + +vztint32_t total_values; /* number of value index entries in table */ + +char *process_mask; + +void (*value_change_callback)(struct vzt_rd_trace **lt, vztint64_t *time, vztint32_t *facidx, char **value); +void *user_callback_data_pointer; + +vztint8_t granule_size; + +vztint32_t numfacs, numrealfacs, numfacbytes, longestname, zfacnamesize, zfacname_predec_size, zfacgeometrysize; +vztint8_t timescale; + +char *zfacnames; + +unsigned int numblocks; +struct vzt_rd_block *block_head, *block_curr; + +vztint64_t start, end; +struct vzt_rd_geometry geometry; + +struct vzt_rd_facname_cache *faccache; + +char *filename; /* for multithread */ +FILE *handle; +void *zhandle; + +vztint64_t block_mem_consumed, block_mem_max; +pthread_mutex_t mutex; /* for these */ + +int pthreads; /* pthreads are enabled, set to max processor # (starting at zero for a uni) */ +unsigned process_linear : 1; /* set by gtkwave for read optimization */ +}; + + +/* + * VZT Reader API functions... + */ +struct vzt_rd_trace * vzt_rd_init(const char *name); +struct vzt_rd_trace * vzt_rd_init_smp(const char *name, unsigned int num_cpus); +void vzt_rd_close(struct vzt_rd_trace *lt); + +_VZT_RD_INLINE vztint64_t vzt_rd_set_max_block_mem_usage(struct vzt_rd_trace *lt, vztint64_t block_mem_max); +_VZT_RD_INLINE vztint64_t vzt_rd_get_block_mem_usage(struct vzt_rd_trace *lt); +_VZT_RD_INLINE unsigned int vzt_rd_get_num_blocks(struct vzt_rd_trace *lt); +unsigned int vzt_rd_get_num_active_blocks(struct vzt_rd_trace *lt); + +_VZT_RD_INLINE vztint32_t vzt_rd_get_num_facs(struct vzt_rd_trace *lt); +char * vzt_rd_get_facname(struct vzt_rd_trace *lt, vztint32_t facidx); +struct vzt_rd_geometry * vzt_rd_get_fac_geometry(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_rows(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_msb(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_lsb(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_flags(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE vztint32_t vzt_rd_get_fac_len(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE vztint32_t vzt_rd_get_alias_root(struct vzt_rd_trace *lt, vztint32_t facidx); + +_VZT_RD_INLINE char vzt_rd_get_timescale(struct vzt_rd_trace *lt); +_VZT_RD_INLINE vztint64_t vzt_rd_get_start_time(struct vzt_rd_trace *lt); +_VZT_RD_INLINE vztint64_t vzt_rd_get_end_time(struct vzt_rd_trace *lt); + +_VZT_RD_INLINE int vzt_rd_get_fac_process_mask(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE int vzt_rd_set_fac_process_mask(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE int vzt_rd_clr_fac_process_mask(struct vzt_rd_trace *lt, vztint32_t facidx); +_VZT_RD_INLINE int vzt_rd_set_fac_process_mask_all(struct vzt_rd_trace *lt); +_VZT_RD_INLINE int vzt_rd_clr_fac_process_mask_all(struct vzt_rd_trace *lt); + + /* null value_change_callback calls an empty dummy function */ +int vzt_rd_iter_blocks(struct vzt_rd_trace *lt, + void (*value_change_callback)(struct vzt_rd_trace **lt, vztint64_t *time, vztint32_t *facidx, char **value), + void *user_callback_data_pointer); +_VZT_RD_INLINE void * vzt_rd_get_user_callback_data_pointer(struct vzt_rd_trace *lt); +void vzt_rd_process_blocks_linearly(struct vzt_rd_trace *lt, int doit); + + /* time (un)/restricted read ops */ +unsigned int vzt_rd_limit_time_range(struct vzt_rd_trace *lt, vztint64_t strt_time, vztint64_t end_time); +unsigned int vzt_rd_unlimit_time_range(struct vzt_rd_trace *lt); + +#endif diff --git a/src/helpers/vzt_write.c b/src/helpers/vzt_write.c new file mode 100644 index 0000000..d712d22 --- /dev/null +++ b/src/helpers/vzt_write.c @@ -0,0 +1,1914 @@ +/* + * Copyright (c) 2003-2005 Tony Bybell. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __CYGWIN__ +#include +#include +#endif +#include "vzt_write.h" + +/* + * gz/bz2 calls + */ +static _VZT_WR_INLINE void *vzt_gzdopen(struct vzt_wr_trace *lt, int fd, const char *mode) +{ +if(lt) + { + lt->ztype = lt->ztype_cfg; /* shadow config at file open */ + + if(!lt->ztype) + { + return(gzdopen(fd, mode)); + } + else + { + return(BZ2_bzdopen(fd, mode)); + } + } +} + +static _VZT_WR_INLINE int vzt_gzclose(struct vzt_wr_trace *lt, void *file) +{ +if(lt) + { + if(!lt->ztype) + { + return(gzclose(file)); + } + else + { + BZ2_bzclose(file); + return(0); + } + } +} + +static _VZT_WR_INLINE int vzt_gzflush(struct vzt_wr_trace *lt, void *file, int flush) +{ +if(lt) + { + if(!lt->ztype) + { + return(gzflush(file, flush)); + } + else + { + return(BZ2_bzflush(file)); + } + } +} + +static _VZT_WR_INLINE int vzt_gzwrite(struct vzt_wr_trace *lt, void *file, void* buf, unsigned len) +{ +if(lt) + { + if(!lt->ztype) + { + return(gzwrite(file, buf, len)); + } + else + { + return(BZ2_bzwrite(file, buf, len)); + } + } +} + + +/************************ splay ************************/ + +static _VZT_WR_INLINE int cmp_l(vztint32_t i, vztint32_t j) +{ +return((i != j) - ((i < j) << 1)); +} + +static int vzt_wr_dsvzt_success; + +static vzt_wr_dsvzt_Tree * vzt_wr_dsvzt_splay (vztint32_t i, vzt_wr_dsvzt_Tree * t) { +/* Simple top down splay, not requiring i to be in the tree t. */ +/* What it does is described above. */ + vzt_wr_dsvzt_Tree N, *l, *r, *y; + int dir; + + vzt_wr_dsvzt_success = 0; + + if (t == NULL) return t; + N.left = N.right = NULL; + l = r = &N; + + for (;;) { + dir = cmp_l(i, t->item); + if (dir < 0) { + if (t->left == NULL) break; + if (cmp_l(i, t->left->item)<0) { + y = t->left; /* rotate right */ + t->left = y->right; + y->right = t; + t = y; + if (t->left == NULL) break; + } + r->left = t; /* link right */ + r = t; + t = t->left; + } else if (dir > 0) { + if (t->right == NULL) break; + if (cmp_l(i, t->right->item)>0) { + y = t->right; /* rotate left */ + t->right = y->left; + y->left = t; + t = y; + if (t->right == NULL) break; + } + l->right = t; /* link left */ + l = t; + t = t->right; + } else { + vzt_wr_dsvzt_success=1; + break; + } + } + l->right = t->left; /* assemble */ + r->left = t->right; + t->left = N.right; + t->right = N.left; + return t; +} + + +static vzt_wr_dsvzt_Tree * vzt_wr_dsvzt_insert(vztint32_t i, vzt_wr_dsvzt_Tree * t, vztint32_t val) { +/* Insert i into the tree t, unless it's already there. */ +/* Return a pointer to the resulting tree. */ + vzt_wr_dsvzt_Tree * n; + int dir; + + n = (vzt_wr_dsvzt_Tree *) calloc (1, sizeof (vzt_wr_dsvzt_Tree)); + if (n == NULL) { + fprintf(stderr, "dsvzt_insert: ran out of memory, exiting.\n"); + exit(255); + } + n->item = i; + n->val = val; + if (t == NULL) { + n->left = n->right = NULL; + return n; + } + t = vzt_wr_dsvzt_splay(i,t); + dir = cmp_l(i,t->item); + if (dir<0) { + n->left = t->left; + n->right = t; + t->left = NULL; + return n; + } else if (dir>0) { + n->right = t->right; + n->left = t; + t->right = NULL; + return n; + } else { /* We get here if it's already in the tree */ + /* Don't add it again */ + free(n); + return t; + } +} + +/************************ splay ************************/ + +static int vzt2_wr_dsvzt_success; + +static vzt2_wr_dsvzt_Tree * vzt2_wr_dsvzt_splay (char *i, vzt2_wr_dsvzt_Tree * t) { +/* Simple top down splay, not requiring i to be in the tree t. */ +/* What it does is described above. */ + vzt2_wr_dsvzt_Tree N, *l, *r, *y; + int dir; + + vzt2_wr_dsvzt_success = 0; + + if (t == NULL) return t; + N.left = N.right = NULL; + l = r = &N; + + for (;;) { + dir = strcmp(i, t->item); + if (dir < 0) { + if (t->left == NULL) break; + if (strcmp(i, t->left->item)<0) { + y = t->left; /* rotate right */ + t->left = y->right; + y->right = t; + t = y; + if (t->left == NULL) break; + } + r->left = t; /* link right */ + r = t; + t = t->left; + } else if (dir > 0) { + if (t->right == NULL) break; + if (strcmp(i, t->right->item)>0) { + y = t->right; /* rotate left */ + t->right = y->left; + y->left = t; + t = y; + if (t->right == NULL) break; + } + l->right = t; /* link left */ + l = t; + t = t->right; + } else { + vzt2_wr_dsvzt_success=1; + break; + } + } + l->right = t->left; /* assemble */ + r->left = t->right; + t->left = N.right; + t->right = N.left; + return t; +} + + +static vzt2_wr_dsvzt_Tree * vzt2_wr_dsvzt_insert(char *i, vzt2_wr_dsvzt_Tree * t, unsigned int val) { +/* Insert i into the tree t, unless it's already there. */ +/* Return a pointer to the resulting tree. */ + vzt2_wr_dsvzt_Tree * n; + int dir; + + n = (vzt2_wr_dsvzt_Tree *) calloc (1, sizeof (vzt2_wr_dsvzt_Tree)); + if (n == NULL) { + fprintf(stderr, "dsvzt_insert: ran out of memory, exiting.\n"); + exit(255); + } + n->item = i; + n->val = val; + if (t == NULL) { + n->left = n->right = NULL; + return n; + } + t = vzt2_wr_dsvzt_splay(i,t); + dir = strcmp(i,t->item); + if (dir<0) { + n->left = t->left; + n->right = t; + t->left = NULL; + return n; + } else if (dir>0) { + n->right = t->right; + n->left = t; + t->right = NULL; + return n; + } else { /* We get here if it's already in the tree */ + /* Don't add it again */ + free(n); + return t; + } +} + +/************************ splay ************************/ + +/* + * functions which emit various big endian + * data to a file + */ +static int vzt_wr_emit_u8(struct vzt_wr_trace *lt, int value) +{ +unsigned char buf[1]; +int nmemb; + +buf[0] = value & 0xff; +nmemb=fwrite(buf, sizeof(char), 1, lt->handle); +lt->position+=nmemb; +return(nmemb); +} + + +static int vzt_wr_emit_u16(struct vzt_wr_trace *lt, int value) +{ +unsigned char buf[2]; +int nmemb; + +buf[0] = (value>>8) & 0xff; +buf[1] = value & 0xff; +nmemb = fwrite(buf, sizeof(char), 2, lt->handle); +lt->position+=nmemb; +return(nmemb); +} + + +static int vzt_wr_emit_u32(struct vzt_wr_trace *lt, int value) +{ +unsigned char buf[4]; +int nmemb; + +buf[0] = (value>>24) & 0xff; +buf[1] = (value>>16) & 0xff; +buf[2] = (value>>8) & 0xff; +buf[3] = value & 0xff; +nmemb=fwrite(buf, sizeof(char), 4, lt->handle); +lt->position+=nmemb; +return(nmemb); +} + + +static int vzt_wr_emit_u64(struct vzt_wr_trace *lt, int valueh, int valuel) +{ +int rc; + +if((rc=vzt_wr_emit_u32(lt, valueh))) + { + rc=vzt_wr_emit_u32(lt, valuel); + } + +return(rc); +} + + +/* + * gzfunctions which emit various big endian + * data to a file. (lt->position needs to be + * fixed up on gzclose so the tables don't + * get out of sync!) + */ +static int gzwrite_buffered(struct vzt_wr_trace *lt) +{ +int rc = 1; + +if(lt->gzbufpnt > VZT_WR_GZWRITE_BUFFER) + { + rc = vzt_gzwrite(lt, lt->zhandle, lt->gzdest, lt->gzbufpnt); + rc = rc ? 1 : 0; + lt->gzbufpnt = 0; + } + +return(rc); +} + +static void gzflush_buffered(struct vzt_wr_trace *lt, int doclose) +{ +if(lt->gzbufpnt) + { + vzt_gzwrite(lt, lt->zhandle, lt->gzdest, lt->gzbufpnt); + lt->gzbufpnt = 0; + if(!doclose) + { + vzt_gzflush(lt, lt->zhandle, Z_SYNC_FLUSH); + } + } + +if(doclose) + { + vzt_gzclose(lt, lt->zhandle); + } +} + + +static int vzt_wr_emit_u8z(struct vzt_wr_trace *lt, int value) +{ +int nmemb; + +lt->gzdest[lt->gzbufpnt++] = value & 0xff; + +nmemb=gzwrite_buffered(lt); +lt->zpackcount++; +lt->position++; +return(nmemb); +} + + +static int vzt_wr_emit_u16z(struct vzt_wr_trace *lt, int value) +{ +int nmemb; + +lt->gzdest[lt->gzbufpnt++] = (value>>8) & 0xff; +lt->gzdest[lt->gzbufpnt++] = value & 0xff; +nmemb = gzwrite_buffered(lt); +lt->zpackcount+=2; +lt->position+=2; +return(nmemb); +} + + +static int vzt_wr_emit_u32z(struct vzt_wr_trace *lt, int value) +{ +int nmemb; + +lt->gzdest[lt->gzbufpnt++] = (value>>24) & 0xff; +lt->gzdest[lt->gzbufpnt++] = (value>>16) & 0xff; +lt->gzdest[lt->gzbufpnt++] = (value>>8) & 0xff; +lt->gzdest[lt->gzbufpnt++] = value & 0xff; +nmemb=gzwrite_buffered(lt); + +lt->zpackcount+=4; +lt->position+=4; +return(nmemb); +} + +static int vzt_wr_emit_u32rz(struct vzt_wr_trace *lt, int value) +{ +int nmemb; + +lt->gzdest[lt->gzbufpnt++] = value & 0xff; +lt->gzdest[lt->gzbufpnt++] = (value>>8) & 0xff; +lt->gzdest[lt->gzbufpnt++] = (value>>16) & 0xff; +lt->gzdest[lt->gzbufpnt++] = (value>>24) & 0xff; +nmemb=gzwrite_buffered(lt); + +lt->zpackcount+=4; +lt->position+=4; +return(nmemb); +} + + +static int vzt_wr_emit_u64z(struct vzt_wr_trace *lt, int valueh, int valuel) +{ +int rc; + +if((rc=vzt_wr_emit_u32z(lt, valueh))) + { + rc=vzt_wr_emit_u32z(lt, valuel); + } + +return(rc); +} + + +static int vzt_wr_emit_stringz(struct vzt_wr_trace *lt, char *value) +{ +int rc=1; +do + { + rc&=vzt_wr_emit_u8z(lt, *value); + } while(*(value++)); +return(rc); +} + + +static int vzt_wr_emit_uv32z(struct vzt_wr_trace *lt, unsigned int v) +{ +int nmemb; +unsigned int nxt; +unsigned int oldpnt = lt->gzbufpnt; + +while((nxt = v>>7)) + { + lt->gzdest[lt->gzbufpnt++] = (v&0x7f); + v = nxt; + } +lt->gzdest[lt->gzbufpnt++] = (v&0x7f) | 0x80; + +lt->zpackcount+=(lt->gzbufpnt - oldpnt); +lt->position+=(lt->gzbufpnt - oldpnt); +nmemb=gzwrite_buffered(lt); + +return(nmemb); +} + +static int vzt_wr_emit_uv64z(struct vzt_wr_trace *lt, unsigned long long v) +{ +int nmemb; +unsigned long long nxt; +unsigned int oldpnt = lt->gzbufpnt; + +while((nxt = v>>7)) + { + lt->gzdest[lt->gzbufpnt++] = (v&0x7f); + v = nxt; + } +lt->gzdest[lt->gzbufpnt++] = (v&0x7f) | 0x80; + +lt->zpackcount+=(lt->gzbufpnt - oldpnt); +lt->position+=(lt->gzbufpnt - oldpnt); +nmemb=gzwrite_buffered(lt); + +return(nmemb); +} + + + + +/* + * hash/symtable manipulation + */ +static int vzt_wr_hash(const char *s) +{ +const char *p; +char ch; +unsigned int h=0, h2=0, pos=0, g; +for(p=s;*p;p++) + { + ch=*p; + h2<<=3; + h2-=((unsigned int)ch+(pos++)); /* this handles stranded vectors quite well.. */ + + h=(h<<4)+ch; + if((g=h&0xf0000000)) + { + h=h^(g>>24); + h=h^g; + } + } + +h^=h2; /* combine the two hashes */ +return(h%VZT_WR_SYMPRIME); +} + + +static struct vzt_wr_symbol *vzt_wr_symadd(struct vzt_wr_trace *lt, const char *name, int hv) +{ +struct vzt_wr_symbol *s; + +s=(struct vzt_wr_symbol *)calloc(1,sizeof(struct vzt_wr_symbol)); +strcpy(s->name=(char *)malloc((s->namlen=strlen(name))+1),name); +s->next=lt->sym[hv]; +lt->sym[hv]=s; +return(s); +} + + +static struct vzt_wr_symbol *vzt_wr_symfind(struct vzt_wr_trace *lt, const char *s) +{ +int hv; +struct vzt_wr_symbol *temp; + +hv=vzt_wr_hash(s); +if(!(temp=lt->sym[hv])) return(NULL); /* no hash entry, add here wanted to add */ + +while(temp) + { + if(!strcmp(temp->name,s)) + { + return(temp); /* in table already */ + } + if(!temp->next) break; + temp=temp->next; + } + +return(NULL); /* not found, add here if you want to add*/ +} + + +/* + * compress facs to a prefix count + string + 0x00 + */ +static void vzt_wr_compress_fac(struct vzt_wr_trace *lt, char *str) +{ +int i; +int len = strlen(str); +int minlen = (lencompress_fac_len) ? len : lt->compress_fac_len; + +if(minlen>65535) minlen=65535; /* keep in printable range--most hierarchies won't be this big anyway */ + +if(lt->compress_fac_str) + { + for(i=0;icompress_fac_str[i]!=str[i]) break; + } + vzt_wr_emit_u16z(lt, i); + vzt_wr_emit_stringz(lt, str+i); + free(lt->compress_fac_str); + } + else + { + vzt_wr_emit_u16z(lt, 0); + vzt_wr_emit_stringz(lt, str); + } + +lt->compress_fac_str = (char *) malloc((lt->compress_fac_len=len)+1); +strcpy(lt->compress_fac_str, str); +} + + +/* + * emit facs in sorted order along with geometry + * and sync table info + */ +static int vzt_wr_compare(const void *v1, const void *v2) +{ +struct vzt_wr_symbol *s1 = *(struct vzt_wr_symbol **)v1; +struct vzt_wr_symbol *s2 = *(struct vzt_wr_symbol **)v2; +int rc = strcmp(s1->name, s2->name); +if(rc) + { + return(rc); + } + else + { + return(s1->msb - s2->msb); + } +} + + +static void strip_brack(struct vzt_wr_symbol *s) +{ +char *lastch = s->name+s->namlen - 1; +if(*lastch!=']') return; +if(s->namlen<3) return; +lastch--; +while(lastch!=s->name) + { + if(*lastch=='[') + { + *lastch=0x00; + return; + } + lastch--; + } +return; +} + + +static void vzt_wr_emitfacs(struct vzt_wr_trace *lt) +{ +int i; + +if((lt)&&(lt->numfacs)) + { + struct vzt_wr_symbol *s = lt->symchain; + struct vzt_wr_symbol **aliascache = calloc(lt->numalias ? lt->numalias : 1, sizeof(struct vzt_wr_symbol *)); + int aliases_encountered, facs_encountered; + + lt->sorted_facs = (struct vzt_wr_symbol **)calloc(lt->numfacs, sizeof(struct vzt_wr_symbol *)); + + if(lt->sorted_facs && aliascache) + { + if(lt->do_strip_brackets) + for(i=0;inumfacs;i++) + { + lt->sorted_facs[i] = s; + strip_brack(s); + s=s->symchain; + } + else + for(i=0;inumfacs;i++) + { + lt->sorted_facs[i] = s; + s=s->symchain; + } + qsort((void *)lt->sorted_facs, lt->numfacs, sizeof(struct vzt_wr_symbol *), vzt_wr_compare); + + /* move facs up */ + aliases_encountered = 0, facs_encountered = 0; + for(i=0;inumfacs;i++) + { + if((lt->sorted_facs[i]->flags&VZT_WR_SYM_F_ALIAS)==0) + { + lt->sorted_facs[facs_encountered] = lt->sorted_facs[i]; + facs_encountered++; + } + else + { + aliascache[aliases_encountered] = lt->sorted_facs[i]; + aliases_encountered++; + } + } + /* then append the aliases */ + for(i=0;isorted_facs[facs_encountered+i] = aliascache[i]; + } + + + for(i=0;inumfacs;i++) + { + lt->sorted_facs[i]->facnum = i; + } + + lt->facname_offset=lt->position; + + vzt_wr_emit_u32(lt, lt->numfacs); /* uncompressed */ + vzt_wr_emit_u32(lt, lt->numfacbytes); /* uncompressed */ + vzt_wr_emit_u32(lt, lt->longestname); /* uncompressed */ + vzt_wr_emit_u32(lt, 0); /* uncompressed : placeholder for zfacnamesize */ + vzt_wr_emit_u32(lt, 0); /* uncompressed : placeholder for zfacname_predec_size */ + vzt_wr_emit_u32(lt, 0); /* uncompressed : placeholder for zfacgeometrysize */ + vzt_wr_emit_u8(lt, lt->timescale); /* timescale (-9 default == nsec) */ + + fflush(lt->handle); + lt->zfacname_size = lt->position; + lt->zhandle = vzt_gzdopen(lt, dup(fileno(lt->handle)), "wb9"); + + lt->zpackcount = 0; + for(i=0;inumfacs;i++) + { + vzt_wr_compress_fac(lt, lt->sorted_facs[i]->name); + free(lt->sorted_facs[i]->name); + lt->sorted_facs[i]->name = NULL; + } + free(lt->compress_fac_str); lt->compress_fac_str=NULL; + lt->compress_fac_len=0; + lt->zfacname_predec_size = lt->zpackcount; + + gzflush_buffered(lt, 1); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); + lt->zfacname_size = lt->position - lt->zfacname_size; + + lt->zhandle = vzt_gzdopen(lt, dup(fileno(lt->handle)), "wb9"); + + lt->facgeometry_offset = lt->position; + for(i=0;inumfacs;i++) + { + if((lt->sorted_facs[i]->flags&VZT_WR_SYM_F_ALIAS)==0) + { + vzt_wr_emit_u32z(lt, lt->sorted_facs[i]->rows); + vzt_wr_emit_u32z(lt, lt->sorted_facs[i]->msb); + vzt_wr_emit_u32z(lt, lt->sorted_facs[i]->lsb); + vzt_wr_emit_u32z(lt, lt->sorted_facs[i]->flags); + } + else + { + vzt_wr_emit_u32z(lt, lt->sorted_facs[i]->aliased_to->facnum); + vzt_wr_emit_u32z(lt, lt->sorted_facs[i]->msb); + vzt_wr_emit_u32z(lt, lt->sorted_facs[i]->lsb); + vzt_wr_emit_u32z(lt, VZT_WR_SYM_F_ALIAS); + } + } + + gzflush_buffered(lt, 1); + fseeko(lt->handle, 0L, SEEK_END); + lt->position=ftello(lt->handle); + lt->break_header_size = lt->position; /* in case we need to emit multiple vzts with same header */ + lt->zfacgeometry_size = lt->position - lt->facgeometry_offset; + + fseeko(lt->handle, lt->facname_offset + 12, SEEK_SET); + vzt_wr_emit_u32(lt, lt->zfacname_size); /* backpatch sizes... */ + vzt_wr_emit_u32(lt, lt->zfacname_predec_size); + vzt_wr_emit_u32(lt, lt->zfacgeometry_size); + + lt->numfacs = facs_encountered; /* don't process alias value changes ever */ + } + + if(aliascache) free(aliascache); + } +} + + +/* + * initialize the trace and get back an lt context + */ +struct vzt_wr_trace *vzt_wr_init(const char *name) +{ +struct vzt_wr_trace *lt=(struct vzt_wr_trace *)calloc(1, sizeof(struct vzt_wr_trace)); + +if((!name)||(!(lt->handle=fopen(name, "wb")))) + { + free(lt); + lt=NULL; + } + else + { + lt->vztname = strdup(name); + + vzt_wr_emit_u16(lt, VZT_WR_HDRID); + vzt_wr_emit_u16(lt, VZT_WR_VERSION); + vzt_wr_emit_u8 (lt, VZT_WR_GRANULE_SIZE); /* currently 32 */ + lt->timescale = -9; + lt->maxgranule = VZT_WR_GRANULE_NUM; + lt->timetable = calloc(lt->maxgranule * VZT_WR_GRANULE_SIZE, sizeof(vzttime_t)); + vzt_wr_set_compression_depth(lt, 4); /* set fast/loose compression depth, user can fix this any time after init */ + lt->initial_value = 'x'; + + lt->multi_state = 1; + } + +return(lt); +} + + +/* + * force trace to two state + */ +void vzt_wr_force_twostate(struct vzt_wr_trace *lt) +{ +if((lt)&&(!lt->symchain)) + { + lt->multi_state = 0; + } +} + + +/* + * setting break size + */ +void vzt_wr_set_break_size(struct vzt_wr_trace *lt, off_t siz) +{ +if(lt) + { + lt->break_size = siz; + } +} + + +/* + * set initial value of trace (0, 1, x, z) only legal vals + */ +void vzt_wr_set_initial_value(struct vzt_wr_trace *lt, char value) +{ +if(lt) + { + switch(value) + { + case '0': + case '1': + case 'x': + case 'z': break; + case 'Z': value = 'z'; break; + default: value = 'x'; break; + } + + lt->initial_value = value; + } +} + + +/* + * maint function for finding a symbol if it exists + */ +struct vzt_wr_symbol *vzt_wr_symbol_find(struct vzt_wr_trace *lt, const char *name) +{ +struct vzt_wr_symbol *s=NULL; + +if((lt)&&(name)) s=vzt_wr_symfind(lt, name); +return(s); +} + + +/* + * add a trace (if it doesn't exist already) + */ +struct vzt_wr_symbol *vzt_wr_symbol_add(struct vzt_wr_trace *lt, const char *name, unsigned int rows, int msb, int lsb, int flags) +{ +struct vzt_wr_symbol *s; +int i, len; +int flagcnt; + +if((!lt)||(lt->sorted_facs)) return(NULL); + +flagcnt = ((flags&VZT_WR_SYM_F_INTEGER)!=0) + ((flags&VZT_WR_SYM_F_DOUBLE)!=0) + ((flags&VZT_WR_SYM_F_STRING)!=0); + +if((flagcnt>1)||(!lt)||(!name)||(vzt_wr_symfind(lt, name))) return (NULL); + +if(!(flags & (VZT_WR_SYM_F_INTEGER|VZT_WR_SYM_F_STRING|VZT_WR_SYM_F_DOUBLE))) + { + len = (msbrows = rows; +s->flags = flags&(~VZT_WR_SYM_F_ALIAS); /* aliasing makes no sense here.. */ + +s->prev = (vzt_wr_dsvzt_Tree **)calloc(len, sizeof(vzt_wr_dsvzt_Tree *)); +s->chg = (vztint32_t *)calloc(len, sizeof(vztint32_t)); + +if(lt->multi_state) + { + s->prevx = (vzt_wr_dsvzt_Tree **)calloc(len, sizeof(vzt_wr_dsvzt_Tree *)); + s->chgx = (vztint32_t *)calloc(len, sizeof(vztint32_t)); + } + +if(!flagcnt) + { + s->msb = msb; + s->lsb = lsb; + } +s->len = len; + +if(!(flags & (VZT_WR_SYM_F_INTEGER|VZT_WR_SYM_F_STRING|VZT_WR_SYM_F_DOUBLE))) + { + if((lt->initial_value == '1')||(lt->initial_value == 'z')) + { + for(i=0;ilen;i++) + { + s->chg[i] = ~0; + } + } + + if(lt->multi_state) + { + if((lt->initial_value == 'x')||(lt->initial_value == 'z')) + { + for(i=0;ilen;i++) + { + s->chgx[i] = ~0; + } + } + } + } + +s->symchain = lt->symchain; +lt->symchain = s; + +lt->numfacs++; + +if((len=strlen(name)) > lt->longestname) lt->longestname = len; +lt->numfacbytes += (len+1); + +return(s); +} + +/* + * add an alias trace (if it doesn't exist already and orig is found) + */ +struct vzt_wr_symbol *vzt_wr_symbol_alias(struct vzt_wr_trace *lt, const char *existing_name, const char *alias, int msb, int lsb) +{ +struct vzt_wr_symbol *s, *sa; +int len; +int bitlen; +int flagcnt; + +if((!lt)||(!existing_name)||(!alias)||(!(s=vzt_wr_symfind(lt, existing_name)))||(vzt_wr_symfind(lt, alias))) return (NULL); + +if(lt->sorted_facs) return(NULL); + +while(s->aliased_to) /* find root alias */ + { + s=s->aliased_to; + } + +flagcnt = ((s->flags&VZT_WR_SYM_F_INTEGER)!=0) + ((s->flags&VZT_WR_SYM_F_DOUBLE)!=0) + ((s->flags&VZT_WR_SYM_F_STRING)!=0); +bitlen = (msblen)) return(NULL); + +sa=vzt_wr_symadd(lt, alias, vzt_wr_hash(alias)); +sa->flags = VZT_WR_SYM_F_ALIAS; /* only point this can get set */ +sa->aliased_to = s; + +if(!flagcnt) + { + sa->msb = msb; + sa->lsb = lsb; + sa->len = bitlen; + } + +sa->symchain = lt->symchain; +lt->symchain = sa; +lt->numfacs++; +lt->numalias++; +if((len=strlen(alias)) > lt->longestname) lt->longestname = len; +lt->numfacbytes += (len+1); + +return(sa); +} + + +/* + * set current time/granule updating + */ +int vzt_wr_inc_time_by_delta(struct vzt_wr_trace *lt, unsigned int timeval) +{ +return(vzt_wr_set_time64(lt, lt->maxtime + (vzttime_t)timeval)); +} + +int vzt_wr_set_time(struct vzt_wr_trace *lt, unsigned int timeval) +{ +return(vzt_wr_set_time64(lt, (vzttime_t)timeval)); +} + +int vzt_wr_inc_time_by_delta64(struct vzt_wr_trace *lt, vzttime_t timeval) +{ +return(vzt_wr_set_time64(lt, lt->maxtime + timeval)); +} + + +/* + * file size limiting/header cloning... + */ +static void vzt_wr_emit_do_breakfile(struct vzt_wr_trace *lt) +{ +unsigned int len = strlen(lt->vztname); +int i; +char *tname = malloc(len + 30); +FILE *f2, *clone; +off_t cnt, seg; +char buf[32768]; + +for(i=len;i>0;i--) + { + if(lt->vztname[i]=='.') break; + } + +if(!i) + { + sprintf(tname, "%s_%03d.vzt", lt->vztname, ++lt->break_number); + } + else + { + memcpy(tname, lt->vztname, i); + sprintf(tname+i, "_%03d.vzt", ++lt->break_number); + } + +f2 = fopen(tname, "wb"); +if(!f2) /* if error, keep writing to same output file...sorry */ + { + free(tname); + return; + } + +clone = fopen(lt->vztname, "rb"); +if(!clone) + { /* this should never happen */ + fclose(f2); + unlink(tname); + free(tname); + return; + } + +/* clone original header */ +for(cnt = 0; cnt < lt->break_header_size; cnt += sizeof(buf)) + { + seg = lt->break_header_size - cnt; + if(seg > sizeof(buf)) + { + seg = sizeof(buf); + } + + fread(buf, seg, 1, clone); + fwrite(buf, seg, 1, f2); + } + +fclose(clone); +fclose(lt->handle); +lt->handle = f2; +free(tname); +} + + +static void vzt_wr_recurse_reorder_dict(vzt_wr_dsvzt_Tree *t, struct vzt_wr_trace *lt, vztint32_t *newval, vztint32_t *bpnt, int depth) +{ +int i, j; + +if(t->left) + { + vzt_wr_recurse_reorder_dict(t->left, lt, newval, bpnt, depth); + } + +*bpnt = t->item; + +if(t->child) + { + vzt_wr_recurse_reorder_dict(t->child, lt, newval, bpnt+1, depth+1); + } + else + { + vztint32_t *bpnt2 = bpnt - depth + 1; + t->val = *newval; /* resequence the dict entries in lexical order */ + *newval = *newval+1; + + if(!lt->rle) + { + for(i=0;irle_start; + vztint32_t run = 0; + + lt->rle_start = (*bpnt2) & 1; + + for(i=0;i>= 1; + } + } + + vzt_wr_emit_uv32z(lt, run); + } + } + +if(t->right) + { + vzt_wr_recurse_reorder_dict(t->right, lt, newval, bpnt, depth); + } +} + + +static void vzt_wr_recurse_free_dict(vzt_wr_dsvzt_Tree *t) +{ +if(t->left) + { + vzt_wr_recurse_free_dict(t->left); + } + +if(t->child) + { + vzt_wr_recurse_free_dict(t->child); + } + +if(t->right) + { + vzt_wr_recurse_free_dict(t->right); + } + +free(t); +} + + +/* + * emit granule + */ +void vzt_wr_flush_granule(struct vzt_wr_trace *lt, int do_finalize) +{ +int i, j; +vztsint32_t k; +int val; +int numticks; + +if(!lt->timegranule) + { + vzt_wr_dsvzt_Tree *t=NULL; + + val = 0; + + for(j=0;jnumfacs;j++) + { + struct vzt_wr_symbol *s = lt->sorted_facs[j]; + for(i=0;ilen;i++) + { + t = vzt_wr_dsvzt_splay(s->chg[i], t); + if(!vzt_wr_dsvzt_success) + { + t = vzt_wr_dsvzt_insert(s->chg[i], t, val++); + } + + k = s->chg[i]; + s->chg[i] = k>>31; + + s->prev[i] = t; + } + } + + if(lt->multi_state) + for(j=0;jnumfacs;j++) + { + struct vzt_wr_symbol *s = lt->sorted_facs[j]; + for(i=0;ilen;i++) + { + lt->use_multi_state |= s->chgx[i]; + t = vzt_wr_dsvzt_splay(s->chgx[i], t); + if(!vzt_wr_dsvzt_success) + { + t = vzt_wr_dsvzt_insert(s->chgx[i], t, val++); + } + + k = s->chgx[i]; + s->chgx[i] = k>>31; + + s->prevx[i] = t; + } + } + + lt->dict = t; + } + else + { + vzt_wr_dsvzt_Tree *t; + + val = 0; + + for(j=0;jnumfacs;j++) + { + struct vzt_wr_symbol *s = lt->sorted_facs[j]; + for(i=0;ilen;i++) + { + t = s->prev[i]->child; + t = vzt_wr_dsvzt_splay(s->chg[i], t); + if(!vzt_wr_dsvzt_success) + { + t = vzt_wr_dsvzt_insert(s->chg[i], t, val++); + } + + k = s->chg[i]; + s->chg[i] = k>>31; + + s->prev[i]->child = t; + s->prev[i] = t; + } + } + + if(lt->multi_state) + for(j=0;jnumfacs;j++) + { + struct vzt_wr_symbol *s = lt->sorted_facs[j]; + for(i=0;ilen;i++) + { + t = s->prevx[i]->child; + lt->use_multi_state |= s->chgx[i]; + t = vzt_wr_dsvzt_splay(s->chgx[i], t); + if(!vzt_wr_dsvzt_success) + { + t = vzt_wr_dsvzt_insert(s->chgx[i], t, val++); + } + + k = s->chgx[i]; + s->chgx[i] = k>>31; + + s->prevx[i]->child = t; + s->prevx[i] = t; + } + } + } + + +numticks = lt->timegranule * VZT_WR_GRANULE_SIZE + lt->timepos; +lt->timepos = 0; +lt->timegranule++; +if((lt->timegranule >= lt->maxgranule)||(do_finalize)) + { + off_t clen, unclen; + vztint32_t newval = 0; + int attempt_break_state = 2; + + do { + fseeko(lt->handle, 0L, SEEK_END); + lt->current_chunk=lt->position = ftello(lt->handle); + + if((lt->break_size)&&(attempt_break_state==2)&&(lt->position >= lt->break_size)&&(lt->position != lt->break_header_size)) + { + vzt_wr_emit_do_breakfile(lt); + attempt_break_state--; + } + else + { + attempt_break_state = 0; + } + } while(attempt_break_state); + + /* flush everything here */ + fseeko(lt->handle, 0L, SEEK_END); + lt->current_chunk=lt->position = ftello(lt->handle); + vzt_wr_emit_u32(lt, 0); /* size of this section (uncompressed) */ + vzt_wr_emit_u32(lt, 0); /* size of this section (compressed) */ + vzt_wr_emit_u64(lt, 0, 0); /* begin time of section */ + vzt_wr_emit_u64(lt, 0, 0); /* end time of section */ + fflush(lt->handle); + lt->current_chunkz = lt->position; + + lt->zhandle = vzt_gzdopen(lt, dup(fileno(lt->handle)), lt->zmode); + lt->zpackcount = 0; + + if((lt->lasttime - lt->firsttime + 1) == numticks) + { + vzt_wr_emit_uv32z(lt, 0); /* special case for cycle simulation */ + } + else + { + vzt_wr_emit_uv32z(lt, numticks); /* number of time ticks */ + for(i=0;itimetable[i] - lt->timetable[i-1] : lt->timetable[i]); /* emit delta */ + } + gzflush_buffered(lt, 0); + } + + vzt_wr_emit_uv32z(lt, lt->timegranule); /* number of 32-bit sections */ + lt->timegranule = 0; + + vzt_wr_emit_uv32z(lt, val); /* number of dict entries */ + while((lt->zpackcount & 3) != 0) + { + vzt_wr_emit_u8z(lt, 0); /* pad to word boundary for machines which need aligned data on reads */ + } + + { + vztint32_t buf[lt->maxgranule]; + memset(buf, 0, lt->maxgranule * sizeof(vztint32_t)); + if(lt->rle) lt->rle_start = 0; + vzt_wr_recurse_reorder_dict(lt->dict, lt, &newval, buf, 1); + } + gzflush_buffered(lt, 0); + + vzt_wr_emit_u8z(lt, (lt->multi_state)&&(lt->use_multi_state)); /* indicates number of bitplanes past twostate */ + while((lt->zpackcount & 3) != 0) + { + vzt_wr_emit_u8z(lt, 0); /* pad to word boundary for machines which need aligned data on reads */ + } + + for(j=0;jnumfacs;j++) + { + struct vzt_wr_symbol *s = lt->sorted_facs[j]; + for(i=0;ilen;i++) + { + vzt_wr_emit_u32rz(lt, s->prev[i]->val); + } + } + + if((lt->multi_state)&&(lt->use_multi_state)) + { + for(j=0;jnumfacs;j++) + { + struct vzt_wr_symbol *s = lt->sorted_facs[j]; + for(i=0;ilen;i++) + { + vzt_wr_emit_u32rz(lt, s->prevx[i]->val); + } + } + lt->use_multi_state = 0; + } + gzflush_buffered(lt, 0); + + vzt_wr_emit_uv32z(lt, lt->numstrings); + if(lt->numstrings) + { + vzt2_wr_dsvzt_Tree *ds, *ds2; + ds = lt->str_head; + for(i=0;inumstrings;i++) + { + /* fprintf(stderr, "%8d %8d) '%s'\n", ds->val, i, ds->item); */ + if(ds->val != i) + { + fprintf(stderr, "internal error line %d\n", __LINE__); + exit(255); + } + + vzt_wr_emit_stringz(lt, ds->item); + ds2 = ds->next; + free(ds->item); + free(ds); + ds = ds2; + } + lt->str_head = lt->str_curr = lt->str = NULL; + lt->numstrings = 0; + } + gzflush_buffered(lt, 1); + + fseeko(lt->handle, 0L, SEEK_END); + lt->position = ftello(lt->handle); + unclen = lt->zpackcount; + clen = lt->position - lt->current_chunkz; + fseeko(lt->handle, lt->current_chunk, SEEK_SET); + vzt_wr_emit_u32(lt, unclen); /* size of this section (uncompressed) */ + vzt_wr_emit_u32(lt, clen); /* size of this section (compressed) */ + + if(!lt->rle) + { + vzt_wr_emit_u64(lt, (lt->firsttime >> 32) & 0xffffffffL, lt->firsttime & 0xffffffffL); /* begin time */ + vzt_wr_emit_u64(lt, (lt->lasttime >> 32) & 0xffffffffL, lt->lasttime & 0xffffffffL); /* end time */ + } + else /* inverted time is the marker the reader needs to look at to see that RLE is used */ + { + vzt_wr_emit_u64(lt, (lt->lasttime >> 32) & 0xffffffffL, lt->lasttime & 0xffffffffL); /* end time */ + vzt_wr_emit_u64(lt, (lt->firsttime >> 32) & 0xffffffffL, lt->firsttime & 0xffffffffL); /* begin time */ + } + fflush(lt->handle); + + vzt_wr_recurse_free_dict(lt->dict); + lt->dict = NULL; + } +} + + +int vzt_wr_set_time64(struct vzt_wr_trace *lt, vzttime_t timeval) +{ +int rc=0; + +if(lt) + { + if(lt->timeset) + { + if(timeval > lt->maxtime) + { + if(lt->bumptime) + { + lt->bumptime = 0; + + if(!lt->flush_valid) + { + lt->timepos++; + } + else + { + lt->flush_valid = 0; + } + + if(lt->timepos == VZT_WR_GRANULE_SIZE) + { + vzt_wr_flush_granule(lt, 0); + } + } + + lt->timetable[lt->timepos + lt->timegranule * VZT_WR_GRANULE_SIZE] = timeval; + lt->lasttime = timeval; + } + } + else + { + lt->timeset = 1; + lt->mintime = lt->maxtime = timeval; + + lt->timetable[lt->timepos + lt->timegranule * VZT_WR_GRANULE_SIZE] = timeval; + } + + if( (!lt->timepos) && (!lt->timegranule) ) + { + lt->firsttime = timeval; + lt->lasttime = timeval; + } + + lt->granule_dirty = 1; + rc = 1; + } + +return(rc); +} + + +/* + * sets trace timescale as 10**x seconds + */ +void vzt_wr_set_timescale(struct vzt_wr_trace *lt, int timescale) +{ +if(lt) + { + lt->timescale = timescale; + } +} + + +/* + * set number of granules per section + * (can modify dynamically but size never can decrease) + */ +void vzt_wr_set_maxgranule(struct vzt_wr_trace *lt, unsigned int maxgranule) +{ +if(lt) + { + if(!maxgranule) maxgranule = 8; + if(maxgranule > lt->maxgranule) + { + vzttime_t *t = calloc(maxgranule * VZT_WR_GRANULE_SIZE, sizeof(vzttime_t)); + memcpy(t, lt->timetable, lt->maxgranule * VZT_WR_GRANULE_SIZE * sizeof(vzttime_t)); + free(lt->timetable); lt->timetable = t; + lt->maxgranule = maxgranule; + } + } +} + + +/* + * Sets bracket stripping (useful for VCD conversions of + * bitblasted nets) + */ +void vzt_wr_symbol_bracket_stripping(struct vzt_wr_trace *lt, int doit) +{ +if(lt) + { + lt->do_strip_brackets = (doit!=0); + } +} + + + +static char *vzt_wr_expand_integer_to_bits(unsigned int len, int value) +{ +static char s[33]; +char *p = s; +unsigned int i; + +if(len>32) len=32; + +len--; + +for(i=0;i<=len;i++) + { + *(p++) = '0' | ((value & (1<<(len-i)))!=0); + } +*p = 0; + +return(s); +} + + +int vzt_wr_emit_value_int(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, int value) +{ +int rc=0; + +if((!lt)||(lt->blackout)||(!s)||(row)) return(rc); + +return(vzt_wr_emit_value_bit_string(lt, s, row, vzt_wr_expand_integer_to_bits(s->len, value))); +} + + +int vzt_wr_emit_value_double(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, double value) +{ +char xdrdata[8]; +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __CYGWIN__ +XDR x; +#endif +vztint32_t msk, msk_n; +int i; + +if((!lt)||(lt->blackout)||(!s)||(!(s->flags&VZT_WR_SYM_F_DOUBLE))||(row)) return(0); + +if(!lt->emitted) + { + vzt_wr_emitfacs(lt); + lt->emitted = 1; + + if(!lt->timeset) + { + vzt_wr_set_time(lt, 0); + } + } + +while(s->aliased_to) /* find root alias if exists */ + { + s=s->aliased_to; + } + +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __CYGWIN__ +xdrmem_create(&x, xdrdata, sizeof(xdrdata), XDR_ENCODE); +xdr_double(&x, &value); +#else +/* byte ordering in windows is reverse of XDR (on x86, that is) */ +for(i=0;i<8;i++) + { + xdrdata[i] = ((char *)&value)[7-i]; + } +#endif + +lt->bumptime = 1; + +msk = (~0 << lt->timepos); +msk_n = ~msk; + +for(i=0;ilen;i++) + { + int byte = i/8; + int bit = 7-(i&7); + + s->chg[i] &= msk_n; + if(xdrdata[byte]&(1<chg[i] |= msk; + } + } + +lt->granule_dirty = 1; + +return(1); +} + + +int vzt_wr_emit_value_string(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, char *value) +{ +int rc=0; +int idx; +vztint32_t msk, msk_n; +int i; + +if((!lt)||(lt->blackout)||(!s)||(!value)||(row)) return(rc); + +if(!lt->emitted) + { + vzt_wr_emitfacs(lt); + lt->emitted = 1; + + if(!lt->timeset) + { + vzt_wr_set_time(lt, 0); + } + } + +while(s->aliased_to) /* find root alias if exists */ + { + s=s->aliased_to; + } + +lt->str = vzt2_wr_dsvzt_splay (value, lt->str); + +if(!vzt2_wr_dsvzt_success) + { + char *vcopy = strdup(value); + if(!lt->str_curr) + { + lt->str = vzt2_wr_dsvzt_insert(strdup(""), NULL, lt->numstrings++); /* zeroth string means no value change in future blocks */ + lt->str_head = lt->str_curr = lt->str; + } + + lt->str = vzt2_wr_dsvzt_insert(vcopy, lt->str, lt->numstrings); + lt->str_curr->next = lt->str; + lt->str_curr = lt->str; + + idx = lt->numstrings; + lt->numstrings++; + } + else + { + idx = lt->str->val; + } + + +lt->bumptime = 1; + +msk = (~0 << lt->timepos); +msk_n = ~msk; + +for(i=0;ilen;i++) + { + s->chg[i] &= msk_n; + if(idx & (1 << (s->len - i - 1))) + { + s->chg[i] |= msk; + } + } + +lt->granule_dirty = 1; + +return(rc); +} + + +int vzt_wr_emit_value_bit_string(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, char *value) +{ +int rc=0; +char *vfix; +int valuelen; +int i; +vztint32_t msk, msk_n; + +if((!lt)||(lt->blackout)||(!s)||(!value)||(!*value)||(row)) return(rc); + +if(!lt->emitted) + { + vzt_wr_emitfacs(lt); + lt->emitted = 1; + + if(!lt->timeset) + { + vzt_wr_set_time(lt, 0); + } + } + +while(s->aliased_to) /* find root alias if exists */ + { + s=s->aliased_to; + } + +valuelen = strlen(value); /* ensure string is proper length */ +if(valuelen == s->len) + { + vfix = alloca(s->len+1); + strcpy(vfix, value); + value = vfix; + } + else + { + vfix = alloca(s->len+1); + + if(valuelen < s->len) + { + int lendelta = s->len - valuelen; + memset(vfix, (value[0]!='1') ? value[0] : '0', lendelta); + strcpy(vfix+lendelta, value); + } + else + { + memcpy(vfix, value, s->len); + vfix[s->len] = 0; + } + + value = vfix; + } + +msk = (~0 << lt->timepos); +msk_n = ~msk; + +if(!lt->multi_state) + { + for(i=0;ilen;i++) + { + unsigned char ch = value[i]; + if(ch>'1') + { + ch |= 1; + } + + s->chg[i] &= msk_n; + if(ch&1) + { + s->chg[i] |= msk; + } + } + } + else + { + for(i=0;ilen;i++) + { + /* 0 = 00, 1 = 01, x = 10, z = 11 */ + unsigned char ch = value[i]; + if((ch=='z')||(ch=='Z')) + { + ch |= 1; + } + s->chg[i] &= msk_n; + if(ch&1) + { + s->chg[i] |= msk; + } + + s->chgx[i] &= msk_n; + if(ch>'1') + { + s->chgx[i] |= msk; + } + } + } + +lt->bumptime = 1; +lt->granule_dirty = 1; + +return(rc); +} + + +/* + * dumping control + */ +void vzt_wr_set_dumpoff(struct vzt_wr_trace *lt) +{ +int i, j; +vztint32_t msk, msk_n; + +if(lt) + { + msk = (~0 << lt->timepos); + msk_n = ~msk; + + for(j=0;jnumfacs;j++) + { + struct vzt_wr_symbol *s = lt->sorted_facs[j]; + for(i=0;ilen;i++) + { + s->chg[i] &= msk_n; + } + + if(lt->multi_state) + { + if(!(s->flags & (VZT_WR_SYM_F_INTEGER|VZT_WR_SYM_F_STRING|VZT_WR_SYM_F_DOUBLE))) + { + for(i=0;ilen;i++) + { + s->chgx[i] |= msk; + } + } + } + else + { + for(i=0;ilen;i++) + { + s->chgx[i] &= msk_n; /* simply precautionary: in case someone does assign an int to x */ + } + } + } + + lt->blackout = 1; + } +} + + +void vzt_wr_set_dumpon(struct vzt_wr_trace *lt) +{ +if(lt) + { + lt->blackout = 0; + } +} + + +/* + * flush the trace... + */ +void vzt_wr_flush(struct vzt_wr_trace *lt) +{ +if(lt) + { + if((lt->timegranule)||(lt->timepos > 0)) + { + if(lt->granule_dirty) + { + lt->timepos++; + vzt_wr_flush_granule(lt, 1); + } + } + } +} + + +/* + * close out the trace and fixate it + */ +void vzt_wr_close(struct vzt_wr_trace *lt) +{ +if(lt) + { + if(lt->granule_dirty) + { + lt->timepos++; + vzt_wr_flush_granule(lt, 1); + } + + if(lt->symchain) + { + struct vzt_wr_symbol *s = lt->symchain; + struct vzt_wr_symbol *s2; + + while(s) + { + if(s->name) { free(s->name); } + if(s->prev) { free(s->prev); } + if(s->chg) { free(s->chg); } + if(s->prevx){ free(s->prevx);} + if(s->chgx) { free(s->chgx); } + s2=s->symchain; + free(s); + s=s2; + } + + lt->symchain = NULL; + } + + free(lt->vztname); + free(lt->timetable); + free(lt->sorted_facs); + fclose(lt->handle); + free(lt); + } + +} + +/* + * set compression depth + */ +void vzt_wr_set_compression_depth(struct vzt_wr_trace *lt, unsigned int depth) +{ +if(lt) + { + if(depth > 9) depth = 9; + sprintf(lt->zmode, "wb%d", depth); + } +} + + +/* + * set compression type + */ +void vzt_wr_set_compression_type(struct vzt_wr_trace *lt, unsigned int type) +{ +if(lt) + { + lt->ztype_cfg = (type != 0); + } +} + + +/* + * set rle mode type + */ +void vzt_wr_set_rle(struct vzt_wr_trace *lt, unsigned int mode) +{ +if(lt) + { + lt->rle = (mode != 0); + } +} + + diff --git a/src/helpers/vzt_write.h b/src/helpers/vzt_write.h new file mode 100644 index 0000000..a0ef63b --- /dev/null +++ b/src/helpers/vzt_write.h @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2004-5 Tony Bybell. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#ifndef DEFS_VZTW_H +#define DEFS_VZTW_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#if defined _MSC_VER || defined __MINGW32__ +#define fseeko fseek +#define ftello ftell +#endif + + +#define VZT_WR_HDRID (('V' << 8) + ('Z')) +#define VZT_WR_VERSION (0x0001) + +#define VZT_WR_GRANULE_SIZE (32) +#define VZT_WR_GRANULE_NUM (8) + +#define VZT_WR_GZWRITE_BUFFER 4096 +#define VZT_WR_SYMPRIME 65519 + +#ifndef _MSC_VER +typedef uint8_t vztint8_t; +typedef uint16_t vztint16_t; +typedef uint32_t vztint32_t; +typedef uint64_t vztint64_t; + +typedef int32_t vztsint32_t; +typedef uint64_t vzttime_t; + +#ifndef __MINGW32__ +#define VZT_WR_LLD "%lld" +#else +#define VZT_WR_LLD "%I64d" +#endif +#define VZT_WR_LLDESC(x) x##LL +#define VZT_WR_ULLDESC(x) x##ULL +#else +typedef unsigned __int8 vztint8_t; +typedef unsigned __int16 vztint16_t; +typedef unsigned __int32 vztint32_t; +typedef unsigned __int64 vztint64_t; + +typedef __int32 vztsint32_t; +typedef unsigned __int64 vzttime_t; +#define VZT_WR_LLD "%I64d" +#define VZT_WR_LLDESC(x) x##i64 +#define VZT_WR_ULLDESC(x) x##i64 +#endif + +#ifdef __GNUC__ +#define _VZT_WR_INLINE inline +#else +#define _VZT_WR_INLINE +#endif + + + +/* + * integer splay + */ +typedef struct vzt_wr_dsvzt_tree_node vzt_wr_dsvzt_Tree; +struct vzt_wr_dsvzt_tree_node { + vzt_wr_dsvzt_Tree * left, * right; + vzt_wr_dsvzt_Tree * child; + vztint32_t item; + vztint32_t val; +}; + +/* + * string splay + */ +typedef struct vzt2_wr_dsvzt_tree_node vzt2_wr_dsvzt_Tree; +struct vzt2_wr_dsvzt_tree_node { + vzt2_wr_dsvzt_Tree * left, * right; + char *item; + unsigned int val; + vzt2_wr_dsvzt_Tree * next; +}; + + +struct vzt_wr_trace +{ +FILE *handle; +void *zhandle; + +vzt_wr_dsvzt_Tree *dict; +vzt_wr_dsvzt_Tree *dict_cache; /* for fast malloc/free */ + +int numstrings; +vzt2_wr_dsvzt_Tree *str_head, *str_curr, *str; /* for potential string vchgs */ + +off_t position; +off_t zfacname_predec_size, zfacname_size, zfacgeometry_size; +off_t zpackcount, zpackcount_cumulative; +off_t current_chunk, current_chunkz; + +struct vzt_wr_symbol **sorted_facs; +struct vzt_wr_symbol *symchain; +int numfacs, numalias; +int numfacbytes; +int longestname; + +int numsections, numblock; +off_t facname_offset, facgeometry_offset; + +vzttime_t mintime, maxtime; +unsigned int timegranule; +int timescale; +int timepos; +vzttime_t *timetable; +unsigned int maxgranule; +vzttime_t firsttime, lasttime; + +char *compress_fac_str; +int compress_fac_len; + +vzttime_t flushtime; +unsigned flush_valid : 1; + +unsigned do_strip_brackets : 1; +unsigned emitted : 1; /* gate off change field zmode changes when set */ +unsigned timeset : 1; /* time has been modified from 0..0 */ +unsigned bumptime : 1; /* says that must go to next time position in granule as value change exists for current time */ +unsigned granule_dirty : 1; /* for flushing out final block */ +unsigned blackout : 1; /* blackout on/off */ +unsigned multi_state : 1; /* 2 or 4 state marker */ +unsigned use_multi_state : 1; /* if zero, can shortcut to 2 state */ +unsigned ztype : 1; /* 0: gzip (default), 1: bzip2 */ +unsigned ztype_cfg : 1; /* 0: gzip (default), 1: bzip2 */ +unsigned rle : 1; /* emit rle packed value section */ +unsigned rle_start : 1; /* initial/previous rle value */ + +char initial_value; + +char zmode[4]; /* fills in with "wb0".."wb9" */ +unsigned int gzbufpnt; + +char *vztname; +off_t break_size; +off_t break_header_size; +unsigned int break_number; + +/* larger datasets at end */ +unsigned char gzdest[VZT_WR_GZWRITE_BUFFER + 10]; /* enough for zlib buffering */ +struct vzt_wr_symbol *sym[VZT_WR_SYMPRIME]; +}; + + +struct vzt_wr_symbol +{ +struct vzt_wr_symbol *next; +struct vzt_wr_symbol *symchain; +char *name; +int namlen; + +int facnum; +struct vzt_wr_symbol *aliased_to; + +unsigned int rows; +int msb, lsb; +int len; +int flags; + +vzt_wr_dsvzt_Tree **prev; /* previous chain (for len bits) */ +vztint32_t *chg; /* for len bits */ + +vzt_wr_dsvzt_Tree **prevx; /* previous xchain (for len bits) */ +vztint32_t *chgx; /* for len xbits */ +}; + + +#define VZT_WR_SYM_F_BITS (0) +#define VZT_WR_SYM_F_INTEGER (1<<0) +#define VZT_WR_SYM_F_DOUBLE (1<<1) +#define VZT_WR_SYM_F_STRING (1<<2) +#define VZT_WR_SYM_F_TIME (VZT_WR_SYM_F_STRING) /* user must correctly format this as a string */ +#define VZT_WR_SYM_F_ALIAS (1<<3) + +#define VZT_WR_SYM_F_SIGNED (1<<4) +#define VZT_WR_SYM_F_BOOLEAN (1<<5) +#define VZT_WR_SYM_F_NATURAL ((1<<6)|(VZT_WR_SYM_F_INTEGER)) +#define VZT_WR_SYM_F_POSITIVE ((1<<7)|(VZT_WR_SYM_F_INTEGER)) +#define VZT_WR_SYM_F_CHARACTER (1<<8) + +#define VZT_WR_SYM_F_CONSTANT (1<<9) +#define VZT_WR_SYM_F_VARIABLE (1<<10) +#define VZT_WR_SYM_F_SIGNAL (1<<11) + +#define VZT_WR_SYM_F_IN (1<<12) +#define VZT_WR_SYM_F_OUT (1<<13) +#define VZT_WR_SYM_F_INOUT (1<<14) + +#define VZT_WR_SYM_F_WIRE (1<<15) +#define VZT_WR_SYM_F_REG (1<<16) + + + /* file I/O */ +struct vzt_wr_trace * vzt_wr_init(const char *name); +void vzt_wr_flush(struct vzt_wr_trace *lt); +void vzt_wr_close(struct vzt_wr_trace *lt); + + /* for dealing with very large traces, split into multiple files approximately "siz" in length */ +void vzt_wr_set_break_size(struct vzt_wr_trace *lt, off_t siz); + + /* 0 = gzip, 1 = bzip2 */ +void vzt_wr_set_compression_type(struct vzt_wr_trace *lt, unsigned int type); + + /* 0 = no compression, 9 = best compression, 4 = default */ +void vzt_wr_set_compression_depth(struct vzt_wr_trace *lt, unsigned int depth); + + /* 0 = pure value changes, 1 = rle packed */ +void vzt_wr_set_rle(struct vzt_wr_trace *lt, unsigned int mode); + + /* bitplane depth: must call before adding any facilities */ +void vzt_wr_force_twostate(struct vzt_wr_trace *lt); + + /* facility creation */ +void vzt_wr_set_initial_value(struct vzt_wr_trace *lt, char value); +struct vzt_wr_symbol * vzt_wr_symbol_find(struct vzt_wr_trace *lt, const char *name); +struct vzt_wr_symbol * vzt_wr_symbol_add(struct vzt_wr_trace *lt, const char *name, unsigned int rows, int msb, int lsb, int flags); +struct vzt_wr_symbol * vzt_wr_symbol_alias(struct vzt_wr_trace *lt, const char *existing_name, const char *alias, int msb, int lsb); +void vzt_wr_symbol_bracket_stripping(struct vzt_wr_trace *lt, int doit); + + /* each granule is VZT_WR_GRANULE_SIZE (32) timesteps, default is 8 per section */ +void vzt_wr_set_maxgranule(struct vzt_wr_trace *lt, unsigned int maxgranule); + + /* time ops */ +void vzt_wr_set_timescale(struct vzt_wr_trace *lt, int timescale); +int vzt_wr_set_time(struct vzt_wr_trace *lt, unsigned int timeval); +int vzt_wr_inc_time_by_delta(struct vzt_wr_trace *lt, unsigned int timeval); +int vzt_wr_set_time64(struct vzt_wr_trace *lt, vzttime_t timeval); +int vzt_wr_inc_time_by_delta64(struct vzt_wr_trace *lt, vzttime_t timeval); + + /* allows blackout regions in VZT files */ +void vzt_wr_set_dumpoff(struct vzt_wr_trace *lt); +void vzt_wr_set_dumpon(struct vzt_wr_trace *lt); + + /* left fill on bit_string uses vcd semantics (left fill with value[0] unless value[0]=='1', then use '0') */ +int vzt_wr_emit_value_int(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, int value); +int vzt_wr_emit_value_double(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, double value); +int vzt_wr_emit_value_string(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, char *value); +int vzt_wr_emit_value_bit_string(struct vzt_wr_trace *lt, struct vzt_wr_symbol *s, unsigned int row, char *value); + +#endif diff --git a/src/hiersearch.c b/src/hiersearch.c index 8f03fe7..40e995f 100644 --- a/src/hiersearch.c +++ b/src/hiersearch.c @@ -8,6 +8,7 @@ */ #include +#include "gtk12compat.h" #include "analyzer.h" #include "aet.h" #include "lx2.h" @@ -238,7 +239,7 @@ static void enter_callback_e(GtkWidget *widget, GtkWidget *nothing) { - gchar *entry_text; + G_CONST_RETURN gchar *entry_text; int len; entry_text = gtk_entry_get_text(GTK_ENTRY(entry)); DEBUG(printf("Entry contents: %s\n", entry_text)); @@ -628,7 +629,7 @@ { tfirst->flags |= TR_HIGHLIGHT; if(tfirst==tlast) break; - tfirst=tfirst->next; + tfirst=tfirst->t_next; } MaxSignalLength(); @@ -686,7 +687,7 @@ { if(!autoname_bundles) { - entrybox_local("Enter Bundle Name",300,"",128,bundle_cleanup); + entrybox_local("Enter Bundle Name",300,"",128,GTK_SIGNAL_FUNC(bundle_cleanup)); } else { diff --git a/src/libbz2/LICENSE b/src/libbz2/LICENSE new file mode 100644 index 0000000..9d4fa43 --- /dev/null +++ b/src/libbz2/LICENSE @@ -0,0 +1,39 @@ + +This program, "bzip2" and associated library "libbzip2", are +copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + +4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + +Julian Seward, Cambridge, UK. +jseward@acm.org +bzip2/libbzip2 version 1.0.2 of 30 December 2001 + diff --git a/src/libbz2/Makefile.in b/src/libbz2/Makefile.in new file mode 100644 index 0000000..74edb19 --- /dev/null +++ b/src/libbz2/Makefile.in @@ -0,0 +1,45 @@ +SHELL=/bin/sh + +# To assist in cross-compiling +CC=@CC@ +AR=ar +RANLIB=@RANLIB@ +LDFLAGS= + +# Suitably paranoid flags to avoid bugs in gcc-2.7 +BIGFILES = -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 +CFLAGS = -O2 + +OBJS= blocksort.o \ + huffman.o \ + crctable.o \ + randtable.o \ + bzcompress.o \ + bzdecompress.o \ + bzlib.o + +all: libbz2.a + +libbz2.a: $(OBJS) + rm -f libbz2.a + $(AR) cq libbz2.a $(OBJS) + $(RANLIB) libbz2.a + +clean: + rm -f *.o libbz2.a + +blocksort.o: blocksort.c + $(CC) $(CFLAGS) -c blocksort.c +huffman.o: huffman.c + $(CC) $(CFLAGS) -c huffman.c +crctable.o: crctable.c + $(CC) $(CFLAGS) -c crctable.c +randtable.o: randtable.c + $(CC) $(CFLAGS) -c randtable.c +bzcompress.o: bzcompress.c + $(CC) $(CFLAGS) -c bzcompress.c +bzdecompress.o: bzdecompress.c + $(CC) $(CFLAGS) -c bzdecompress.c +bzlib.o: bzlib.c + $(CC) $(CFLAGS) -c bzlib.c + diff --git a/src/libbz2/blocksort.c b/src/libbz2/blocksort.c new file mode 100644 index 0000000..aba3efc --- /dev/null +++ b/src/libbz2/blocksort.c @@ -0,0 +1,1141 @@ + +/*-------------------------------------------------------------*/ +/*--- Block sorting machinery ---*/ +/*--- blocksort.c ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. + + To get some idea how the block sorting algorithms in this file + work, read my paper + On the Performance of BWT Sorting Algorithms + in Proceedings of the IEEE Data Compression Conference 2000, + Snowbird, Utah, USA, 27-30 March 2000. The main sort in this + file implements the algorithm called cache in the paper. +--*/ + + +#include "bzlib_private.h" + +/*---------------------------------------------*/ +/*--- Fallback O(N log(N)^2) sorting ---*/ +/*--- algorithm, for repetitive blocks ---*/ +/*---------------------------------------------*/ + +/*---------------------------------------------*/ +static +__inline__ +void fallbackSimpleSort ( UInt32* fmap, + UInt32* eclass, + Int32 lo, + Int32 hi ) +{ + Int32 i, j, tmp; + UInt32 ec_tmp; + + if (lo == hi) return; + + if (hi - lo > 3) { + for ( i = hi-4; i >= lo; i-- ) { + tmp = fmap[i]; + ec_tmp = eclass[tmp]; + for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 ) + fmap[j-4] = fmap[j]; + fmap[j-4] = tmp; + } + } + + for ( i = hi-1; i >= lo; i-- ) { + tmp = fmap[i]; + ec_tmp = eclass[tmp]; + for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ ) + fmap[j-1] = fmap[j]; + fmap[j-1] = tmp; + } +} + + +/*---------------------------------------------*/ +#define fswap(zz1, zz2) \ + { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } + +#define fvswap(zzp1, zzp2, zzn) \ +{ \ + Int32 yyp1 = (zzp1); \ + Int32 yyp2 = (zzp2); \ + Int32 yyn = (zzn); \ + while (yyn > 0) { \ + fswap(fmap[yyp1], fmap[yyp2]); \ + yyp1++; yyp2++; yyn--; \ + } \ +} + + +#define fmin(a,b) ((a) < (b)) ? (a) : (b) + +#define fpush(lz,hz) { stackLo[sp] = lz; \ + stackHi[sp] = hz; \ + sp++; } + +#define fpop(lz,hz) { sp--; \ + lz = stackLo[sp]; \ + hz = stackHi[sp]; } + +#define FALLBACK_QSORT_SMALL_THRESH 10 +#define FALLBACK_QSORT_STACK_SIZE 100 + + +static +void fallbackQSort3 ( UInt32* fmap, + UInt32* eclass, + Int32 loSt, + Int32 hiSt ) +{ + Int32 unLo, unHi, ltLo, gtHi, n, m; + Int32 sp, lo, hi; + UInt32 med, r, r3; + Int32 stackLo[FALLBACK_QSORT_STACK_SIZE]; + Int32 stackHi[FALLBACK_QSORT_STACK_SIZE]; + + r = 0; + + sp = 0; + fpush ( loSt, hiSt ); + + while (sp > 0) { + + AssertH ( sp < FALLBACK_QSORT_STACK_SIZE, 1004 ); + + fpop ( lo, hi ); + if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) { + fallbackSimpleSort ( fmap, eclass, lo, hi ); + continue; + } + + /* Random partitioning. Median of 3 sometimes fails to + avoid bad cases. Median of 9 seems to help but + looks rather expensive. This too seems to work but + is cheaper. Guidance for the magic constants + 7621 and 32768 is taken from Sedgewick's algorithms + book, chapter 35. + */ + r = ((r * 7621) + 1) % 32768; + r3 = r % 3; + if (r3 == 0) med = eclass[fmap[lo]]; else + if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else + med = eclass[fmap[hi]]; + + unLo = ltLo = lo; + unHi = gtHi = hi; + + while (1) { + while (1) { + if (unLo > unHi) break; + n = (Int32)eclass[fmap[unLo]] - (Int32)med; + if (n == 0) { + fswap(fmap[unLo], fmap[ltLo]); + ltLo++; unLo++; + continue; + }; + if (n > 0) break; + unLo++; + } + while (1) { + if (unLo > unHi) break; + n = (Int32)eclass[fmap[unHi]] - (Int32)med; + if (n == 0) { + fswap(fmap[unHi], fmap[gtHi]); + gtHi--; unHi--; + continue; + }; + if (n < 0) break; + unHi--; + } + if (unLo > unHi) break; + fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--; + } + + AssertD ( unHi == unLo-1, "fallbackQSort3(2)" ); + + if (gtHi < ltLo) continue; + + n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n); + m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m); + + n = lo + unLo - ltLo - 1; + m = hi - (gtHi - unHi) + 1; + + if (n - lo > hi - m) { + fpush ( lo, n ); + fpush ( m, hi ); + } else { + fpush ( m, hi ); + fpush ( lo, n ); + } + } +} + +#undef fmin +#undef fpush +#undef fpop +#undef fswap +#undef fvswap +#undef FALLBACK_QSORT_SMALL_THRESH +#undef FALLBACK_QSORT_STACK_SIZE + + +/*---------------------------------------------*/ +/* Pre: + nblock > 0 + eclass exists for [0 .. nblock-1] + ((UChar*)eclass) [0 .. nblock-1] holds block + ptr exists for [0 .. nblock-1] + + Post: + ((UChar*)eclass) [0 .. nblock-1] holds block + All other areas of eclass destroyed + fmap [0 .. nblock-1] holds sorted order + bhtab [ 0 .. 2+(nblock/32) ] destroyed +*/ + +#define SET_BH(zz) bhtab[(zz) >> 5] |= (1 << ((zz) & 31)) +#define CLEAR_BH(zz) bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31)) +#define ISSET_BH(zz) (bhtab[(zz) >> 5] & (1 << ((zz) & 31))) +#define WORD_BH(zz) bhtab[(zz) >> 5] +#define UNALIGNED_BH(zz) ((zz) & 0x01f) + +static +void fallbackSort ( UInt32* fmap, + UInt32* eclass, + UInt32* bhtab, + Int32 nblock, + Int32 verb ) +{ + Int32 ftab[257]; + Int32 ftabCopy[256]; + Int32 H, i, j, k, l, r, cc, cc1; + Int32 nNotDone; + Int32 nBhtab; + UChar* eclass8 = (UChar*)eclass; + + /*-- + Initial 1-char radix sort to generate + initial fmap and initial BH bits. + --*/ + if (verb >= 4) + VPrintf0 ( " bucket sorting ...\n" ); + for (i = 0; i < 257; i++) ftab[i] = 0; + for (i = 0; i < nblock; i++) ftab[eclass8[i]]++; + for (i = 0; i < 256; i++) ftabCopy[i] = ftab[i]; + for (i = 1; i < 257; i++) ftab[i] += ftab[i-1]; + + for (i = 0; i < nblock; i++) { + j = eclass8[i]; + k = ftab[j] - 1; + ftab[j] = k; + fmap[k] = i; + } + + nBhtab = 2 + (nblock / 32); + for (i = 0; i < nBhtab; i++) bhtab[i] = 0; + for (i = 0; i < 256; i++) SET_BH(ftab[i]); + + /*-- + Inductively refine the buckets. Kind-of an + "exponential radix sort" (!), inspired by the + Manber-Myers suffix array construction algorithm. + --*/ + + /*-- set sentinel bits for block-end detection --*/ + for (i = 0; i < 32; i++) { + SET_BH(nblock + 2*i); + CLEAR_BH(nblock + 2*i + 1); + } + + /*-- the log(N) loop --*/ + H = 1; + while (1) { + + if (verb >= 4) + VPrintf1 ( " depth %6d has ", H ); + + j = 0; + for (i = 0; i < nblock; i++) { + if (ISSET_BH(i)) j = i; + k = fmap[i] - H; if (k < 0) k += nblock; + eclass[k] = j; + } + + nNotDone = 0; + r = -1; + while (1) { + + /*-- find the next non-singleton bucket --*/ + k = r + 1; + while (ISSET_BH(k) && UNALIGNED_BH(k)) k++; + if (ISSET_BH(k)) { + while (WORD_BH(k) == 0xffffffff) k += 32; + while (ISSET_BH(k)) k++; + } + l = k - 1; + if (l >= nblock) break; + while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++; + if (!ISSET_BH(k)) { + while (WORD_BH(k) == 0x00000000) k += 32; + while (!ISSET_BH(k)) k++; + } + r = k - 1; + if (r >= nblock) break; + + /*-- now [l, r] bracket current bucket --*/ + if (r > l) { + nNotDone += (r - l + 1); + fallbackQSort3 ( fmap, eclass, l, r ); + + /*-- scan bucket and generate header bits-- */ + cc = -1; + for (i = l; i <= r; i++) { + cc1 = eclass[fmap[i]]; + if (cc != cc1) { SET_BH(i); cc = cc1; }; + } + } + } + + if (verb >= 4) + VPrintf1 ( "%6d unresolved strings\n", nNotDone ); + + H *= 2; + if (H > nblock || nNotDone == 0) break; + } + + /*-- + Reconstruct the original block in + eclass8 [0 .. nblock-1], since the + previous phase destroyed it. + --*/ + if (verb >= 4) + VPrintf0 ( " reconstructing block ...\n" ); + j = 0; + for (i = 0; i < nblock; i++) { + while (ftabCopy[j] == 0) j++; + ftabCopy[j]--; + eclass8[fmap[i]] = (UChar)j; + } + AssertH ( j < 256, 1005 ); +} + +#undef SET_BH +#undef CLEAR_BH +#undef ISSET_BH +#undef WORD_BH +#undef UNALIGNED_BH + + +/*---------------------------------------------*/ +/*--- The main, O(N^2 log(N)) sorting ---*/ +/*--- algorithm. Faster for "normal" ---*/ +/*--- non-repetitive blocks. ---*/ +/*---------------------------------------------*/ + +/*---------------------------------------------*/ +static +__inline__ +Bool mainGtU ( UInt32 i1, + UInt32 i2, + UChar* block, + UInt16* quadrant, + UInt32 nblock, + Int32* budget ) +{ + Int32 k; + UChar c1, c2; + UInt16 s1, s2; + + AssertD ( i1 != i2, "mainGtU" ); + /* 1 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 2 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 3 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 4 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 5 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 6 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 7 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 8 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 9 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 10 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 11 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + /* 12 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + i1++; i2++; + + k = nblock + 8; + + do { + /* 1 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 2 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 3 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 4 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 5 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 6 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 7 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + /* 8 */ + c1 = block[i1]; c2 = block[i2]; + if (c1 != c2) return (c1 > c2); + s1 = quadrant[i1]; s2 = quadrant[i2]; + if (s1 != s2) return (s1 > s2); + i1++; i2++; + + if (i1 >= nblock) i1 -= nblock; + if (i2 >= nblock) i2 -= nblock; + + k -= 8; + (*budget)--; + } + while (k >= 0); + + return False; +} + + +/*---------------------------------------------*/ +/*-- + Knuth's increments seem to work better + than Incerpi-Sedgewick here. Possibly + because the number of elems to sort is + usually small, typically <= 20. +--*/ +static +Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280, + 9841, 29524, 88573, 265720, + 797161, 2391484 }; + +static +void mainSimpleSort ( UInt32* ptr, + UChar* block, + UInt16* quadrant, + Int32 nblock, + Int32 lo, + Int32 hi, + Int32 d, + Int32* budget ) +{ + Int32 i, j, h, bigN, hp; + UInt32 v; + + bigN = hi - lo + 1; + if (bigN < 2) return; + + hp = 0; + while (incs[hp] < bigN) hp++; + hp--; + + for (; hp >= 0; hp--) { + h = incs[hp]; + + i = lo + h; + while (True) { + + /*-- copy 1 --*/ + if (i > hi) break; + v = ptr[i]; + j = i; + while ( mainGtU ( + ptr[j-h]+d, v+d, block, quadrant, nblock, budget + ) ) { + ptr[j] = ptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) break; + } + ptr[j] = v; + i++; + + /*-- copy 2 --*/ + if (i > hi) break; + v = ptr[i]; + j = i; + while ( mainGtU ( + ptr[j-h]+d, v+d, block, quadrant, nblock, budget + ) ) { + ptr[j] = ptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) break; + } + ptr[j] = v; + i++; + + /*-- copy 3 --*/ + if (i > hi) break; + v = ptr[i]; + j = i; + while ( mainGtU ( + ptr[j-h]+d, v+d, block, quadrant, nblock, budget + ) ) { + ptr[j] = ptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) break; + } + ptr[j] = v; + i++; + + if (*budget < 0) return; + } + } +} + + +/*---------------------------------------------*/ +/*-- + The following is an implementation of + an elegant 3-way quicksort for strings, + described in a paper "Fast Algorithms for + Sorting and Searching Strings", by Robert + Sedgewick and Jon L. Bentley. +--*/ + +#define mswap(zz1, zz2) \ + { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } + +#define mvswap(zzp1, zzp2, zzn) \ +{ \ + Int32 yyp1 = (zzp1); \ + Int32 yyp2 = (zzp2); \ + Int32 yyn = (zzn); \ + while (yyn > 0) { \ + mswap(ptr[yyp1], ptr[yyp2]); \ + yyp1++; yyp2++; yyn--; \ + } \ +} + +static +__inline__ +UChar mmed3 ( UChar a, UChar b, UChar c ) +{ + UChar t; + if (a > b) { t = a; a = b; b = t; }; + if (b > c) { + b = c; + if (a > b) b = a; + } + return b; +} + +#define mmin(a,b) ((a) < (b)) ? (a) : (b) + +#define mpush(lz,hz,dz) { stackLo[sp] = lz; \ + stackHi[sp] = hz; \ + stackD [sp] = dz; \ + sp++; } + +#define mpop(lz,hz,dz) { sp--; \ + lz = stackLo[sp]; \ + hz = stackHi[sp]; \ + dz = stackD [sp]; } + + +#define mnextsize(az) (nextHi[az]-nextLo[az]) + +#define mnextswap(az,bz) \ + { Int32 tz; \ + tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \ + tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \ + tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; } + + +#define MAIN_QSORT_SMALL_THRESH 20 +#define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT) +#define MAIN_QSORT_STACK_SIZE 100 + +static +void mainQSort3 ( UInt32* ptr, + UChar* block, + UInt16* quadrant, + Int32 nblock, + Int32 loSt, + Int32 hiSt, + Int32 dSt, + Int32* budget ) +{ + Int32 unLo, unHi, ltLo, gtHi, n, m, med; + Int32 sp, lo, hi, d; + + Int32 stackLo[MAIN_QSORT_STACK_SIZE]; + Int32 stackHi[MAIN_QSORT_STACK_SIZE]; + Int32 stackD [MAIN_QSORT_STACK_SIZE]; + + Int32 nextLo[3]; + Int32 nextHi[3]; + Int32 nextD [3]; + + sp = 0; + mpush ( loSt, hiSt, dSt ); + + while (sp > 0) { + + AssertH ( sp < MAIN_QSORT_STACK_SIZE, 1001 ); + + mpop ( lo, hi, d ); + if (hi - lo < MAIN_QSORT_SMALL_THRESH || + d > MAIN_QSORT_DEPTH_THRESH) { + mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget ); + if (*budget < 0) return; + continue; + } + + med = (Int32) + mmed3 ( block[ptr[ lo ]+d], + block[ptr[ hi ]+d], + block[ptr[ (lo+hi)>>1 ]+d] ); + + unLo = ltLo = lo; + unHi = gtHi = hi; + + while (True) { + while (True) { + if (unLo > unHi) break; + n = ((Int32)block[ptr[unLo]+d]) - med; + if (n == 0) { + mswap(ptr[unLo], ptr[ltLo]); + ltLo++; unLo++; continue; + }; + if (n > 0) break; + unLo++; + } + while (True) { + if (unLo > unHi) break; + n = ((Int32)block[ptr[unHi]+d]) - med; + if (n == 0) { + mswap(ptr[unHi], ptr[gtHi]); + gtHi--; unHi--; continue; + }; + if (n < 0) break; + unHi--; + } + if (unLo > unHi) break; + mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--; + } + + AssertD ( unHi == unLo-1, "mainQSort3(2)" ); + + if (gtHi < ltLo) { + mpush(lo, hi, d+1 ); + continue; + } + + n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n); + m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m); + + n = lo + unLo - ltLo - 1; + m = hi - (gtHi - unHi) + 1; + + nextLo[0] = lo; nextHi[0] = n; nextD[0] = d; + nextLo[1] = m; nextHi[1] = hi; nextD[1] = d; + nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1; + + if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); + if (mnextsize(1) < mnextsize(2)) mnextswap(1,2); + if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); + + AssertD (mnextsize(0) >= mnextsize(1), "mainQSort3(8)" ); + AssertD (mnextsize(1) >= mnextsize(2), "mainQSort3(9)" ); + + mpush (nextLo[0], nextHi[0], nextD[0]); + mpush (nextLo[1], nextHi[1], nextD[1]); + mpush (nextLo[2], nextHi[2], nextD[2]); + } +} + +#undef mswap +#undef mvswap +#undef mpush +#undef mpop +#undef mmin +#undef mnextsize +#undef mnextswap +#undef MAIN_QSORT_SMALL_THRESH +#undef MAIN_QSORT_DEPTH_THRESH +#undef MAIN_QSORT_STACK_SIZE + + +/*---------------------------------------------*/ +/* Pre: + nblock > N_OVERSHOOT + block32 exists for [0 .. nblock-1 +N_OVERSHOOT] + ((UChar*)block32) [0 .. nblock-1] holds block + ptr exists for [0 .. nblock-1] + + Post: + ((UChar*)block32) [0 .. nblock-1] holds block + All other areas of block32 destroyed + ftab [0 .. 65536 ] destroyed + ptr [0 .. nblock-1] holds sorted order + if (*budget < 0), sorting was abandoned +*/ + +#define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8]) +#define SETMASK (1 << 21) +#define CLEARMASK (~(SETMASK)) + +static +void mainSort ( UInt32* ptr, + UChar* block, + UInt16* quadrant, + UInt32* ftab, + Int32 nblock, + Int32 verb, + Int32* budget ) +{ + Int32 i, j, k, ss, sb; + Int32 runningOrder[256]; + Bool bigDone[256]; + Int32 copyStart[256]; + Int32 copyEnd [256]; + UChar c1; + Int32 numQSorted; + UInt16 s; + if (verb >= 4) VPrintf0 ( " main sort initialise ...\n" ); + + /*-- set up the 2-byte frequency table --*/ + for (i = 65536; i >= 0; i--) ftab[i] = 0; + + j = block[0] << 8; + i = nblock-1; + for (; i >= 3; i -= 4) { + quadrant[i] = 0; + j = (j >> 8) | ( ((UInt16)block[i]) << 8); + ftab[j]++; + quadrant[i-1] = 0; + j = (j >> 8) | ( ((UInt16)block[i-1]) << 8); + ftab[j]++; + quadrant[i-2] = 0; + j = (j >> 8) | ( ((UInt16)block[i-2]) << 8); + ftab[j]++; + quadrant[i-3] = 0; + j = (j >> 8) | ( ((UInt16)block[i-3]) << 8); + ftab[j]++; + } + for (; i >= 0; i--) { + quadrant[i] = 0; + j = (j >> 8) | ( ((UInt16)block[i]) << 8); + ftab[j]++; + } + + /*-- (emphasises close relationship of block & quadrant) --*/ + for (i = 0; i < BZ_N_OVERSHOOT; i++) { + block [nblock+i] = block[i]; + quadrant[nblock+i] = 0; + } + + if (verb >= 4) VPrintf0 ( " bucket sorting ...\n" ); + + /*-- Complete the initial radix sort --*/ + for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1]; + + s = block[0] << 8; + i = nblock-1; + for (; i >= 3; i -= 4) { + s = (s >> 8) | (block[i] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i; + s = (s >> 8) | (block[i-1] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i-1; + s = (s >> 8) | (block[i-2] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i-2; + s = (s >> 8) | (block[i-3] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i-3; + } + for (; i >= 0; i--) { + s = (s >> 8) | (block[i] << 8); + j = ftab[s] -1; + ftab[s] = j; + ptr[j] = i; + } + + /*-- + Now ftab contains the first loc of every small bucket. + Calculate the running order, from smallest to largest + big bucket. + --*/ + for (i = 0; i <= 255; i++) { + bigDone [i] = False; + runningOrder[i] = i; + } + + { + Int32 vv; + Int32 h = 1; + do h = 3 * h + 1; while (h <= 256); + do { + h = h / 3; + for (i = h; i <= 255; i++) { + vv = runningOrder[i]; + j = i; + while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) { + runningOrder[j] = runningOrder[j-h]; + j = j - h; + if (j <= (h - 1)) goto zero; + } + zero: + runningOrder[j] = vv; + } + } while (h != 1); + } + + /*-- + The main sorting loop. + --*/ + + numQSorted = 0; + + for (i = 0; i <= 255; i++) { + + /*-- + Process big buckets, starting with the least full. + Basically this is a 3-step process in which we call + mainQSort3 to sort the small buckets [ss, j], but + also make a big effort to avoid the calls if we can. + --*/ + ss = runningOrder[i]; + + /*-- + Step 1: + Complete the big bucket [ss] by quicksorting + any unsorted small buckets [ss, j], for j != ss. + Hopefully previous pointer-scanning phases have already + completed many of the small buckets [ss, j], so + we don't have to sort them at all. + --*/ + for (j = 0; j <= 255; j++) { + if (j != ss) { + sb = (ss << 8) + j; + if ( ! (ftab[sb] & SETMASK) ) { + Int32 lo = ftab[sb] & CLEARMASK; + Int32 hi = (ftab[sb+1] & CLEARMASK) - 1; + if (hi > lo) { + if (verb >= 4) + VPrintf4 ( " qsort [0x%x, 0x%x] " + "done %d this %d\n", + ss, j, numQSorted, hi - lo + 1 ); + mainQSort3 ( + ptr, block, quadrant, nblock, + lo, hi, BZ_N_RADIX, budget + ); + numQSorted += (hi - lo + 1); + if (*budget < 0) return; + } + } + ftab[sb] |= SETMASK; + } + } + + AssertH ( !bigDone[ss], 1006 ); + + /*-- + Step 2: + Now scan this big bucket [ss] so as to synthesise the + sorted order for small buckets [t, ss] for all t, + including, magically, the bucket [ss,ss] too. + This will avoid doing Real Work in subsequent Step 1's. + --*/ + { + for (j = 0; j <= 255; j++) { + copyStart[j] = ftab[(j << 8) + ss] & CLEARMASK; + copyEnd [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1; + } + for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) { + k = ptr[j]-1; if (k < 0) k += nblock; + c1 = block[k]; + if (!bigDone[c1]) + ptr[ copyStart[c1]++ ] = k; + } + for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) { + k = ptr[j]-1; if (k < 0) k += nblock; + c1 = block[k]; + if (!bigDone[c1]) + ptr[ copyEnd[c1]-- ] = k; + } + } + + AssertH ( (copyStart[ss]-1 == copyEnd[ss]) + || + /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1. + Necessity for this case is demonstrated by compressing + a sequence of approximately 48.5 million of character + 251; 1.0.0/1.0.1 will then die here. */ + (copyStart[ss] == 0 && copyEnd[ss] == nblock-1), + 1007 ) + + for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK; + + /*-- + Step 3: + The [ss] big bucket is now done. Record this fact, + and update the quadrant descriptors. Remember to + update quadrants in the overshoot area too, if + necessary. The "if (i < 255)" test merely skips + this updating for the last bucket processed, since + updating for the last bucket is pointless. + + The quadrant array provides a way to incrementally + cache sort orderings, as they appear, so as to + make subsequent comparisons in fullGtU() complete + faster. For repetitive blocks this makes a big + difference (but not big enough to be able to avoid + the fallback sorting mechanism, exponential radix sort). + + The precise meaning is: at all times: + + for 0 <= i < nblock and 0 <= j <= nblock + + if block[i] != block[j], + + then the relative values of quadrant[i] and + quadrant[j] are meaningless. + + else { + if quadrant[i] < quadrant[j] + then the string starting at i lexicographically + precedes the string starting at j + + else if quadrant[i] > quadrant[j] + then the string starting at j lexicographically + precedes the string starting at i + + else + the relative ordering of the strings starting + at i and j has not yet been determined. + } + --*/ + bigDone[ss] = True; + + if (i < 255) { + Int32 bbStart = ftab[ss << 8] & CLEARMASK; + Int32 bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart; + Int32 shifts = 0; + + while ((bbSize >> shifts) > 65534) shifts++; + + for (j = bbSize-1; j >= 0; j--) { + Int32 a2update = ptr[bbStart + j]; + UInt16 qVal = (UInt16)(j >> shifts); + quadrant[a2update] = qVal; + if (a2update < BZ_N_OVERSHOOT) + quadrant[a2update + nblock] = qVal; + } + AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 ); + } + + } + + if (verb >= 4) + VPrintf3 ( " %d pointers, %d sorted, %d scanned\n", + nblock, numQSorted, nblock - numQSorted ); +} + +#undef BIGFREQ +#undef SETMASK +#undef CLEARMASK + + +/*---------------------------------------------*/ +/* Pre: + nblock > 0 + arr2 exists for [0 .. nblock-1 +N_OVERSHOOT] + ((UChar*)arr2) [0 .. nblock-1] holds block + arr1 exists for [0 .. nblock-1] + + Post: + ((UChar*)arr2) [0 .. nblock-1] holds block + All other areas of block destroyed + ftab [ 0 .. 65536 ] destroyed + arr1 [0 .. nblock-1] holds sorted order +*/ +void BZ2_blockSort ( EState* s ) +{ + UInt32* ptr = s->ptr; + UChar* block = s->block; + UInt32* ftab = s->ftab; + Int32 nblock = s->nblock; + Int32 verb = s->verbosity; + Int32 wfact = s->workFactor; + UInt16* quadrant; + Int32 budget; + Int32 budgetInit; + Int32 i; + + if (nblock < 10000) { + fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); + } else { + /* Calculate the location for quadrant, remembering to get + the alignment right. Assumes that &(block[0]) is at least + 2-byte aligned -- this should be ok since block is really + the first section of arr2. + */ + i = nblock+BZ_N_OVERSHOOT; + if (i & 1) i++; + quadrant = (UInt16*)(&(block[i])); + + /* (wfact-1) / 3 puts the default-factor-30 + transition point at very roughly the same place as + with v0.1 and v0.9.0. + Not that it particularly matters any more, since the + resulting compressed stream is now the same regardless + of whether or not we use the main sort or fallback sort. + */ + if (wfact < 1 ) wfact = 1; + if (wfact > 100) wfact = 100; + budgetInit = nblock * ((wfact-1) / 3); + budget = budgetInit; + + mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget ); + if (verb >= 3) + VPrintf3 ( " %d work, %d block, ratio %5.2f\n", + budgetInit - budget, + nblock, + (float)(budgetInit - budget) / + (float)(nblock==0 ? 1 : nblock) ); + if (budget < 0) { + if (verb >= 2) + VPrintf0 ( " too repetitive; using fallback" + " sorting algorithm\n" ); + fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); + } + } + + s->origPtr = -1; + for (i = 0; i < s->nblock; i++) + if (ptr[i] == 0) + { s->origPtr = i; break; }; + + AssertH( s->origPtr != -1, 1003 ); +} + + +/*-------------------------------------------------------------*/ +/*--- end blocksort.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/bzcompress.c b/src/libbz2/bzcompress.c new file mode 100644 index 0000000..56501c1 --- /dev/null +++ b/src/libbz2/bzcompress.c @@ -0,0 +1,714 @@ + +/*-------------------------------------------------------------*/ +/*--- Compression machinery (not incl block sorting) ---*/ +/*--- compress.c ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + +/*-- + CHANGES + ~~~~~~~ + 0.9.0 -- original version. + + 0.9.0a/b -- no changes in this file. + + 0.9.0c + * changed setting of nGroups in sendMTFValues() so as to + do a bit better on small files +--*/ + +#include "bzlib_private.h" + + +/*---------------------------------------------------*/ +/*--- Bit stream I/O ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +void BZ2_bsInitWrite ( EState* s ) +{ + s->bsLive = 0; + s->bsBuff = 0; +} + + +/*---------------------------------------------------*/ +static +void bsFinishWrite ( EState* s ) +{ + while (s->bsLive > 0) { + s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24); + s->numZ++; + s->bsBuff <<= 8; + s->bsLive -= 8; + } +} + + +/*---------------------------------------------------*/ +#define bsNEEDW(nz) \ +{ \ + while (s->bsLive >= 8) { \ + s->zbits[s->numZ] \ + = (UChar)(s->bsBuff >> 24); \ + s->numZ++; \ + s->bsBuff <<= 8; \ + s->bsLive -= 8; \ + } \ +} + + +/*---------------------------------------------------*/ +static +__inline__ +void bsW ( EState* s, Int32 n, UInt32 v ) +{ + bsNEEDW ( n ); + s->bsBuff |= (v << (32 - s->bsLive - n)); + s->bsLive += n; +} + + +/*---------------------------------------------------*/ +static +void bsPutUInt32 ( EState* s, UInt32 u ) +{ + bsW ( s, 8, (u >> 24) & 0xffL ); + bsW ( s, 8, (u >> 16) & 0xffL ); + bsW ( s, 8, (u >> 8) & 0xffL ); + bsW ( s, 8, u & 0xffL ); +} + + +/*---------------------------------------------------*/ +static +void bsPutUChar ( EState* s, UChar c ) +{ + bsW( s, 8, (UInt32)c ); +} + + +/*---------------------------------------------------*/ +/*--- The back end proper ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +static +void makeMaps_e ( EState* s ) +{ + Int32 i; + s->nInUse = 0; + for (i = 0; i < 256; i++) + if (s->inUse[i]) { + s->unseqToSeq[i] = s->nInUse; + s->nInUse++; + } +} + + +/*---------------------------------------------------*/ +static +void generateMTFValues ( EState* s ) +{ + UChar yy[256]; + Int32 i, j; + Int32 zPend; + Int32 wr; + Int32 EOB; + + /* + After sorting (eg, here), + s->arr1 [ 0 .. s->nblock-1 ] holds sorted order, + and + ((UChar*)s->arr2) [ 0 .. s->nblock-1 ] + holds the original block data. + + The first thing to do is generate the MTF values, + and put them in + ((UInt16*)s->arr1) [ 0 .. s->nblock-1 ]. + Because there are strictly fewer or equal MTF values + than block values, ptr values in this area are overwritten + with MTF values only when they are no longer needed. + + The final compressed bitstream is generated into the + area starting at + (UChar*) (&((UChar*)s->arr2)[s->nblock]) + + These storage aliases are set up in bzCompressInit(), + except for the last one, which is arranged in + compressBlock(). + */ + UInt32* ptr = s->ptr; + UChar* block = s->block; + UInt16* mtfv = s->mtfv; + + makeMaps_e ( s ); + EOB = s->nInUse+1; + + for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0; + + wr = 0; + zPend = 0; + for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i; + + for (i = 0; i < s->nblock; i++) { + UChar ll_i; + AssertD ( wr <= i, "generateMTFValues(1)" ); + j = ptr[i]-1; if (j < 0) j += s->nblock; + ll_i = s->unseqToSeq[block[j]]; + AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" ); + + if (yy[0] == ll_i) { + zPend++; + } else { + + if (zPend > 0) { + zPend--; + while (True) { + if (zPend & 1) { + mtfv[wr] = BZ_RUNB; wr++; + s->mtfFreq[BZ_RUNB]++; + } else { + mtfv[wr] = BZ_RUNA; wr++; + s->mtfFreq[BZ_RUNA]++; + } + if (zPend < 2) break; + zPend = (zPend - 2) / 2; + }; + zPend = 0; + } + { + register UChar rtmp; + register UChar* ryy_j; + register UChar rll_i; + rtmp = yy[1]; + yy[1] = yy[0]; + ryy_j = &(yy[1]); + rll_i = ll_i; + while ( rll_i != rtmp ) { + register UChar rtmp2; + ryy_j++; + rtmp2 = rtmp; + rtmp = *ryy_j; + *ryy_j = rtmp2; + }; + yy[0] = rtmp; + j = ryy_j - &(yy[0]); + mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++; + } + + } + } + + if (zPend > 0) { + zPend--; + while (True) { + if (zPend & 1) { + mtfv[wr] = BZ_RUNB; wr++; + s->mtfFreq[BZ_RUNB]++; + } else { + mtfv[wr] = BZ_RUNA; wr++; + s->mtfFreq[BZ_RUNA]++; + } + if (zPend < 2) break; + zPend = (zPend - 2) / 2; + }; + zPend = 0; + } + + mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++; + + s->nMTF = wr; +} + + +/*---------------------------------------------------*/ +#define BZ_LESSER_ICOST 0 +#define BZ_GREATER_ICOST 15 + +static +void sendMTFValues ( EState* s ) +{ + Int32 v, t, i, j, gs, ge, totc, bt, bc, iter; + Int32 nSelectors, alphaSize, minLen, maxLen, selCtr; + Int32 nGroups, nBytes; + + /*-- + UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + is a global since the decoder also needs it. + + Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + are also globals only used in this proc. + Made global to keep stack frame size small. + --*/ + + + UInt16 cost[BZ_N_GROUPS]; + Int32 fave[BZ_N_GROUPS]; + + UInt16* mtfv = s->mtfv; + + if (s->verbosity >= 3) + VPrintf3( " %d in block, %d after MTF & 1-2 coding, " + "%d+2 syms in use\n", + s->nblock, s->nMTF, s->nInUse ); + + alphaSize = s->nInUse+2; + for (t = 0; t < BZ_N_GROUPS; t++) + for (v = 0; v < alphaSize; v++) + s->len[t][v] = BZ_GREATER_ICOST; + + /*--- Decide how many coding tables to use ---*/ + AssertH ( s->nMTF > 0, 3001 ); + if (s->nMTF < 200) nGroups = 2; else + if (s->nMTF < 600) nGroups = 3; else + if (s->nMTF < 1200) nGroups = 4; else + if (s->nMTF < 2400) nGroups = 5; else + nGroups = 6; + + /*--- Generate an initial set of coding tables ---*/ + { + Int32 nPart, remF, tFreq, aFreq; + + nPart = nGroups; + remF = s->nMTF; + gs = 0; + while (nPart > 0) { + tFreq = remF / nPart; + ge = gs-1; + aFreq = 0; + while (aFreq < tFreq && ge < alphaSize-1) { + ge++; + aFreq += s->mtfFreq[ge]; + } + + if (ge > gs + && nPart != nGroups && nPart != 1 + && ((nGroups-nPart) % 2 == 1)) { + aFreq -= s->mtfFreq[ge]; + ge--; + } + + if (s->verbosity >= 3) + VPrintf5( " initial group %d, [%d .. %d], " + "has %d syms (%4.1f%%)\n", + nPart, gs, ge, aFreq, + (100.0 * (float)aFreq) / (float)(s->nMTF) ); + + for (v = 0; v < alphaSize; v++) + if (v >= gs && v <= ge) + s->len[nPart-1][v] = BZ_LESSER_ICOST; else + s->len[nPart-1][v] = BZ_GREATER_ICOST; + + nPart--; + gs = ge+1; + remF -= aFreq; + } + } + + /*--- + Iterate up to BZ_N_ITERS times to improve the tables. + ---*/ + for (iter = 0; iter < BZ_N_ITERS; iter++) { + + for (t = 0; t < nGroups; t++) fave[t] = 0; + + for (t = 0; t < nGroups; t++) + for (v = 0; v < alphaSize; v++) + s->rfreq[t][v] = 0; + + /*--- + Set up an auxiliary length table which is used to fast-track + the common case (nGroups == 6). + ---*/ + if (nGroups == 6) { + for (v = 0; v < alphaSize; v++) { + s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v]; + s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v]; + s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v]; + } + } + + nSelectors = 0; + totc = 0; + gs = 0; + while (True) { + + /*--- Set group start & end marks. --*/ + if (gs >= s->nMTF) break; + ge = gs + BZ_G_SIZE - 1; + if (ge >= s->nMTF) ge = s->nMTF-1; + + /*-- + Calculate the cost of this group as coded + by each of the coding tables. + --*/ + for (t = 0; t < nGroups; t++) cost[t] = 0; + + if (nGroups == 6 && 50 == ge-gs+1) { + /*--- fast track the common case ---*/ + register UInt32 cost01, cost23, cost45; + register UInt16 icv; + cost01 = cost23 = cost45 = 0; + +# define BZ_ITER(nn) \ + icv = mtfv[gs+(nn)]; \ + cost01 += s->len_pack[icv][0]; \ + cost23 += s->len_pack[icv][1]; \ + cost45 += s->len_pack[icv][2]; \ + + BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4); + BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9); + BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14); + BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19); + BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24); + BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29); + BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34); + BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39); + BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44); + BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49); + +# undef BZ_ITER + + cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16; + cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16; + cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16; + + } else { + /*--- slow version which correctly handles all situations ---*/ + for (i = gs; i <= ge; i++) { + UInt16 icv = mtfv[i]; + for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv]; + } + } + + /*-- + Find the coding table which is best for this group, + and record its identity in the selector table. + --*/ + bc = 999999999; bt = -1; + for (t = 0; t < nGroups; t++) + if (cost[t] < bc) { bc = cost[t]; bt = t; }; + totc += bc; + fave[bt]++; + s->selector[nSelectors] = bt; + nSelectors++; + + /*-- + Increment the symbol frequencies for the selected table. + --*/ + if (nGroups == 6 && 50 == ge-gs+1) { + /*--- fast track the common case ---*/ + +# define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++ + + BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4); + BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9); + BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14); + BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19); + BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24); + BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29); + BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34); + BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39); + BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44); + BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49); + +# undef BZ_ITUR + + } else { + /*--- slow version which correctly handles all situations ---*/ + for (i = gs; i <= ge; i++) + s->rfreq[bt][ mtfv[i] ]++; + } + + gs = ge+1; + } + if (s->verbosity >= 3) { + VPrintf2 ( " pass %d: size is %d, grp uses are ", + iter+1, totc/8 ); + for (t = 0; t < nGroups; t++) + VPrintf1 ( "%d ", fave[t] ); + VPrintf0 ( "\n" ); + } + + /*-- + Recompute the tables based on the accumulated frequencies. + --*/ + for (t = 0; t < nGroups; t++) + BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]), + alphaSize, 20 ); + } + + + AssertH( nGroups < 8, 3002 ); + AssertH( nSelectors < 32768 && + nSelectors <= (2 + (900000 / BZ_G_SIZE)), + 3003 ); + + + /*--- Compute MTF values for the selectors. ---*/ + { + UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp; + for (i = 0; i < nGroups; i++) pos[i] = i; + for (i = 0; i < nSelectors; i++) { + ll_i = s->selector[i]; + j = 0; + tmp = pos[j]; + while ( ll_i != tmp ) { + j++; + tmp2 = tmp; + tmp = pos[j]; + pos[j] = tmp2; + }; + pos[0] = tmp; + s->selectorMtf[i] = j; + } + }; + + /*--- Assign actual codes for the tables. --*/ + for (t = 0; t < nGroups; t++) { + minLen = 32; + maxLen = 0; + for (i = 0; i < alphaSize; i++) { + if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; + if (s->len[t][i] < minLen) minLen = s->len[t][i]; + } + AssertH ( !(maxLen > 20), 3004 ); + AssertH ( !(minLen < 1), 3005 ); + BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]), + minLen, maxLen, alphaSize ); + } + + /*--- Transmit the mapping table. ---*/ + { + Bool inUse16[16]; + for (i = 0; i < 16; i++) { + inUse16[i] = False; + for (j = 0; j < 16; j++) + if (s->inUse[i * 16 + j]) inUse16[i] = True; + } + + nBytes = s->numZ; + for (i = 0; i < 16; i++) + if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0); + + for (i = 0; i < 16; i++) + if (inUse16[i]) + for (j = 0; j < 16; j++) { + if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0); + } + + if (s->verbosity >= 3) + VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes ); + } + + /*--- Now the selectors. ---*/ + nBytes = s->numZ; + bsW ( s, 3, nGroups ); + bsW ( s, 15, nSelectors ); + for (i = 0; i < nSelectors; i++) { + for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1); + bsW(s,1,0); + } + if (s->verbosity >= 3) + VPrintf1( "selectors %d, ", s->numZ-nBytes ); + + /*--- Now the coding tables. ---*/ + nBytes = s->numZ; + + for (t = 0; t < nGroups; t++) { + Int32 curr = s->len[t][0]; + bsW ( s, 5, curr ); + for (i = 0; i < alphaSize; i++) { + while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ }; + while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ }; + bsW ( s, 1, 0 ); + } + } + + if (s->verbosity >= 3) + VPrintf1 ( "code lengths %d, ", s->numZ-nBytes ); + + /*--- And finally, the block data proper ---*/ + nBytes = s->numZ; + selCtr = 0; + gs = 0; + while (True) { + if (gs >= s->nMTF) break; + ge = gs + BZ_G_SIZE - 1; + if (ge >= s->nMTF) ge = s->nMTF-1; + AssertH ( s->selector[selCtr] < nGroups, 3006 ); + + if (nGroups == 6 && 50 == ge-gs+1) { + /*--- fast track the common case ---*/ + UInt16 mtfv_i; + UChar* s_len_sel_selCtr + = &(s->len[s->selector[selCtr]][0]); + Int32* s_code_sel_selCtr + = &(s->code[s->selector[selCtr]][0]); + +# define BZ_ITAH(nn) \ + mtfv_i = mtfv[gs+(nn)]; \ + bsW ( s, \ + s_len_sel_selCtr[mtfv_i], \ + s_code_sel_selCtr[mtfv_i] ) + + BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4); + BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9); + BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14); + BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19); + BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24); + BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29); + BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34); + BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39); + BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44); + BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49); + +# undef BZ_ITAH + + } else { + /*--- slow version which correctly handles all situations ---*/ + for (i = gs; i <= ge; i++) { + bsW ( s, + s->len [s->selector[selCtr]] [mtfv[i]], + s->code [s->selector[selCtr]] [mtfv[i]] ); + } + } + + + gs = ge+1; + selCtr++; + } + AssertH( selCtr == nSelectors, 3007 ); + + if (s->verbosity >= 3) + VPrintf1( "codes %d\n", s->numZ-nBytes ); +} + + +/*---------------------------------------------------*/ +void BZ2_compressBlock ( EState* s, Bool is_last_block ) +{ + if (s->nblock > 0) { + + BZ_FINALISE_CRC ( s->blockCRC ); + s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31); + s->combinedCRC ^= s->blockCRC; + if (s->blockNo > 1) s->numZ = 0; + + if (s->verbosity >= 2) + VPrintf4( " block %d: crc = 0x%8x, " + "combined CRC = 0x%8x, size = %d\n", + s->blockNo, s->blockCRC, s->combinedCRC, s->nblock ); + + BZ2_blockSort ( s ); + } + + s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]); + + /*-- If this is the first block, create the stream header. --*/ + if (s->blockNo == 1) { + BZ2_bsInitWrite ( s ); + bsPutUChar ( s, BZ_HDR_B ); + bsPutUChar ( s, BZ_HDR_Z ); + bsPutUChar ( s, BZ_HDR_h ); + bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) ); + } + + if (s->nblock > 0) { + + bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 ); + bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 ); + bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 ); + + /*-- Now the block's CRC, so it is in a known place. --*/ + bsPutUInt32 ( s, s->blockCRC ); + + /*-- + Now a single bit indicating (non-)randomisation. + As of version 0.9.5, we use a better sorting algorithm + which makes randomisation unnecessary. So always set + the randomised bit to 'no'. Of course, the decoder + still needs to be able to handle randomised blocks + so as to maintain backwards compatibility with + older versions of bzip2. + --*/ + bsW(s,1,0); + + bsW ( s, 24, s->origPtr ); + generateMTFValues ( s ); + sendMTFValues ( s ); + } + + + /*-- If this is the last block, add the stream trailer. --*/ + if (is_last_block) { + + bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 ); + bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 ); + bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 ); + bsPutUInt32 ( s, s->combinedCRC ); + if (s->verbosity >= 2) + VPrintf1( " final combined CRC = 0x%x\n ", s->combinedCRC ); + bsFinishWrite ( s ); + } +} + + +/*-------------------------------------------------------------*/ +/*--- end compress.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/bzdecompress.c b/src/libbz2/bzdecompress.c new file mode 100644 index 0000000..e921347 --- /dev/null +++ b/src/libbz2/bzdecompress.c @@ -0,0 +1,660 @@ + +/*-------------------------------------------------------------*/ +/*--- Decompression machinery ---*/ +/*--- decompress.c ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + + +#include "bzlib_private.h" + + +/*---------------------------------------------------*/ +static +void makeMaps_d ( DState* s ) +{ + Int32 i; + s->nInUse = 0; + for (i = 0; i < 256; i++) + if (s->inUse[i]) { + s->seqToUnseq[s->nInUse] = i; + s->nInUse++; + } +} + + +/*---------------------------------------------------*/ +#define RETURN(rrr) \ + { retVal = rrr; goto save_state_and_return; }; + +#define GET_BITS(lll,vvv,nnn) \ + case lll: s->state = lll; \ + while (True) { \ + if (s->bsLive >= nnn) { \ + UInt32 v; \ + v = (s->bsBuff >> \ + (s->bsLive-nnn)) & ((1 << nnn)-1); \ + s->bsLive -= nnn; \ + vvv = v; \ + break; \ + } \ + if (s->strm->avail_in == 0) RETURN(BZ_OK); \ + s->bsBuff \ + = (s->bsBuff << 8) | \ + ((UInt32) \ + (*((UChar*)(s->strm->next_in)))); \ + s->bsLive += 8; \ + s->strm->next_in++; \ + s->strm->avail_in--; \ + s->strm->total_in_lo32++; \ + if (s->strm->total_in_lo32 == 0) \ + s->strm->total_in_hi32++; \ + } + +#define GET_UCHAR(lll,uuu) \ + GET_BITS(lll,uuu,8) + +#define GET_BIT(lll,uuu) \ + GET_BITS(lll,uuu,1) + +/*---------------------------------------------------*/ +#define GET_MTF_VAL(label1,label2,lval) \ +{ \ + if (groupPos == 0) { \ + groupNo++; \ + if (groupNo >= nSelectors) \ + RETURN(BZ_DATA_ERROR); \ + groupPos = BZ_G_SIZE; \ + gSel = s->selector[groupNo]; \ + gMinlen = s->minLens[gSel]; \ + gLimit = &(s->limit[gSel][0]); \ + gPerm = &(s->perm[gSel][0]); \ + gBase = &(s->base[gSel][0]); \ + } \ + groupPos--; \ + zn = gMinlen; \ + GET_BITS(label1, zvec, zn); \ + while (1) { \ + if (zn > 20 /* the longest code */) \ + RETURN(BZ_DATA_ERROR); \ + if (zvec <= gLimit[zn]) break; \ + zn++; \ + GET_BIT(label2, zj); \ + zvec = (zvec << 1) | zj; \ + }; \ + if (zvec - gBase[zn] < 0 \ + || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ + RETURN(BZ_DATA_ERROR); \ + lval = gPerm[zvec - gBase[zn]]; \ +} + + +/*---------------------------------------------------*/ +Int32 BZ2_decompress ( DState* s ) +{ + UChar uc; + Int32 retVal; + Int32 minLen, maxLen; + bz_stream* strm = s->strm; + + /* stuff that needs to be saved/restored */ + Int32 i; + Int32 j; + Int32 t; + Int32 alphaSize; + Int32 nGroups; + Int32 nSelectors; + Int32 EOB; + Int32 groupNo; + Int32 groupPos; + Int32 nextSym; + Int32 nblockMAX; + Int32 nblock; + Int32 es; + Int32 N; + Int32 curr; + Int32 zt; + Int32 zn; + Int32 zvec; + Int32 zj; + Int32 gSel; + Int32 gMinlen; + Int32* gLimit; + Int32* gBase; + Int32* gPerm; + + if (s->state == BZ_X_MAGIC_1) { + /*initialise the save area*/ + s->save_i = 0; + s->save_j = 0; + s->save_t = 0; + s->save_alphaSize = 0; + s->save_nGroups = 0; + s->save_nSelectors = 0; + s->save_EOB = 0; + s->save_groupNo = 0; + s->save_groupPos = 0; + s->save_nextSym = 0; + s->save_nblockMAX = 0; + s->save_nblock = 0; + s->save_es = 0; + s->save_N = 0; + s->save_curr = 0; + s->save_zt = 0; + s->save_zn = 0; + s->save_zvec = 0; + s->save_zj = 0; + s->save_gSel = 0; + s->save_gMinlen = 0; + s->save_gLimit = NULL; + s->save_gBase = NULL; + s->save_gPerm = NULL; + } + + /*restore from the save area*/ + i = s->save_i; + j = s->save_j; + t = s->save_t; + alphaSize = s->save_alphaSize; + nGroups = s->save_nGroups; + nSelectors = s->save_nSelectors; + EOB = s->save_EOB; + groupNo = s->save_groupNo; + groupPos = s->save_groupPos; + nextSym = s->save_nextSym; + nblockMAX = s->save_nblockMAX; + nblock = s->save_nblock; + es = s->save_es; + N = s->save_N; + curr = s->save_curr; + zt = s->save_zt; + zn = s->save_zn; + zvec = s->save_zvec; + zj = s->save_zj; + gSel = s->save_gSel; + gMinlen = s->save_gMinlen; + gLimit = s->save_gLimit; + gBase = s->save_gBase; + gPerm = s->save_gPerm; + + retVal = BZ_OK; + + switch (s->state) { + + GET_UCHAR(BZ_X_MAGIC_1, uc); + if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); + + GET_UCHAR(BZ_X_MAGIC_2, uc); + if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); + + GET_UCHAR(BZ_X_MAGIC_3, uc) + if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); + + GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) + if (s->blockSize100k < (BZ_HDR_0 + 1) || + s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); + s->blockSize100k -= BZ_HDR_0; + + if (s->smallDecompress) { + s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); + s->ll4 = BZALLOC( + ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) + ); + if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); + } else { + s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); + if (s->tt == NULL) RETURN(BZ_MEM_ERROR); + } + + GET_UCHAR(BZ_X_BLKHDR_1, uc); + + if (uc == 0x17) goto endhdr_2; + if (uc != 0x31) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_2, uc); + if (uc != 0x41) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_3, uc); + if (uc != 0x59) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_4, uc); + if (uc != 0x26) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_5, uc); + if (uc != 0x53) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_BLKHDR_6, uc); + if (uc != 0x59) RETURN(BZ_DATA_ERROR); + + s->currBlockNo++; + if (s->verbosity >= 2) + VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); + + s->storedBlockCRC = 0; + GET_UCHAR(BZ_X_BCRC_1, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_BCRC_2, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_BCRC_3, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_BCRC_4, uc); + s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); + + GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); + + s->origPtr = 0; + GET_UCHAR(BZ_X_ORIGPTR_1, uc); + s->origPtr = (s->origPtr << 8) | ((Int32)uc); + GET_UCHAR(BZ_X_ORIGPTR_2, uc); + s->origPtr = (s->origPtr << 8) | ((Int32)uc); + GET_UCHAR(BZ_X_ORIGPTR_3, uc); + s->origPtr = (s->origPtr << 8) | ((Int32)uc); + + if (s->origPtr < 0) + RETURN(BZ_DATA_ERROR); + if (s->origPtr > 10 + 100000*s->blockSize100k) + RETURN(BZ_DATA_ERROR); + + /*--- Receive the mapping table ---*/ + for (i = 0; i < 16; i++) { + GET_BIT(BZ_X_MAPPING_1, uc); + if (uc == 1) + s->inUse16[i] = True; else + s->inUse16[i] = False; + } + + for (i = 0; i < 256; i++) s->inUse[i] = False; + + for (i = 0; i < 16; i++) + if (s->inUse16[i]) + for (j = 0; j < 16; j++) { + GET_BIT(BZ_X_MAPPING_2, uc); + if (uc == 1) s->inUse[i * 16 + j] = True; + } + makeMaps_d ( s ); + if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); + alphaSize = s->nInUse+2; + + /*--- Now the selectors ---*/ + GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); + if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); + GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); + if (nSelectors < 1) RETURN(BZ_DATA_ERROR); + for (i = 0; i < nSelectors; i++) { + j = 0; + while (True) { + GET_BIT(BZ_X_SELECTOR_3, uc); + if (uc == 0) break; + j++; + if (j >= nGroups) RETURN(BZ_DATA_ERROR); + } + s->selectorMtf[i] = j; + } + + /*--- Undo the MTF values for the selectors. ---*/ + { + UChar pos[BZ_N_GROUPS], tmp, v; + for (v = 0; v < nGroups; v++) pos[v] = v; + + for (i = 0; i < nSelectors; i++) { + v = s->selectorMtf[i]; + tmp = pos[v]; + while (v > 0) { pos[v] = pos[v-1]; v--; } + pos[0] = tmp; + s->selector[i] = tmp; + } + } + + /*--- Now the coding tables ---*/ + for (t = 0; t < nGroups; t++) { + GET_BITS(BZ_X_CODING_1, curr, 5); + for (i = 0; i < alphaSize; i++) { + while (True) { + if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); + GET_BIT(BZ_X_CODING_2, uc); + if (uc == 0) break; + GET_BIT(BZ_X_CODING_3, uc); + if (uc == 0) curr++; else curr--; + } + s->len[t][i] = curr; + } + } + + /*--- Create the Huffman decoding tables ---*/ + for (t = 0; t < nGroups; t++) { + minLen = 32; + maxLen = 0; + for (i = 0; i < alphaSize; i++) { + if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; + if (s->len[t][i] < minLen) minLen = s->len[t][i]; + } + BZ2_hbCreateDecodeTables ( + &(s->limit[t][0]), + &(s->base[t][0]), + &(s->perm[t][0]), + &(s->len[t][0]), + minLen, maxLen, alphaSize + ); + s->minLens[t] = minLen; + } + + /*--- Now the MTF values ---*/ + + EOB = s->nInUse+1; + nblockMAX = 100000 * s->blockSize100k; + groupNo = -1; + groupPos = 0; + + for (i = 0; i <= 255; i++) s->unzftab[i] = 0; + + /*-- MTF init --*/ + { + Int32 ii, jj, kk; + kk = MTFA_SIZE-1; + for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { + for (jj = MTFL_SIZE-1; jj >= 0; jj--) { + s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); + kk--; + } + s->mtfbase[ii] = kk + 1; + } + } + /*-- end MTF init --*/ + + nblock = 0; + GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); + + while (True) { + + if (nextSym == EOB) break; + + if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { + + es = -1; + N = 1; + do { + if (nextSym == BZ_RUNA) es = es + (0+1) * N; else + if (nextSym == BZ_RUNB) es = es + (1+1) * N; + N = N * 2; + GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); + } + while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); + + es++; + uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; + s->unzftab[uc] += es; + + if (s->smallDecompress) + while (es > 0) { + if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); + s->ll16[nblock] = (UInt16)uc; + nblock++; + es--; + } + else + while (es > 0) { + if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); + s->tt[nblock] = (UInt32)uc; + nblock++; + es--; + }; + + continue; + + } else { + + if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); + + /*-- uc = MTF ( nextSym-1 ) --*/ + { + Int32 ii, jj, kk, pp, lno, off; + UInt32 nn; + nn = (UInt32)(nextSym - 1); + + if (nn < MTFL_SIZE) { + /* avoid general-case expense */ + pp = s->mtfbase[0]; + uc = s->mtfa[pp+nn]; + while (nn > 3) { + Int32 z = pp+nn; + s->mtfa[(z) ] = s->mtfa[(z)-1]; + s->mtfa[(z)-1] = s->mtfa[(z)-2]; + s->mtfa[(z)-2] = s->mtfa[(z)-3]; + s->mtfa[(z)-3] = s->mtfa[(z)-4]; + nn -= 4; + } + while (nn > 0) { + s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; + }; + s->mtfa[pp] = uc; + } else { + /* general case */ + lno = nn / MTFL_SIZE; + off = nn % MTFL_SIZE; + pp = s->mtfbase[lno] + off; + uc = s->mtfa[pp]; + while (pp > s->mtfbase[lno]) { + s->mtfa[pp] = s->mtfa[pp-1]; pp--; + }; + s->mtfbase[lno]++; + while (lno > 0) { + s->mtfbase[lno]--; + s->mtfa[s->mtfbase[lno]] + = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; + lno--; + } + s->mtfbase[0]--; + s->mtfa[s->mtfbase[0]] = uc; + if (s->mtfbase[0] == 0) { + kk = MTFA_SIZE-1; + for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { + for (jj = MTFL_SIZE-1; jj >= 0; jj--) { + s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; + kk--; + } + s->mtfbase[ii] = kk + 1; + } + } + } + } + /*-- end uc = MTF ( nextSym-1 ) --*/ + + s->unzftab[s->seqToUnseq[uc]]++; + if (s->smallDecompress) + s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else + s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); + nblock++; + + GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); + continue; + } + } + + /* Now we know what nblock is, we can do a better sanity + check on s->origPtr. + */ + if (s->origPtr < 0 || s->origPtr >= nblock) + RETURN(BZ_DATA_ERROR); + + s->state_out_len = 0; + s->state_out_ch = 0; + BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); + s->state = BZ_X_OUTPUT; + if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); + + /*-- Set up cftab to facilitate generation of T^(-1) --*/ + s->cftab[0] = 0; + for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; + for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; + + if (s->smallDecompress) { + + /*-- Make a copy of cftab, used in generation of T --*/ + for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; + + /*-- compute the T vector --*/ + for (i = 0; i < nblock; i++) { + uc = (UChar)(s->ll16[i]); + SET_LL(i, s->cftabCopy[uc]); + s->cftabCopy[uc]++; + } + + /*-- Compute T^(-1) by pointer reversal on T --*/ + i = s->origPtr; + j = GET_LL(i); + do { + Int32 tmp = GET_LL(j); + SET_LL(j, i); + i = j; + j = tmp; + } + while (i != s->origPtr); + + s->tPos = s->origPtr; + s->nblock_used = 0; + if (s->blockRandomised) { + BZ_RAND_INIT_MASK; + BZ_GET_SMALL(s->k0); s->nblock_used++; + BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; + } else { + BZ_GET_SMALL(s->k0); s->nblock_used++; + } + + } else { + + /*-- compute the T^(-1) vector --*/ + for (i = 0; i < nblock; i++) { + uc = (UChar)(s->tt[i] & 0xff); + s->tt[s->cftab[uc]] |= (i << 8); + s->cftab[uc]++; + } + + s->tPos = s->tt[s->origPtr] >> 8; + s->nblock_used = 0; + if (s->blockRandomised) { + BZ_RAND_INIT_MASK; + BZ_GET_FAST(s->k0); s->nblock_used++; + BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; + } else { + BZ_GET_FAST(s->k0); s->nblock_used++; + } + + } + + RETURN(BZ_OK); + + + + endhdr_2: + + GET_UCHAR(BZ_X_ENDHDR_2, uc); + if (uc != 0x72) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_3, uc); + if (uc != 0x45) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_4, uc); + if (uc != 0x38) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_5, uc); + if (uc != 0x50) RETURN(BZ_DATA_ERROR); + GET_UCHAR(BZ_X_ENDHDR_6, uc); + if (uc != 0x90) RETURN(BZ_DATA_ERROR); + + s->storedCombinedCRC = 0; + GET_UCHAR(BZ_X_CCRC_1, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_CCRC_2, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_CCRC_3, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + GET_UCHAR(BZ_X_CCRC_4, uc); + s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); + + s->state = BZ_X_IDLE; + RETURN(BZ_STREAM_END); + + default: AssertH ( False, 4001 ); + } + + AssertH ( False, 4002 ); + + save_state_and_return: + + s->save_i = i; + s->save_j = j; + s->save_t = t; + s->save_alphaSize = alphaSize; + s->save_nGroups = nGroups; + s->save_nSelectors = nSelectors; + s->save_EOB = EOB; + s->save_groupNo = groupNo; + s->save_groupPos = groupPos; + s->save_nextSym = nextSym; + s->save_nblockMAX = nblockMAX; + s->save_nblock = nblock; + s->save_es = es; + s->save_N = N; + s->save_curr = curr; + s->save_zt = zt; + s->save_zn = zn; + s->save_zvec = zvec; + s->save_zj = zj; + s->save_gSel = gSel; + s->save_gMinlen = gMinlen; + s->save_gLimit = gLimit; + s->save_gBase = gBase; + s->save_gPerm = gPerm; + + return retVal; +} + + +/*-------------------------------------------------------------*/ +/*--- end decompress.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/bzlib.c b/src/libbz2/bzlib.c new file mode 100644 index 0000000..7d1cb27 --- /dev/null +++ b/src/libbz2/bzlib.c @@ -0,0 +1,1593 @@ + +/*-------------------------------------------------------------*/ +/*--- Library top-level functions. ---*/ +/*--- bzlib.c ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + +/*-- + CHANGES + ~~~~~~~ + 0.9.0 -- original version. + + 0.9.0a/b -- no changes in this file. + + 0.9.0c + * made zero-length BZ_FLUSH work correctly in bzCompress(). + * fixed bzWrite/bzRead to ignore zero-length requests. + * fixed bzread to correctly handle read requests after EOF. + * wrong parameter order in call to bzDecompressInit in + bzBuffToBuffDecompress. Fixed. +--*/ + +#include "bzlib_private.h" + + +/*---------------------------------------------------*/ +/*--- Compression stuff ---*/ +/*---------------------------------------------------*/ + + +/*---------------------------------------------------*/ +#ifndef BZ_NO_STDIO +void BZ2_bz__AssertH__fail ( int errcode ) +{ + fprintf(stderr, + "\n\nbzip2/libbzip2: internal error number %d.\n" + "This is a bug in bzip2/libbzip2, %s.\n" + "Please report it to me at: jseward@acm.org. If this happened\n" + "when you were using some program which uses libbzip2 as a\n" + "component, you should also report this bug to the author(s)\n" + "of that program. Please make an effort to report this bug;\n" + "timely and accurate bug reports eventually lead to higher\n" + "quality software. Thanks. Julian Seward, 30 December 2001.\n\n", + errcode, + BZ2_bzlibVersion() + ); + + if (errcode == 1007) { + fprintf(stderr, + "\n*** A special note about internal error number 1007 ***\n" + "\n" + "Experience suggests that a common cause of i.e. 1007\n" + "is unreliable memory or other hardware. The 1007 assertion\n" + "just happens to cross-check the results of huge numbers of\n" + "memory reads/writes, and so acts (unintendedly) as a stress\n" + "test of your memory system.\n" + "\n" + "I suggest the following: try compressing the file again,\n" + "possibly monitoring progress in detail with the -vv flag.\n" + "\n" + "* If the error cannot be reproduced, and/or happens at different\n" + " points in compression, you may have a flaky memory system.\n" + " Try a memory-test program. I have used Memtest86\n" + " (www.memtest86.com). At the time of writing it is free (GPLd).\n" + " Memtest86 tests memory much more thorougly than your BIOSs\n" + " power-on test, and may find failures that the BIOS doesn't.\n" + "\n" + "* If the error can be repeatably reproduced, this is a bug in\n" + " bzip2, and I would very much like to hear about it. Please\n" + " let me know, and, ideally, save a copy of the file causing the\n" + " problem -- without which I will be unable to investigate it.\n" + "\n" + ); + } + + exit(3); +} +#endif + + +/*---------------------------------------------------*/ +static +int bz_config_ok ( void ) +{ + if (sizeof(int) != 4) return 0; + if (sizeof(short) != 2) return 0; + if (sizeof(char) != 1) return 0; + return 1; +} + + +/*---------------------------------------------------*/ +static +void* default_bzalloc ( void* opaque, Int32 items, Int32 size ) +{ + void* v = malloc ( items * size ); + return v; +} + +static +void default_bzfree ( void* opaque, void* addr ) +{ + if (addr != NULL) free ( addr ); +} + + +/*---------------------------------------------------*/ +static +void prepare_new_block ( EState* s ) +{ + Int32 i; + s->nblock = 0; + s->numZ = 0; + s->state_out_pos = 0; + BZ_INITIALISE_CRC ( s->blockCRC ); + for (i = 0; i < 256; i++) s->inUse[i] = False; + s->blockNo++; +} + + +/*---------------------------------------------------*/ +static +void init_RL ( EState* s ) +{ + s->state_in_ch = 256; + s->state_in_len = 0; +} + + +static +Bool isempty_RL ( EState* s ) +{ + if (s->state_in_ch < 256 && s->state_in_len > 0) + return False; else + return True; +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzCompressInit) + ( bz_stream* strm, + int blockSize100k, + int verbosity, + int workFactor ) +{ + Int32 n; + EState* s; + + if (!bz_config_ok()) return BZ_CONFIG_ERROR; + + if (strm == NULL || + blockSize100k < 1 || blockSize100k > 9 || + workFactor < 0 || workFactor > 250) + return BZ_PARAM_ERROR; + + if (workFactor == 0) workFactor = 30; + if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; + if (strm->bzfree == NULL) strm->bzfree = default_bzfree; + + s = BZALLOC( sizeof(EState) ); + if (s == NULL) return BZ_MEM_ERROR; + s->strm = strm; + + s->arr1 = NULL; + s->arr2 = NULL; + s->ftab = NULL; + + n = 100000 * blockSize100k; + s->arr1 = BZALLOC( n * sizeof(UInt32) ); + s->arr2 = BZALLOC( (n+BZ_N_OVERSHOOT) * sizeof(UInt32) ); + s->ftab = BZALLOC( 65537 * sizeof(UInt32) ); + + if (s->arr1 == NULL || s->arr2 == NULL || s->ftab == NULL) { + if (s->arr1 != NULL) BZFREE(s->arr1); + if (s->arr2 != NULL) BZFREE(s->arr2); + if (s->ftab != NULL) BZFREE(s->ftab); + if (s != NULL) BZFREE(s); + return BZ_MEM_ERROR; + } + + s->blockNo = 0; + s->state = BZ_S_INPUT; + s->mode = BZ_M_RUNNING; + s->combinedCRC = 0; + s->blockSize100k = blockSize100k; + s->nblockMAX = 100000 * blockSize100k - 19; + s->verbosity = verbosity; + s->workFactor = workFactor; + + s->block = (UChar*)s->arr2; + s->mtfv = (UInt16*)s->arr1; + s->zbits = NULL; + s->ptr = (UInt32*)s->arr1; + + strm->state = s; + strm->total_in_lo32 = 0; + strm->total_in_hi32 = 0; + strm->total_out_lo32 = 0; + strm->total_out_hi32 = 0; + init_RL ( s ); + prepare_new_block ( s ); + return BZ_OK; +} + + +/*---------------------------------------------------*/ +static +void add_pair_to_block ( EState* s ) +{ + Int32 i; + UChar ch = (UChar)(s->state_in_ch); + for (i = 0; i < s->state_in_len; i++) { + BZ_UPDATE_CRC( s->blockCRC, ch ); + } + s->inUse[s->state_in_ch] = True; + switch (s->state_in_len) { + case 1: + s->block[s->nblock] = (UChar)ch; s->nblock++; + break; + case 2: + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + break; + case 3: + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + break; + default: + s->inUse[s->state_in_len-4] = True; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = (UChar)ch; s->nblock++; + s->block[s->nblock] = ((UChar)(s->state_in_len-4)); + s->nblock++; + break; + } +} + + +/*---------------------------------------------------*/ +static +void flush_RL ( EState* s ) +{ + if (s->state_in_ch < 256) add_pair_to_block ( s ); + init_RL ( s ); +} + + +/*---------------------------------------------------*/ +#define ADD_CHAR_TO_BLOCK(zs,zchh0) \ +{ \ + UInt32 zchh = (UInt32)(zchh0); \ + /*-- fast track the common case --*/ \ + if (zchh != zs->state_in_ch && \ + zs->state_in_len == 1) { \ + UChar ch = (UChar)(zs->state_in_ch); \ + BZ_UPDATE_CRC( zs->blockCRC, ch ); \ + zs->inUse[zs->state_in_ch] = True; \ + zs->block[zs->nblock] = (UChar)ch; \ + zs->nblock++; \ + zs->state_in_ch = zchh; \ + } \ + else \ + /*-- general, uncommon cases --*/ \ + if (zchh != zs->state_in_ch || \ + zs->state_in_len == 255) { \ + if (zs->state_in_ch < 256) \ + add_pair_to_block ( zs ); \ + zs->state_in_ch = zchh; \ + zs->state_in_len = 1; \ + } else { \ + zs->state_in_len++; \ + } \ +} + + +/*---------------------------------------------------*/ +static +Bool copy_input_until_stop ( EState* s ) +{ + Bool progress_in = False; + + if (s->mode == BZ_M_RUNNING) { + + /*-- fast track the common case --*/ + while (True) { + /*-- block full? --*/ + if (s->nblock >= s->nblockMAX) break; + /*-- no input? --*/ + if (s->strm->avail_in == 0) break; + progress_in = True; + ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); + s->strm->next_in++; + s->strm->avail_in--; + s->strm->total_in_lo32++; + if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; + } + + } else { + + /*-- general, uncommon case --*/ + while (True) { + /*-- block full? --*/ + if (s->nblock >= s->nblockMAX) break; + /*-- no input? --*/ + if (s->strm->avail_in == 0) break; + /*-- flush/finish end? --*/ + if (s->avail_in_expect == 0) break; + progress_in = True; + ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); + s->strm->next_in++; + s->strm->avail_in--; + s->strm->total_in_lo32++; + if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; + s->avail_in_expect--; + } + } + return progress_in; +} + + +/*---------------------------------------------------*/ +static +Bool copy_output_until_stop ( EState* s ) +{ + Bool progress_out = False; + + while (True) { + + /*-- no output space? --*/ + if (s->strm->avail_out == 0) break; + + /*-- block done? --*/ + if (s->state_out_pos >= s->numZ) break; + + progress_out = True; + *(s->strm->next_out) = s->zbits[s->state_out_pos]; + s->state_out_pos++; + s->strm->avail_out--; + s->strm->next_out++; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + return progress_out; +} + + +/*---------------------------------------------------*/ +static +Bool handle_compress ( bz_stream* strm ) +{ + Bool progress_in = False; + Bool progress_out = False; + EState* s = strm->state; + + while (True) { + + if (s->state == BZ_S_OUTPUT) { + progress_out |= copy_output_until_stop ( s ); + if (s->state_out_pos < s->numZ) break; + if (s->mode == BZ_M_FINISHING && + s->avail_in_expect == 0 && + isempty_RL(s)) break; + prepare_new_block ( s ); + s->state = BZ_S_INPUT; + if (s->mode == BZ_M_FLUSHING && + s->avail_in_expect == 0 && + isempty_RL(s)) break; + } + + if (s->state == BZ_S_INPUT) { + progress_in |= copy_input_until_stop ( s ); + if (s->mode != BZ_M_RUNNING && s->avail_in_expect == 0) { + flush_RL ( s ); + BZ2_compressBlock ( s, (Bool)(s->mode == BZ_M_FINISHING) ); + s->state = BZ_S_OUTPUT; + } + else + if (s->nblock >= s->nblockMAX) { + BZ2_compressBlock ( s, False ); + s->state = BZ_S_OUTPUT; + } + else + if (s->strm->avail_in == 0) { + break; + } + } + + } + + return progress_in || progress_out; +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action ) +{ + Bool progress; + EState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + preswitch: + switch (s->mode) { + + case BZ_M_IDLE: + return BZ_SEQUENCE_ERROR; + + case BZ_M_RUNNING: + if (action == BZ_RUN) { + progress = handle_compress ( strm ); + return progress ? BZ_RUN_OK : BZ_PARAM_ERROR; + } + else + if (action == BZ_FLUSH) { + s->avail_in_expect = strm->avail_in; + s->mode = BZ_M_FLUSHING; + goto preswitch; + } + else + if (action == BZ_FINISH) { + s->avail_in_expect = strm->avail_in; + s->mode = BZ_M_FINISHING; + goto preswitch; + } + else + return BZ_PARAM_ERROR; + + case BZ_M_FLUSHING: + if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR; + if (s->avail_in_expect != s->strm->avail_in) + return BZ_SEQUENCE_ERROR; + progress = handle_compress ( strm ); + if (s->avail_in_expect > 0 || !isempty_RL(s) || + s->state_out_pos < s->numZ) return BZ_FLUSH_OK; + s->mode = BZ_M_RUNNING; + return BZ_RUN_OK; + + case BZ_M_FINISHING: + if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR; + if (s->avail_in_expect != s->strm->avail_in) + return BZ_SEQUENCE_ERROR; + progress = handle_compress ( strm ); + if (!progress) return BZ_SEQUENCE_ERROR; + if (s->avail_in_expect > 0 || !isempty_RL(s) || + s->state_out_pos < s->numZ) return BZ_FINISH_OK; + s->mode = BZ_M_IDLE; + return BZ_STREAM_END; + } + return BZ_OK; /*--not reached--*/ +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzCompressEnd) ( bz_stream *strm ) +{ + EState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + if (s->arr1 != NULL) BZFREE(s->arr1); + if (s->arr2 != NULL) BZFREE(s->arr2); + if (s->ftab != NULL) BZFREE(s->ftab); + BZFREE(strm->state); + + strm->state = NULL; + + return BZ_OK; +} + + +/*---------------------------------------------------*/ +/*--- Decompression stuff ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzDecompressInit) + ( bz_stream* strm, + int verbosity, + int small ) +{ + DState* s; + + if (!bz_config_ok()) return BZ_CONFIG_ERROR; + + if (strm == NULL) return BZ_PARAM_ERROR; + if (small != 0 && small != 1) return BZ_PARAM_ERROR; + if (verbosity < 0 || verbosity > 4) return BZ_PARAM_ERROR; + + if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; + if (strm->bzfree == NULL) strm->bzfree = default_bzfree; + + s = BZALLOC( sizeof(DState) ); + if (s == NULL) return BZ_MEM_ERROR; + s->strm = strm; + strm->state = s; + s->state = BZ_X_MAGIC_1; + s->bsLive = 0; + s->bsBuff = 0; + s->calculatedCombinedCRC = 0; + strm->total_in_lo32 = 0; + strm->total_in_hi32 = 0; + strm->total_out_lo32 = 0; + strm->total_out_hi32 = 0; + s->smallDecompress = (Bool)small; + s->ll4 = NULL; + s->ll16 = NULL; + s->tt = NULL; + s->currBlockNo = 0; + s->verbosity = verbosity; + + return BZ_OK; +} + + +/*---------------------------------------------------*/ +static +void unRLE_obuf_to_output_FAST ( DState* s ) +{ + UChar k1; + + if (s->blockRandomised) { + + while (True) { + /* try to finish existing run */ + while (True) { + if (s->strm->avail_out == 0) return; + if (s->state_out_len == 0) break; + *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; + BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); + s->state_out_len--; + s->strm->next_out++; + s->strm->avail_out--; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + /* can a new run be started? */ + if (s->nblock_used == s->save_nblock+1) return; + + + s->state_out_len = 1; + s->state_out_ch = s->k0; + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 2; + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 3; + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + s->state_out_len = ((Int32)k1) + 4; + BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK; + s->k0 ^= BZ_RAND_MASK; s->nblock_used++; + } + + } else { + + /* restore */ + UInt32 c_calculatedBlockCRC = s->calculatedBlockCRC; + UChar c_state_out_ch = s->state_out_ch; + Int32 c_state_out_len = s->state_out_len; + Int32 c_nblock_used = s->nblock_used; + Int32 c_k0 = s->k0; + UInt32* c_tt = s->tt; + UInt32 c_tPos = s->tPos; + char* cs_next_out = s->strm->next_out; + unsigned int cs_avail_out = s->strm->avail_out; + /* end restore */ + + UInt32 avail_out_INIT = cs_avail_out; + Int32 s_save_nblockPP = s->save_nblock+1; + unsigned int total_out_lo32_old; + + while (True) { + + /* try to finish existing run */ + if (c_state_out_len > 0) { + while (True) { + if (cs_avail_out == 0) goto return_notr; + if (c_state_out_len == 1) break; + *( (UChar*)(cs_next_out) ) = c_state_out_ch; + BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); + c_state_out_len--; + cs_next_out++; + cs_avail_out--; + } + s_state_out_len_eq_one: + { + if (cs_avail_out == 0) { + c_state_out_len = 1; goto return_notr; + }; + *( (UChar*)(cs_next_out) ) = c_state_out_ch; + BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); + cs_next_out++; + cs_avail_out--; + } + } + /* can a new run be started? */ + if (c_nblock_used == s_save_nblockPP) { + c_state_out_len = 0; goto return_notr; + }; + c_state_out_ch = c_k0; + BZ_GET_FAST_C(k1); c_nblock_used++; + if (k1 != c_k0) { + c_k0 = k1; goto s_state_out_len_eq_one; + }; + if (c_nblock_used == s_save_nblockPP) + goto s_state_out_len_eq_one; + + c_state_out_len = 2; + BZ_GET_FAST_C(k1); c_nblock_used++; + if (c_nblock_used == s_save_nblockPP) continue; + if (k1 != c_k0) { c_k0 = k1; continue; }; + + c_state_out_len = 3; + BZ_GET_FAST_C(k1); c_nblock_used++; + if (c_nblock_used == s_save_nblockPP) continue; + if (k1 != c_k0) { c_k0 = k1; continue; }; + + BZ_GET_FAST_C(k1); c_nblock_used++; + c_state_out_len = ((Int32)k1) + 4; + BZ_GET_FAST_C(c_k0); c_nblock_used++; + } + + return_notr: + total_out_lo32_old = s->strm->total_out_lo32; + s->strm->total_out_lo32 += (avail_out_INIT - cs_avail_out); + if (s->strm->total_out_lo32 < total_out_lo32_old) + s->strm->total_out_hi32++; + + /* save */ + s->calculatedBlockCRC = c_calculatedBlockCRC; + s->state_out_ch = c_state_out_ch; + s->state_out_len = c_state_out_len; + s->nblock_used = c_nblock_used; + s->k0 = c_k0; + s->tt = c_tt; + s->tPos = c_tPos; + s->strm->next_out = cs_next_out; + s->strm->avail_out = cs_avail_out; + /* end save */ + } +} + + + +/*---------------------------------------------------*/ +__inline__ Int32 BZ2_indexIntoF ( Int32 indx, Int32 *cftab ) +{ + Int32 nb, na, mid; + nb = 0; + na = 256; + do { + mid = (nb + na) >> 1; + if (indx >= cftab[mid]) nb = mid; else na = mid; + } + while (na - nb != 1); + return nb; +} + + +/*---------------------------------------------------*/ +static +void unRLE_obuf_to_output_SMALL ( DState* s ) +{ + UChar k1; + + if (s->blockRandomised) { + + while (True) { + /* try to finish existing run */ + while (True) { + if (s->strm->avail_out == 0) return; + if (s->state_out_len == 0) break; + *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; + BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); + s->state_out_len--; + s->strm->next_out++; + s->strm->avail_out--; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + /* can a new run be started? */ + if (s->nblock_used == s->save_nblock+1) return; + + + s->state_out_len = 1; + s->state_out_ch = s->k0; + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 2; + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 3; + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; + k1 ^= BZ_RAND_MASK; s->nblock_used++; + s->state_out_len = ((Int32)k1) + 4; + BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK; + s->k0 ^= BZ_RAND_MASK; s->nblock_used++; + } + + } else { + + while (True) { + /* try to finish existing run */ + while (True) { + if (s->strm->avail_out == 0) return; + if (s->state_out_len == 0) break; + *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; + BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); + s->state_out_len--; + s->strm->next_out++; + s->strm->avail_out--; + s->strm->total_out_lo32++; + if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; + } + + /* can a new run be started? */ + if (s->nblock_used == s->save_nblock+1) return; + + s->state_out_len = 1; + s->state_out_ch = s->k0; + BZ_GET_SMALL(k1); s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 2; + BZ_GET_SMALL(k1); s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + s->state_out_len = 3; + BZ_GET_SMALL(k1); s->nblock_used++; + if (s->nblock_used == s->save_nblock+1) continue; + if (k1 != s->k0) { s->k0 = k1; continue; }; + + BZ_GET_SMALL(k1); s->nblock_used++; + s->state_out_len = ((Int32)k1) + 4; + BZ_GET_SMALL(s->k0); s->nblock_used++; + } + + } +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzDecompress) ( bz_stream *strm ) +{ + DState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + while (True) { + if (s->state == BZ_X_IDLE) return BZ_SEQUENCE_ERROR; + if (s->state == BZ_X_OUTPUT) { + if (s->smallDecompress) + unRLE_obuf_to_output_SMALL ( s ); else + unRLE_obuf_to_output_FAST ( s ); + if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) { + BZ_FINALISE_CRC ( s->calculatedBlockCRC ); + if (s->verbosity >= 3) + VPrintf2 ( " {0x%x, 0x%x}", s->storedBlockCRC, + s->calculatedBlockCRC ); + if (s->verbosity >= 2) VPrintf0 ( "]" ); + if (s->calculatedBlockCRC != s->storedBlockCRC) + return BZ_DATA_ERROR; + s->calculatedCombinedCRC + = (s->calculatedCombinedCRC << 1) | + (s->calculatedCombinedCRC >> 31); + s->calculatedCombinedCRC ^= s->calculatedBlockCRC; + s->state = BZ_X_BLKHDR_1; + } else { + return BZ_OK; + } + } + if (s->state >= BZ_X_MAGIC_1) { + Int32 r = BZ2_decompress ( s ); + if (r == BZ_STREAM_END) { + if (s->verbosity >= 3) + VPrintf2 ( "\n combined CRCs: stored = 0x%x, computed = 0x%x", + s->storedCombinedCRC, s->calculatedCombinedCRC ); + if (s->calculatedCombinedCRC != s->storedCombinedCRC) + return BZ_DATA_ERROR; + return r; + } + if (s->state != BZ_X_OUTPUT) return r; + } + } + + AssertH ( 0, 6001 ); + + return 0; /*NOTREACHED*/ +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm ) +{ + DState* s; + if (strm == NULL) return BZ_PARAM_ERROR; + s = strm->state; + if (s == NULL) return BZ_PARAM_ERROR; + if (s->strm != strm) return BZ_PARAM_ERROR; + + if (s->tt != NULL) BZFREE(s->tt); + if (s->ll16 != NULL) BZFREE(s->ll16); + if (s->ll4 != NULL) BZFREE(s->ll4); + + BZFREE(strm->state); + strm->state = NULL; + + return BZ_OK; +} + + +#ifndef BZ_NO_STDIO +/*---------------------------------------------------*/ +/*--- File I/O stuff ---*/ +/*---------------------------------------------------*/ + +#define BZ_SETERR(eee) \ +{ \ + if (bzerror != NULL) *bzerror = eee; \ + if (bzf != NULL) bzf->lastErr = eee; \ +} + +typedef + struct { + FILE* handle; + Char buf[BZ_MAX_UNUSED]; + Int32 bufN; + Bool writing; + bz_stream strm; + Int32 lastErr; + Bool initialisedOk; + } + bzFile; + + +/*---------------------------------------------*/ +static Bool myfeof ( FILE* f ) +{ + Int32 c = fgetc ( f ); + if (c == EOF) return True; + ungetc ( c, f ); + return False; +} + + +/*---------------------------------------------------*/ +BZFILE* BZ_API(BZ2_bzWriteOpen) + ( int* bzerror, + FILE* f, + int blockSize100k, + int verbosity, + int workFactor ) +{ + Int32 ret; + bzFile* bzf = NULL; + + BZ_SETERR(BZ_OK); + + if (f == NULL || + (blockSize100k < 1 || blockSize100k > 9) || + (workFactor < 0 || workFactor > 250) || + (verbosity < 0 || verbosity > 4)) + { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; + + if (ferror(f)) + { BZ_SETERR(BZ_IO_ERROR); return NULL; }; + + bzf = malloc ( sizeof(bzFile) ); + if (bzf == NULL) + { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; + + BZ_SETERR(BZ_OK); + bzf->initialisedOk = False; + bzf->bufN = 0; + bzf->handle = f; + bzf->writing = True; + bzf->strm.bzalloc = NULL; + bzf->strm.bzfree = NULL; + bzf->strm.opaque = NULL; + + if (workFactor == 0) workFactor = 30; + ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k, + verbosity, workFactor ); + if (ret != BZ_OK) + { BZ_SETERR(ret); free(bzf); return NULL; }; + + bzf->strm.avail_in = 0; + bzf->initialisedOk = True; + return bzf; +} + + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzWrite) + ( int* bzerror, + BZFILE* b, + void* buf, + int len ) +{ + Int32 n, n2, ret; + bzFile* bzf = (bzFile*)b; + + BZ_SETERR(BZ_OK); + if (bzf == NULL || buf == NULL || len < 0) + { BZ_SETERR(BZ_PARAM_ERROR); return; }; + if (!(bzf->writing)) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + + if (len == 0) + { BZ_SETERR(BZ_OK); return; }; + + bzf->strm.avail_in = len; + bzf->strm.next_in = buf; + + while (True) { + bzf->strm.avail_out = BZ_MAX_UNUSED; + bzf->strm.next_out = bzf->buf; + ret = BZ2_bzCompress ( &(bzf->strm), BZ_RUN ); + if (ret != BZ_RUN_OK) + { BZ_SETERR(ret); return; }; + + if (bzf->strm.avail_out < BZ_MAX_UNUSED) { + n = BZ_MAX_UNUSED - bzf->strm.avail_out; + n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), + n, bzf->handle ); + if (n != n2 || ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + } + + if (bzf->strm.avail_in == 0) + { BZ_SETERR(BZ_OK); return; }; + } +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzWriteClose) + ( int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in, + unsigned int* nbytes_out ) +{ + BZ2_bzWriteClose64 ( bzerror, b, abandon, + nbytes_in, NULL, nbytes_out, NULL ); +} + + +void BZ_API(BZ2_bzWriteClose64) + ( int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in_lo32, + unsigned int* nbytes_in_hi32, + unsigned int* nbytes_out_lo32, + unsigned int* nbytes_out_hi32 ) +{ + Int32 n, n2, ret; + bzFile* bzf = (bzFile*)b; + + if (bzf == NULL) + { BZ_SETERR(BZ_OK); return; }; + if (!(bzf->writing)) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + + if (nbytes_in_lo32 != NULL) *nbytes_in_lo32 = 0; + if (nbytes_in_hi32 != NULL) *nbytes_in_hi32 = 0; + if (nbytes_out_lo32 != NULL) *nbytes_out_lo32 = 0; + if (nbytes_out_hi32 != NULL) *nbytes_out_hi32 = 0; + + if ((!abandon) && bzf->lastErr == BZ_OK) { + while (True) { + bzf->strm.avail_out = BZ_MAX_UNUSED; + bzf->strm.next_out = bzf->buf; + ret = BZ2_bzCompress ( &(bzf->strm), BZ_FINISH ); + if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) + { BZ_SETERR(ret); return; }; + + if (bzf->strm.avail_out < BZ_MAX_UNUSED) { + n = BZ_MAX_UNUSED - bzf->strm.avail_out; + n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), + n, bzf->handle ); + if (n != n2 || ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + } + + if (ret == BZ_STREAM_END) break; + } + } + + if ( !abandon && !ferror ( bzf->handle ) ) { + fflush ( bzf->handle ); + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return; }; + } + + if (nbytes_in_lo32 != NULL) + *nbytes_in_lo32 = bzf->strm.total_in_lo32; + if (nbytes_in_hi32 != NULL) + *nbytes_in_hi32 = bzf->strm.total_in_hi32; + if (nbytes_out_lo32 != NULL) + *nbytes_out_lo32 = bzf->strm.total_out_lo32; + if (nbytes_out_hi32 != NULL) + *nbytes_out_hi32 = bzf->strm.total_out_hi32; + + BZ_SETERR(BZ_OK); + BZ2_bzCompressEnd ( &(bzf->strm) ); + free ( bzf ); +} + + +/*---------------------------------------------------*/ +BZFILE* BZ_API(BZ2_bzReadOpen) + ( int* bzerror, + FILE* f, + int verbosity, + int small, + void* unused, + int nUnused ) +{ + bzFile* bzf = NULL; + int ret; + + BZ_SETERR(BZ_OK); + + if (f == NULL || + (small != 0 && small != 1) || + (verbosity < 0 || verbosity > 4) || + (unused == NULL && nUnused != 0) || + (unused != NULL && (nUnused < 0 || nUnused > BZ_MAX_UNUSED))) + { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; + + if (ferror(f)) + { BZ_SETERR(BZ_IO_ERROR); return NULL; }; + + bzf = malloc ( sizeof(bzFile) ); + if (bzf == NULL) + { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; + + BZ_SETERR(BZ_OK); + + bzf->initialisedOk = False; + bzf->handle = f; + bzf->bufN = 0; + bzf->writing = False; + bzf->strm.bzalloc = NULL; + bzf->strm.bzfree = NULL; + bzf->strm.opaque = NULL; + + while (nUnused > 0) { + bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++; + unused = ((void*)( 1 + ((UChar*)(unused)) )); + nUnused--; + } + + ret = BZ2_bzDecompressInit ( &(bzf->strm), verbosity, small ); + if (ret != BZ_OK) + { BZ_SETERR(ret); free(bzf); return NULL; }; + + bzf->strm.avail_in = bzf->bufN; + bzf->strm.next_in = bzf->buf; + + bzf->initialisedOk = True; + return bzf; +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzReadClose) ( int *bzerror, BZFILE *b ) +{ + bzFile* bzf = (bzFile*)b; + + BZ_SETERR(BZ_OK); + if (bzf == NULL) + { BZ_SETERR(BZ_OK); return; }; + + if (bzf->writing) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + + if (bzf->initialisedOk) + (void)BZ2_bzDecompressEnd ( &(bzf->strm) ); + free ( bzf ); +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzRead) + ( int* bzerror, + BZFILE* b, + void* buf, + int len ) +{ + Int32 n, ret; + bzFile* bzf = (bzFile*)b; + + BZ_SETERR(BZ_OK); + + if (bzf == NULL || buf == NULL || len < 0) + { BZ_SETERR(BZ_PARAM_ERROR); return 0; }; + + if (bzf->writing) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return 0; }; + + if (len == 0) + { BZ_SETERR(BZ_OK); return 0; }; + + bzf->strm.avail_out = len; + bzf->strm.next_out = buf; + + while (True) { + + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return 0; }; + + if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) { + n = fread ( bzf->buf, sizeof(UChar), + BZ_MAX_UNUSED, bzf->handle ); + if (ferror(bzf->handle)) + { BZ_SETERR(BZ_IO_ERROR); return 0; }; + bzf->bufN = n; + bzf->strm.avail_in = bzf->bufN; + bzf->strm.next_in = bzf->buf; + } + + ret = BZ2_bzDecompress ( &(bzf->strm) ); + + if (ret != BZ_OK && ret != BZ_STREAM_END) + { BZ_SETERR(ret); return 0; }; + + if (ret == BZ_OK && myfeof(bzf->handle) && + bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0) + { BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; }; + + if (ret == BZ_STREAM_END) + { BZ_SETERR(BZ_STREAM_END); + return len - bzf->strm.avail_out; }; + if (bzf->strm.avail_out == 0) + { BZ_SETERR(BZ_OK); return len; }; + + } + + return 0; /*not reached*/ +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzReadGetUnused) + ( int* bzerror, + BZFILE* b, + void** unused, + int* nUnused ) +{ + bzFile* bzf = (bzFile*)b; + if (bzf == NULL) + { BZ_SETERR(BZ_PARAM_ERROR); return; }; + if (bzf->lastErr != BZ_STREAM_END) + { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; + if (unused == NULL || nUnused == NULL) + { BZ_SETERR(BZ_PARAM_ERROR); return; }; + + BZ_SETERR(BZ_OK); + *nUnused = bzf->strm.avail_in; + *unused = bzf->strm.next_in; +} +#endif + + +/*---------------------------------------------------*/ +/*--- Misc convenience stuff ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzBuffToBuffCompress) + ( char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int blockSize100k, + int verbosity, + int workFactor ) +{ + bz_stream strm; + int ret; + + if (dest == NULL || destLen == NULL || + source == NULL || + blockSize100k < 1 || blockSize100k > 9 || + verbosity < 0 || verbosity > 4 || + workFactor < 0 || workFactor > 250) + return BZ_PARAM_ERROR; + + if (workFactor == 0) workFactor = 30; + strm.bzalloc = NULL; + strm.bzfree = NULL; + strm.opaque = NULL; + ret = BZ2_bzCompressInit ( &strm, blockSize100k, + verbosity, workFactor ); + if (ret != BZ_OK) return ret; + + strm.next_in = source; + strm.next_out = dest; + strm.avail_in = sourceLen; + strm.avail_out = *destLen; + + ret = BZ2_bzCompress ( &strm, BZ_FINISH ); + if (ret == BZ_FINISH_OK) goto output_overflow; + if (ret != BZ_STREAM_END) goto errhandler; + + /* normal termination */ + *destLen -= strm.avail_out; + BZ2_bzCompressEnd ( &strm ); + return BZ_OK; + + output_overflow: + BZ2_bzCompressEnd ( &strm ); + return BZ_OUTBUFF_FULL; + + errhandler: + BZ2_bzCompressEnd ( &strm ); + return ret; +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzBuffToBuffDecompress) + ( char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int small, + int verbosity ) +{ + bz_stream strm; + int ret; + + if (dest == NULL || destLen == NULL || + source == NULL || + (small != 0 && small != 1) || + verbosity < 0 || verbosity > 4) + return BZ_PARAM_ERROR; + + strm.bzalloc = NULL; + strm.bzfree = NULL; + strm.opaque = NULL; + ret = BZ2_bzDecompressInit ( &strm, verbosity, small ); + if (ret != BZ_OK) return ret; + + strm.next_in = source; + strm.next_out = dest; + strm.avail_in = sourceLen; + strm.avail_out = *destLen; + + ret = BZ2_bzDecompress ( &strm ); + if (ret == BZ_OK) goto output_overflow_or_eof; + if (ret != BZ_STREAM_END) goto errhandler; + + /* normal termination */ + *destLen -= strm.avail_out; + BZ2_bzDecompressEnd ( &strm ); + return BZ_OK; + + output_overflow_or_eof: + if (strm.avail_out > 0) { + BZ2_bzDecompressEnd ( &strm ); + return BZ_UNEXPECTED_EOF; + } else { + BZ2_bzDecompressEnd ( &strm ); + return BZ_OUTBUFF_FULL; + }; + + errhandler: + BZ2_bzDecompressEnd ( &strm ); + return ret; +} + + +/*---------------------------------------------------*/ +/*-- + Code contributed by Yoshioka Tsuneo + (QWF00133@niftyserve.or.jp/tsuneo-y@is.aist-nara.ac.jp), + to support better zlib compatibility. + This code is not _officially_ part of libbzip2 (yet); + I haven't tested it, documented it, or considered the + threading-safeness of it. + If this code breaks, please contact both Yoshioka and me. +--*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------------*/ +/*-- + return version like "0.9.0c". +--*/ +const char * BZ_API(BZ2_bzlibVersion)(void) +{ + return BZ_VERSION; +} + + +#ifndef BZ_NO_STDIO +/*---------------------------------------------------*/ + +#if defined(_WIN32) || defined(OS2) || defined(MSDOS) +# include +# include +# define SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY) +#else +# define SET_BINARY_MODE(file) +#endif +static +BZFILE * bzopen_or_bzdopen + ( const char *path, /* no use when bzdopen */ + int fd, /* no use when bzdopen */ + const char *mode, + int open_mode) /* bzopen: 0, bzdopen:1 */ +{ + int bzerr; + char unused[BZ_MAX_UNUSED]; + int blockSize100k = 9; + int writing = 0; + char mode2[10] = ""; + FILE *fp = NULL; + BZFILE *bzfp = NULL; + int verbosity = 0; + int workFactor = 30; + int smallMode = 0; + int nUnused = 0; + + if (mode == NULL) return NULL; + while (*mode) { + switch (*mode) { + case 'r': + writing = 0; break; + case 'w': + writing = 1; break; + case 's': + smallMode = 1; break; + default: + if (isdigit((int)(*mode))) { + blockSize100k = *mode-BZ_HDR_0; + } + } + mode++; + } + strcat(mode2, writing ? "w" : "r" ); + strcat(mode2,"b"); /* binary mode */ + + if (open_mode==0) { + if (path==NULL || strcmp(path,"")==0) { + fp = (writing ? stdout : stdin); + SET_BINARY_MODE(fp); + } else { + fp = fopen(path,mode2); + } + } else { +#ifdef BZ_STRICT_ANSI + fp = NULL; +#else + fp = fdopen(fd,mode2); +#endif + } + if (fp == NULL) return NULL; + + if (writing) { + /* Guard against total chaos and anarchy -- JRS */ + if (blockSize100k < 1) blockSize100k = 1; + if (blockSize100k > 9) blockSize100k = 9; + bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k, + verbosity,workFactor); + } else { + bzfp = BZ2_bzReadOpen(&bzerr,fp,verbosity,smallMode, + unused,nUnused); + } + if (bzfp == NULL) { + if (fp != stdin && fp != stdout) fclose(fp); + return NULL; + } + return bzfp; +} + + +/*---------------------------------------------------*/ +/*-- + open file for read or write. + ex) bzopen("file","w9") + case path="" or NULL => use stdin or stdout. +--*/ +BZFILE * BZ_API(BZ2_bzopen) + ( const char *path, + const char *mode ) +{ + return bzopen_or_bzdopen(path,-1,mode,/*bzopen*/0); +} + + +/*---------------------------------------------------*/ +BZFILE * BZ_API(BZ2_bzdopen) + ( int fd, + const char *mode ) +{ + return bzopen_or_bzdopen(NULL,fd,mode,/*bzdopen*/1); +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzread) (BZFILE* b, void* buf, int len ) +{ + int bzerr, nread; + if (((bzFile*)b)->lastErr == BZ_STREAM_END) return 0; + nread = BZ2_bzRead(&bzerr,b,buf,len); + if (bzerr == BZ_OK || bzerr == BZ_STREAM_END) { + return nread; + } else { + return -1; + } +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzwrite) (BZFILE* b, void* buf, int len ) +{ + int bzerr; + + BZ2_bzWrite(&bzerr,b,buf,len); + if(bzerr == BZ_OK){ + return len; + }else{ + return -1; + } +} + + +/*---------------------------------------------------*/ +int BZ_API(BZ2_bzflush) (BZFILE *b) +{ + /* do nothing now... */ + return 0; +} + + +/*---------------------------------------------------*/ +void BZ_API(BZ2_bzclose) (BZFILE* b) +{ + int bzerr; + FILE *fp = ((bzFile *)b)->handle; + + if (b==NULL) {return;} + if(((bzFile*)b)->writing){ + BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL); + if(bzerr != BZ_OK){ + BZ2_bzWriteClose(NULL,b,1,NULL,NULL); + } + }else{ + BZ2_bzReadClose(&bzerr,b); + } + if(fp!=stdin && fp!=stdout){ + fclose(fp); + } +} + + +/*---------------------------------------------------*/ +/*-- + return last error code +--*/ +static char *bzerrorstrings[] = { + "OK" + ,"SEQUENCE_ERROR" + ,"PARAM_ERROR" + ,"MEM_ERROR" + ,"DATA_ERROR" + ,"DATA_ERROR_MAGIC" + ,"IO_ERROR" + ,"UNEXPECTED_EOF" + ,"OUTBUFF_FULL" + ,"CONFIG_ERROR" + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ + ,"???" /* for future */ +}; + + +const char * BZ_API(BZ2_bzerror) (BZFILE *b, int *errnum) +{ + int err = ((bzFile *)b)->lastErr; + + if(err>0) err = 0; + *errnum = err; + return bzerrorstrings[err*-1]; +} +#endif + + +/*-------------------------------------------------------------*/ +/*--- end bzlib.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/bzlib.h b/src/libbz2/bzlib.h new file mode 100644 index 0000000..9ac43a1 --- /dev/null +++ b/src/libbz2/bzlib.h @@ -0,0 +1,321 @@ + +/*-------------------------------------------------------------*/ +/*--- Public header file for the library. ---*/ +/*--- bzlib.h ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + + +#ifndef _BZLIB_H +#define _BZLIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define BZ_RUN 0 +#define BZ_FLUSH 1 +#define BZ_FINISH 2 + +#define BZ_OK 0 +#define BZ_RUN_OK 1 +#define BZ_FLUSH_OK 2 +#define BZ_FINISH_OK 3 +#define BZ_STREAM_END 4 +#define BZ_SEQUENCE_ERROR (-1) +#define BZ_PARAM_ERROR (-2) +#define BZ_MEM_ERROR (-3) +#define BZ_DATA_ERROR (-4) +#define BZ_DATA_ERROR_MAGIC (-5) +#define BZ_IO_ERROR (-6) +#define BZ_UNEXPECTED_EOF (-7) +#define BZ_OUTBUFF_FULL (-8) +#define BZ_CONFIG_ERROR (-9) + +typedef + struct { + char *next_in; + unsigned int avail_in; + unsigned int total_in_lo32; + unsigned int total_in_hi32; + + char *next_out; + unsigned int avail_out; + unsigned int total_out_lo32; + unsigned int total_out_hi32; + + void *state; + + void *(*bzalloc)(void *,int,int); + void (*bzfree)(void *,void *); + void *opaque; + } + bz_stream; + + +#ifndef BZ_IMPORT +#define BZ_EXPORT +#endif + +/* Need a definitition for FILE */ +#include + +#ifdef _WIN32 +# include +# ifdef small + /* windows.h define small to char */ +# undef small +# endif +# ifdef BZ_EXPORT +# define BZ_API(func) WINAPI func +# define BZ_EXTERN extern +# else + /* import windows dll dynamically */ +# define BZ_API(func) (WINAPI * func) +# define BZ_EXTERN +# endif +#else +# define BZ_API(func) func +# define BZ_EXTERN extern +#endif + + +/*-- Core (low-level) library functions --*/ + +BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( + bz_stream* strm, + int blockSize100k, + int verbosity, + int workFactor + ); + +BZ_EXTERN int BZ_API(BZ2_bzCompress) ( + bz_stream* strm, + int action + ); + +BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( + bz_stream* strm + ); + +BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( + bz_stream *strm, + int verbosity, + int small + ); + +BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( + bz_stream* strm + ); + +BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( + bz_stream *strm + ); + + + +/*-- High(er) level library functions --*/ + +#ifndef BZ_NO_STDIO +#define BZ_MAX_UNUSED 5000 + +typedef void BZFILE; + +BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( + int* bzerror, + FILE* f, + int verbosity, + int small, + void* unused, + int nUnused + ); + +BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( + int* bzerror, + BZFILE* b + ); + +BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( + int* bzerror, + BZFILE* b, + void** unused, + int* nUnused + ); + +BZ_EXTERN int BZ_API(BZ2_bzRead) ( + int* bzerror, + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( + int* bzerror, + FILE* f, + int blockSize100k, + int verbosity, + int workFactor + ); + +BZ_EXTERN void BZ_API(BZ2_bzWrite) ( + int* bzerror, + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( + int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in, + unsigned int* nbytes_out + ); + +BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( + int* bzerror, + BZFILE* b, + int abandon, + unsigned int* nbytes_in_lo32, + unsigned int* nbytes_in_hi32, + unsigned int* nbytes_out_lo32, + unsigned int* nbytes_out_hi32 + ); +#endif + + +/*-- Utility functions --*/ + +BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( + char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int blockSize100k, + int verbosity, + int workFactor + ); + +BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( + char* dest, + unsigned int* destLen, + char* source, + unsigned int sourceLen, + int small, + int verbosity + ); + + +/*-- + Code contributed by Yoshioka Tsuneo + (QWF00133@niftyserve.or.jp/tsuneo-y@is.aist-nara.ac.jp), + to support better zlib compatibility. + This code is not _officially_ part of libbzip2 (yet); + I haven't tested it, documented it, or considered the + threading-safeness of it. + If this code breaks, please contact both Yoshioka and me. +--*/ + +BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) ( + void + ); + +#ifndef BZ_NO_STDIO +BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) ( + const char *path, + const char *mode + ); + +BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) ( + int fd, + const char *mode + ); + +BZ_EXTERN int BZ_API(BZ2_bzread) ( + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN int BZ_API(BZ2_bzwrite) ( + BZFILE* b, + void* buf, + int len + ); + +BZ_EXTERN int BZ_API(BZ2_bzflush) ( + BZFILE* b + ); + +BZ_EXTERN void BZ_API(BZ2_bzclose) ( + BZFILE* b + ); + +BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( + BZFILE *b, + int *errnum + ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif + +/*-------------------------------------------------------------*/ +/*--- end bzlib.h ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/bzlib_private.h b/src/libbz2/bzlib_private.h new file mode 100644 index 0000000..ff973c3 --- /dev/null +++ b/src/libbz2/bzlib_private.h @@ -0,0 +1,537 @@ + +/*-------------------------------------------------------------*/ +/*--- Private header file for the library. ---*/ +/*--- bzlib_private.h ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + + +#ifndef _BZLIB_PRIVATE_H +#define _BZLIB_PRIVATE_H + +#include + +#ifndef BZ_NO_STDIO +#include +#include +#include +#endif + +#include "bzlib.h" + + + +/*-- General stuff. --*/ + +#define BZ_VERSION "1.0.2, 30-Dec-2001" + +typedef char Char; +typedef unsigned char Bool; +typedef unsigned char UChar; +typedef int Int32; +typedef unsigned int UInt32; +typedef short Int16; +typedef unsigned short UInt16; + +#define True ((Bool)1) +#define False ((Bool)0) + +#ifndef __GNUC__ +#define __inline__ /* */ +#endif + +#ifndef BZ_NO_STDIO +extern void BZ2_bz__AssertH__fail ( int errcode ); +#define AssertH(cond,errcode) \ + { if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); } +#if BZ_DEBUG +#define AssertD(cond,msg) \ + { if (!(cond)) { \ + fprintf ( stderr, \ + "\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\ + exit(1); \ + }} +#else +#define AssertD(cond,msg) /* */ +#endif +#define VPrintf0(zf) \ + fprintf(stderr,zf) +#define VPrintf1(zf,za1) \ + fprintf(stderr,zf,za1) +#define VPrintf2(zf,za1,za2) \ + fprintf(stderr,zf,za1,za2) +#define VPrintf3(zf,za1,za2,za3) \ + fprintf(stderr,zf,za1,za2,za3) +#define VPrintf4(zf,za1,za2,za3,za4) \ + fprintf(stderr,zf,za1,za2,za3,za4) +#define VPrintf5(zf,za1,za2,za3,za4,za5) \ + fprintf(stderr,zf,za1,za2,za3,za4,za5) +#else +extern void bz_internal_error ( int errcode ); +#define AssertH(cond,errcode) \ + { if (!(cond)) bz_internal_error ( errcode ); } +#define AssertD(cond,msg) /* */ +#define VPrintf0(zf) /* */ +#define VPrintf1(zf,za1) /* */ +#define VPrintf2(zf,za1,za2) /* */ +#define VPrintf3(zf,za1,za2,za3) /* */ +#define VPrintf4(zf,za1,za2,za3,za4) /* */ +#define VPrintf5(zf,za1,za2,za3,za4,za5) /* */ +#endif + + +#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1) +#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp)) + + +/*-- Header bytes. --*/ + +#define BZ_HDR_B 0x42 /* 'B' */ +#define BZ_HDR_Z 0x5a /* 'Z' */ +#define BZ_HDR_h 0x68 /* 'h' */ +#define BZ_HDR_0 0x30 /* '0' */ + +/*-- Constants for the back end. --*/ + +#define BZ_MAX_ALPHA_SIZE 258 +#define BZ_MAX_CODE_LEN 23 + +#define BZ_RUNA 0 +#define BZ_RUNB 1 + +#define BZ_N_GROUPS 6 +#define BZ_G_SIZE 50 +#define BZ_N_ITERS 4 + +#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE)) + + + +/*-- Stuff for randomising repetitive blocks. --*/ + +extern Int32 BZ2_rNums[512]; + +#define BZ_RAND_DECLS \ + Int32 rNToGo; \ + Int32 rTPos \ + +#define BZ_RAND_INIT_MASK \ + s->rNToGo = 0; \ + s->rTPos = 0 \ + +#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0) + +#define BZ_RAND_UPD_MASK \ + if (s->rNToGo == 0) { \ + s->rNToGo = BZ2_rNums[s->rTPos]; \ + s->rTPos++; \ + if (s->rTPos == 512) s->rTPos = 0; \ + } \ + s->rNToGo--; + + + +/*-- Stuff for doing CRCs. --*/ + +extern UInt32 BZ2_crc32Table[256]; + +#define BZ_INITIALISE_CRC(crcVar) \ +{ \ + crcVar = 0xffffffffL; \ +} + +#define BZ_FINALISE_CRC(crcVar) \ +{ \ + crcVar = ~(crcVar); \ +} + +#define BZ_UPDATE_CRC(crcVar,cha) \ +{ \ + crcVar = (crcVar << 8) ^ \ + BZ2_crc32Table[(crcVar >> 24) ^ \ + ((UChar)cha)]; \ +} + + + +/*-- States and modes for compression. --*/ + +#define BZ_M_IDLE 1 +#define BZ_M_RUNNING 2 +#define BZ_M_FLUSHING 3 +#define BZ_M_FINISHING 4 + +#define BZ_S_OUTPUT 1 +#define BZ_S_INPUT 2 + +#define BZ_N_RADIX 2 +#define BZ_N_QSORT 12 +#define BZ_N_SHELL 18 +#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2) + + + + +/*-- Structure holding all the compression-side stuff. --*/ + +typedef + struct { + /* pointer back to the struct bz_stream */ + bz_stream* strm; + + /* mode this stream is in, and whether inputting */ + /* or outputting data */ + Int32 mode; + Int32 state; + + /* remembers avail_in when flush/finish requested */ + UInt32 avail_in_expect; + + /* for doing the block sorting */ + UInt32* arr1; + UInt32* arr2; + UInt32* ftab; + Int32 origPtr; + + /* aliases for arr1 and arr2 */ + UInt32* ptr; + UChar* block; + UInt16* mtfv; + UChar* zbits; + + /* for deciding when to use the fallback sorting algorithm */ + Int32 workFactor; + + /* run-length-encoding of the input */ + UInt32 state_in_ch; + Int32 state_in_len; + BZ_RAND_DECLS; + + /* input and output limits and current posns */ + Int32 nblock; + Int32 nblockMAX; + Int32 numZ; + Int32 state_out_pos; + + /* map of bytes used in block */ + Int32 nInUse; + Bool inUse[256]; + UChar unseqToSeq[256]; + + /* the buffer for bit stream creation */ + UInt32 bsBuff; + Int32 bsLive; + + /* block and combined CRCs */ + UInt32 blockCRC; + UInt32 combinedCRC; + + /* misc administratium */ + Int32 verbosity; + Int32 blockNo; + Int32 blockSize100k; + + /* stuff for coding the MTF values */ + Int32 nMTF; + Int32 mtfFreq [BZ_MAX_ALPHA_SIZE]; + UChar selector [BZ_MAX_SELECTORS]; + UChar selectorMtf[BZ_MAX_SELECTORS]; + + UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + /* second dimension: only 3 needed; 4 makes index calculations faster */ + UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4]; + + } + EState; + + + +/*-- externs for compression. --*/ + +extern void +BZ2_blockSort ( EState* ); + +extern void +BZ2_compressBlock ( EState*, Bool ); + +extern void +BZ2_bsInitWrite ( EState* ); + +extern void +BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 ); + +extern void +BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 ); + + + +/*-- states for decompression. --*/ + +#define BZ_X_IDLE 1 +#define BZ_X_OUTPUT 2 + +#define BZ_X_MAGIC_1 10 +#define BZ_X_MAGIC_2 11 +#define BZ_X_MAGIC_3 12 +#define BZ_X_MAGIC_4 13 +#define BZ_X_BLKHDR_1 14 +#define BZ_X_BLKHDR_2 15 +#define BZ_X_BLKHDR_3 16 +#define BZ_X_BLKHDR_4 17 +#define BZ_X_BLKHDR_5 18 +#define BZ_X_BLKHDR_6 19 +#define BZ_X_BCRC_1 20 +#define BZ_X_BCRC_2 21 +#define BZ_X_BCRC_3 22 +#define BZ_X_BCRC_4 23 +#define BZ_X_RANDBIT 24 +#define BZ_X_ORIGPTR_1 25 +#define BZ_X_ORIGPTR_2 26 +#define BZ_X_ORIGPTR_3 27 +#define BZ_X_MAPPING_1 28 +#define BZ_X_MAPPING_2 29 +#define BZ_X_SELECTOR_1 30 +#define BZ_X_SELECTOR_2 31 +#define BZ_X_SELECTOR_3 32 +#define BZ_X_CODING_1 33 +#define BZ_X_CODING_2 34 +#define BZ_X_CODING_3 35 +#define BZ_X_MTF_1 36 +#define BZ_X_MTF_2 37 +#define BZ_X_MTF_3 38 +#define BZ_X_MTF_4 39 +#define BZ_X_MTF_5 40 +#define BZ_X_MTF_6 41 +#define BZ_X_ENDHDR_2 42 +#define BZ_X_ENDHDR_3 43 +#define BZ_X_ENDHDR_4 44 +#define BZ_X_ENDHDR_5 45 +#define BZ_X_ENDHDR_6 46 +#define BZ_X_CCRC_1 47 +#define BZ_X_CCRC_2 48 +#define BZ_X_CCRC_3 49 +#define BZ_X_CCRC_4 50 + + + +/*-- Constants for the fast MTF decoder. --*/ + +#define MTFA_SIZE 4096 +#define MTFL_SIZE 16 + + + +/*-- Structure holding all the decompression-side stuff. --*/ + +typedef + struct { + /* pointer back to the struct bz_stream */ + bz_stream* strm; + + /* state indicator for this stream */ + Int32 state; + + /* for doing the final run-length decoding */ + UChar state_out_ch; + Int32 state_out_len; + Bool blockRandomised; + BZ_RAND_DECLS; + + /* the buffer for bit stream reading */ + UInt32 bsBuff; + Int32 bsLive; + + /* misc administratium */ + Int32 blockSize100k; + Bool smallDecompress; + Int32 currBlockNo; + Int32 verbosity; + + /* for undoing the Burrows-Wheeler transform */ + Int32 origPtr; + UInt32 tPos; + Int32 k0; + Int32 unzftab[256]; + Int32 nblock_used; + Int32 cftab[257]; + Int32 cftabCopy[257]; + + /* for undoing the Burrows-Wheeler transform (FAST) */ + UInt32 *tt; + + /* for undoing the Burrows-Wheeler transform (SMALL) */ + UInt16 *ll16; + UChar *ll4; + + /* stored and calculated CRCs */ + UInt32 storedBlockCRC; + UInt32 storedCombinedCRC; + UInt32 calculatedBlockCRC; + UInt32 calculatedCombinedCRC; + + /* map of bytes used in block */ + Int32 nInUse; + Bool inUse[256]; + Bool inUse16[16]; + UChar seqToUnseq[256]; + + /* for decoding the MTF values */ + UChar mtfa [MTFA_SIZE]; + Int32 mtfbase[256 / MTFL_SIZE]; + UChar selector [BZ_MAX_SELECTORS]; + UChar selectorMtf[BZ_MAX_SELECTORS]; + UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + + Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; + Int32 minLens[BZ_N_GROUPS]; + + /* save area for scalars in the main decompress code */ + Int32 save_i; + Int32 save_j; + Int32 save_t; + Int32 save_alphaSize; + Int32 save_nGroups; + Int32 save_nSelectors; + Int32 save_EOB; + Int32 save_groupNo; + Int32 save_groupPos; + Int32 save_nextSym; + Int32 save_nblockMAX; + Int32 save_nblock; + Int32 save_es; + Int32 save_N; + Int32 save_curr; + Int32 save_zt; + Int32 save_zn; + Int32 save_zvec; + Int32 save_zj; + Int32 save_gSel; + Int32 save_gMinlen; + Int32* save_gLimit; + Int32* save_gBase; + Int32* save_gPerm; + + } + DState; + + + +/*-- Macros for decompression. --*/ + +#define BZ_GET_FAST(cccc) \ + s->tPos = s->tt[s->tPos]; \ + cccc = (UChar)(s->tPos & 0xff); \ + s->tPos >>= 8; + +#define BZ_GET_FAST_C(cccc) \ + c_tPos = c_tt[c_tPos]; \ + cccc = (UChar)(c_tPos & 0xff); \ + c_tPos >>= 8; + +#define SET_LL4(i,n) \ + { if (((i) & 0x1) == 0) \ + s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \ + s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \ + } + +#define GET_LL4(i) \ + ((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF) + +#define SET_LL(i,n) \ + { s->ll16[i] = (UInt16)(n & 0x0000ffff); \ + SET_LL4(i, n >> 16); \ + } + +#define GET_LL(i) \ + (((UInt32)s->ll16[i]) | (GET_LL4(i) << 16)) + +#define BZ_GET_SMALL(cccc) \ + cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \ + s->tPos = GET_LL(s->tPos); + + +/*-- externs for decompression. --*/ + +extern Int32 +BZ2_indexIntoF ( Int32, Int32* ); + +extern Int32 +BZ2_decompress ( DState* ); + +extern void +BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*, + Int32, Int32, Int32 ); + + +#endif + + +/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/ + +#ifdef BZ_NO_STDIO +#ifndef NULL +#define NULL 0 +#endif +#endif + + +/*-------------------------------------------------------------*/ +/*--- end bzlib_private.h ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/crctable.c b/src/libbz2/crctable.c new file mode 100644 index 0000000..b16746a --- /dev/null +++ b/src/libbz2/crctable.c @@ -0,0 +1,144 @@ + +/*-------------------------------------------------------------*/ +/*--- Table for doing CRCs ---*/ +/*--- crctable.c ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + + +#include "bzlib_private.h" + +/*-- + I think this is an implementation of the AUTODIN-II, + Ethernet & FDDI 32-bit CRC standard. Vaguely derived + from code by Rob Warnock, in Section 51 of the + comp.compression FAQ. +--*/ + +UInt32 BZ2_crc32Table[256] = { + + /*-- Ugly, innit? --*/ + + 0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L, + 0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L, + 0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L, + 0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL, + 0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L, + 0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L, + 0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L, + 0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL, + 0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L, + 0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L, + 0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L, + 0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL, + 0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L, + 0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L, + 0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L, + 0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL, + 0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL, + 0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L, + 0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L, + 0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL, + 0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL, + 0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L, + 0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L, + 0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL, + 0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL, + 0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L, + 0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L, + 0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL, + 0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL, + 0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L, + 0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L, + 0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL, + 0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L, + 0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL, + 0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL, + 0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L, + 0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L, + 0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL, + 0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL, + 0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L, + 0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L, + 0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL, + 0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL, + 0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L, + 0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L, + 0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL, + 0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL, + 0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L, + 0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L, + 0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL, + 0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L, + 0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L, + 0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L, + 0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL, + 0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L, + 0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L, + 0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L, + 0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL, + 0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L, + 0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L, + 0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L, + 0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL, + 0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L, + 0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L +}; + + +/*-------------------------------------------------------------*/ +/*--- end crctable.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/huffman.c b/src/libbz2/huffman.c new file mode 100644 index 0000000..293095c --- /dev/null +++ b/src/libbz2/huffman.c @@ -0,0 +1,228 @@ + +/*-------------------------------------------------------------*/ +/*--- Huffman coding low-level stuff ---*/ +/*--- huffman.c ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + + +#include "bzlib_private.h" + +/*---------------------------------------------------*/ +#define WEIGHTOF(zz0) ((zz0) & 0xffffff00) +#define DEPTHOF(zz1) ((zz1) & 0x000000ff) +#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3)) + +#define ADDWEIGHTS(zw1,zw2) \ + (WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \ + (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2))) + +#define UPHEAP(z) \ +{ \ + Int32 zz, tmp; \ + zz = z; tmp = heap[zz]; \ + while (weight[tmp] < weight[heap[zz >> 1]]) { \ + heap[zz] = heap[zz >> 1]; \ + zz >>= 1; \ + } \ + heap[zz] = tmp; \ +} + +#define DOWNHEAP(z) \ +{ \ + Int32 zz, yy, tmp; \ + zz = z; tmp = heap[zz]; \ + while (True) { \ + yy = zz << 1; \ + if (yy > nHeap) break; \ + if (yy < nHeap && \ + weight[heap[yy+1]] < weight[heap[yy]]) \ + yy++; \ + if (weight[tmp] < weight[heap[yy]]) break; \ + heap[zz] = heap[yy]; \ + zz = yy; \ + } \ + heap[zz] = tmp; \ +} + + +/*---------------------------------------------------*/ +void BZ2_hbMakeCodeLengths ( UChar *len, + Int32 *freq, + Int32 alphaSize, + Int32 maxLen ) +{ + /*-- + Nodes and heap entries run from 1. Entry 0 + for both the heap and nodes is a sentinel. + --*/ + Int32 nNodes, nHeap, n1, n2, i, j, k; + Bool tooLong; + + Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ]; + Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ]; + Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ]; + + for (i = 0; i < alphaSize; i++) + weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; + + while (True) { + + nNodes = alphaSize; + nHeap = 0; + + heap[0] = 0; + weight[0] = 0; + parent[0] = -2; + + for (i = 1; i <= alphaSize; i++) { + parent[i] = -1; + nHeap++; + heap[nHeap] = i; + UPHEAP(nHeap); + } + + AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 ); + + while (nHeap > 1) { + n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); + n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); + nNodes++; + parent[n1] = parent[n2] = nNodes; + weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]); + parent[nNodes] = -1; + nHeap++; + heap[nHeap] = nNodes; + UPHEAP(nHeap); + } + + AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 ); + + tooLong = False; + for (i = 1; i <= alphaSize; i++) { + j = 0; + k = i; + while (parent[k] >= 0) { k = parent[k]; j++; } + len[i-1] = j; + if (j > maxLen) tooLong = True; + } + + if (! tooLong) break; + + for (i = 1; i < alphaSize; i++) { + j = weight[i] >> 8; + j = 1 + (j / 2); + weight[i] = j << 8; + } + } +} + + +/*---------------------------------------------------*/ +void BZ2_hbAssignCodes ( Int32 *code, + UChar *length, + Int32 minLen, + Int32 maxLen, + Int32 alphaSize ) +{ + Int32 n, vec, i; + + vec = 0; + for (n = minLen; n <= maxLen; n++) { + for (i = 0; i < alphaSize; i++) + if (length[i] == n) { code[i] = vec; vec++; }; + vec <<= 1; + } +} + + +/*---------------------------------------------------*/ +void BZ2_hbCreateDecodeTables ( Int32 *limit, + Int32 *base, + Int32 *perm, + UChar *length, + Int32 minLen, + Int32 maxLen, + Int32 alphaSize ) +{ + Int32 pp, i, j, vec; + + pp = 0; + for (i = minLen; i <= maxLen; i++) + for (j = 0; j < alphaSize; j++) + if (length[j] == i) { perm[pp] = j; pp++; }; + + for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0; + for (i = 0; i < alphaSize; i++) base[length[i]+1]++; + + for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1]; + + for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0; + vec = 0; + + for (i = minLen; i <= maxLen; i++) { + vec += (base[i+1] - base[i]); + limit[i] = vec-1; + vec <<= 1; + } + for (i = minLen + 1; i <= maxLen; i++) + base[i] = ((limit[i-1] + 1) << 1) - base[i]; +} + + +/*-------------------------------------------------------------*/ +/*--- end huffman.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libbz2/randtable.c b/src/libbz2/randtable.c new file mode 100644 index 0000000..5c922e9 --- /dev/null +++ b/src/libbz2/randtable.c @@ -0,0 +1,124 @@ + +/*-------------------------------------------------------------*/ +/*--- Table for randomising repetitive blocks ---*/ +/*--- randtable.c ---*/ +/*-------------------------------------------------------------*/ + +/*-- + This file is a part of bzip2 and/or libbzip2, a program and + library for lossless, block-sorting data compression. + + Copyright (C) 1996-2002 Julian R Seward. 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. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + + Julian Seward, Cambridge, UK. + jseward@acm.org + bzip2/libbzip2 version 1.0 of 21 March 2000 + + This program is based on (at least) the work of: + Mike Burrows + David Wheeler + Peter Fenwick + Alistair Moffat + Radford Neal + Ian H. Witten + Robert Sedgewick + Jon L. Bentley + + For more information on these sources, see the manual. +--*/ + + +#include "bzlib_private.h" + + +/*---------------------------------------------*/ +Int32 BZ2_rNums[512] = { + 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, + 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, + 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, + 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, + 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, + 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, + 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, + 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, + 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, + 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, + 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, + 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, + 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, + 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, + 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, + 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, + 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, + 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, + 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, + 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, + 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, + 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, + 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, + 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, + 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, + 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, + 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, + 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, + 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, + 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, + 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, + 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, + 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, + 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, + 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, + 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, + 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, + 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, + 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, + 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, + 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, + 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, + 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, + 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, + 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, + 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, + 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, + 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, + 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, + 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, + 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, + 936, 638 +}; + + +/*-------------------------------------------------------------*/ +/*--- end randtable.c ---*/ +/*-------------------------------------------------------------*/ diff --git a/src/libz/Makefile.in b/src/libz/Makefile.in new file mode 100644 index 0000000..892e91f --- /dev/null +++ b/src/libz/Makefile.in @@ -0,0 +1,73 @@ +SHELL=/bin/sh + +# To assist in cross-compiling +CC=@CC@ +AR=ar +RANLIB=@RANLIB@ +LDFLAGS= + +# Suitably paranoid flags to avoid bugs in gcc-2.7 +BIGFILES = -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 +CFLAGS = -O2 + +OBJS= adler32.o \ + compress.o \ + crc32.o \ + deflate.o \ + gzio.o \ + infback.o \ + inffast.o \ + inflate.o \ + inftrees.o \ + trees.o \ + uncompr.o \ + zutil.o + + +all: libz.a + +libz.a: $(OBJS) + rm -f libz.a + $(AR) cq libz.a $(OBJS) + $(RANLIB) libz.a + +clean: + rm -f *.o libz.a + + +adler32.o: adler32.c + $(CC) $(CFLAGS) -c adler32.c + +compress.o: compress.c + $(CC) $(CFLAGS) -c compress.c + +crc32.o: crc32.c + $(CC) $(CFLAGS) -c crc32.c + +deflate.o: deflate.c + $(CC) $(CFLAGS) -c deflate.c + +gzio.o: gzio.c + $(CC) $(CFLAGS) -c gzio.c + +infback.o: infback.c + $(CC) $(CFLAGS) -c infback.c + +inffast.o: inffast.c + $(CC) $(CFLAGS) -c inffast.c + +inflate.o: inflate.c + $(CC) $(CFLAGS) -c inflate.c + +inftrees.o: inftrees.c + $(CC) $(CFLAGS) -c inftrees.c + +trees.o: trees.c + $(CC) $(CFLAGS) -c trees.c + +uncompr.o: uncompr.c + $(CC) $(CFLAGS) -c uncompr.c + +zutil.o: zutil.c + $(CC) $(CFLAGS) -c zutil.c + diff --git a/src/libz/README b/src/libz/README new file mode 100644 index 0000000..0f12054 --- /dev/null +++ b/src/libz/README @@ -0,0 +1,126 @@ +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.1 is a general purpose data compression library. All the code is +thread safe. The data format used by the zlib library is described by RFCs +(Request for Comments) 1950 to 1952 in the files +http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) +and rfc1952.txt (gzip format). These documents are also available in other +formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example +of the library is given in the file example.c which also tests that the library +is working correctly. Another example is given in the file minigzip.c. The +compression library itself is composed of all source files except example.c and +minigzip.c. + +To compile all files and run the test program, follow the instructions given at +the top of Makefile. In short "make test; make install" should work for most +machines. For Unix: "./configure; make test; make install" For MSDOS, use one +of the special makefiles such as Makefile.msc. For VMS, use Make_vms.com or +descrip.mms. + +Questions about zlib should be sent to , or to Gilles Vollant + for the Windows DLL version. The zlib home page is +http://www.zlib.org or http://www.gzip.org/zlib/ Before reporting a problem, +please check this site to verify that you have the latest version of zlib; +otherwise get the latest version and check whether the problem still exists or +not. + +PLEASE read the zlib FAQ http://www.gzip.org/zlib/zlib_faq.html before asking +for help. + +Mark Nelson wrote an article about zlib for the Jan. 1997 +issue of Dr. Dobb's Journal; a copy of the article is available in +http://dogma.net/markn/articles/zlibtool/zlibtool.htm + +The changes made in version 1.2.1 are documented in the file ChangeLog. + +Unsupported third party contributions are provided in directory "contrib". + +A Java implementation of zlib is available in the Java Development Kit +http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html +See the zlib home page http://www.zlib.org for details. + +A Perl interface to zlib written by Paul Marquess is in the +CPAN (Comprehensive Perl Archive Network) sites +http://www.cpan.org/modules/by-module/Compress/ + +A Python interface to zlib written by A.M. Kuchling is +available in Python 1.5 and later versions, see +http://www.python.org/doc/lib/module-zlib.html + +A zlib binding for TCL written by Andreas Kupries is +availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html + +An experimental package to read and write files in .zip format, written on top +of zlib by Gilles Vollant , is available in the +contrib/minizip directory of zlib. + + +Notes for some targets: + +- For Windows DLL versions, please see win32/DLL_FAQ.txt + +- For 64-bit Irix, deflate.c must be compiled without any optimization. With + -O, one libpng test fails. The test works in 32 bit mode (with the -n32 + compiler flag). The compiler bug has been reported to SGI. + +- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works + when compiled with cc. + +- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is + necessary to get gzprintf working correctly. This is done by configure. + +- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with + other compilers. Use "make test" to check your compiler. + +- gzdopen is not supported on RISCOS, BEOS and by some Mac compilers. + +- For PalmOs, see http://palmzlib.sourceforge.net/ + +- When building a shared, i.e. dynamic library on Mac OS X, the library must be + installed before testing (do "make install" before "make test"), since the + library location is specified in the library. + + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate + and zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; + they are too numerous to cite here. + +Copyright notice: + + (C) 1995-2003 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* +receiving lengthy legal documents to sign. The sources are provided +for free but without warranty of any kind. The library has been +entirely written by Jean-loup Gailly and Mark Adler; it does not +include third-party code. + +If you redistribute modified sources, we would appreciate that you include +in the file ChangeLog history information documenting your changes. Please +read the FAQ for more information on the distribution of modified source +versions. diff --git a/src/libz/adler32.c b/src/libz/adler32.c new file mode 100644 index 0000000..624a169 --- /dev/null +++ b/src/libz/adler32.c @@ -0,0 +1,74 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +#define BASE 65521UL /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {s1 += buf[i]; s2 += s1;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +#ifdef NO_DIVIDE +# define MOD(a) \ + do { \ + if (a >= (BASE << 16)) a -= (BASE << 16); \ + if (a >= (BASE << 15)) a -= (BASE << 15); \ + if (a >= (BASE << 14)) a -= (BASE << 14); \ + if (a >= (BASE << 13)) a -= (BASE << 13); \ + if (a >= (BASE << 12)) a -= (BASE << 12); \ + if (a >= (BASE << 11)) a -= (BASE << 11); \ + if (a >= (BASE << 10)) a -= (BASE << 10); \ + if (a >= (BASE << 9)) a -= (BASE << 9); \ + if (a >= (BASE << 8)) a -= (BASE << 8); \ + if (a >= (BASE << 7)) a -= (BASE << 7); \ + if (a >= (BASE << 6)) a -= (BASE << 6); \ + if (a >= (BASE << 5)) a -= (BASE << 5); \ + if (a >= (BASE << 4)) a -= (BASE << 4); \ + if (a >= (BASE << 3)) a -= (BASE << 3); \ + if (a >= (BASE << 2)) a -= (BASE << 2); \ + if (a >= (BASE << 1)) a -= (BASE << 1); \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long s1 = adler & 0xffff; + unsigned long s2 = (adler >> 16) & 0xffff; + int k; + + if (buf == Z_NULL) return 1L; + + while (len > 0) { + k = len < NMAX ? (int)len : NMAX; + len -= k; + while (k >= 16) { + DO16(buf); + buf += 16; + k -= 16; + } + if (k != 0) do { + s1 += *buf++; + s2 += s1; + } while (--k); + MOD(s1); + MOD(s2); + } + return (s2 << 16) | s1; +} diff --git a/src/libz/compress.c b/src/libz/compress.c new file mode 100644 index 0000000..24ef029 --- /dev/null +++ b/src/libz/compress.c @@ -0,0 +1,79 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2002 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound (sourceLen) + uLong sourceLen; +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; +} diff --git a/src/libz/crc32.c b/src/libz/crc32.c new file mode 100644 index 0000000..689b288 --- /dev/null +++ b/src/libz/crc32.c @@ -0,0 +1,311 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results about a factor + * of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +#define local static + +/* Find a four-byte integer type for crc32_little() and crc32_big(). */ +#ifndef NOBYFOUR +# ifdef STDC /* need ANSI C limits.h to determine sizes */ +# include +# define BYFOUR +# if (UINT_MAX == 0xffffffffUL) + typedef unsigned int u4; +# else +# if (ULONG_MAX == 0xffffffffUL) + typedef unsigned long u4; +# else +# if (USHRT_MAX == 0xffffffffUL) + typedef unsigned short u4; +# else +# undef BYFOUR /* can't find a four-byte integer type! */ +# endif +# endif +# endif +# endif /* STDC */ +#endif /* !NOBYFOUR */ + +/* Definitions for doing the crc four data bytes at a time. */ +#ifdef BYFOUR +# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ + (((w)&0xff00)<<8)+(((w)&0xff)<<24)) + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, unsigned)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, unsigned)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +#ifdef DYNAMIC_CRC_TABLE + +local int crc_table_empty = 1; +local unsigned long FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const unsigned long FAR *)); +#endif /* MAKECRCH */ + +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + unsigned long c; + int n, k; + unsigned long poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0UL; + for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) + poly |= 1UL << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (unsigned long)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, and + then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = REV(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = REV(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + +#ifdef MAKECRCH + /* write out CRC tables to crc32.h */ + { + FILE *out; + + out = fopen("crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const unsigned long FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const unsigned long FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const unsigned long FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const unsigned long FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + u4 endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +#ifdef BYFOUR + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register u4 c; + register const u4 FAR *buf4; + + c = (u4)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const u4 FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *++buf4; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register u4 c; + register const u4 FAR *buf4; + + c = REV((u4)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const u4 FAR *)buf; + buf4--; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf4++; + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(REV(c)); +} + +#endif /* BYFOUR */ diff --git a/src/libz/crc32.h b/src/libz/crc32.h new file mode 100644 index 0000000..8053b61 --- /dev/null +++ b/src/libz/crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const unsigned long FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/src/libz/deflate.c b/src/libz/deflate.c new file mode 100644 index 0000000..0525b2f --- /dev/null +++ b/src/libz/deflate.c @@ -0,0 +1,1502 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://www.ietf.org/rfc/rfc1951.txt + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.1 Copyright 1995-2003 Jean-loup Gailly "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifndef FASTEST +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif +#endif +local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +#ifndef NO_DUMMY_DECL +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +#endif + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_RLE) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt length = dictLength; + uInt n; + IPos hash_head = 0; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || + strm->state->wrap == 2 || + (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) + return Z_STREAM_ERROR; + + s = strm->state; + if (s->wrap) + strm->adler = adler32(strm->adler, dictionary, dictLength); + + if (length < MIN_MATCH) return Z_OK; + if (length > MAX_DIST(s)) { + length = MAX_DIST(s); +#ifndef USE_DICT_HEAD + dictionary += dictLength - length; /* use the tail of the dictionary */ +#endif + } + zmemcpy(s->window, dictionary, length); + s->strstart = length; + s->block_start = (long)length; + + /* Insert all strings in the hash table (except for the last two bytes). + * s->lookahead stays null, so s->ins_h will be recomputed at the next + * call of fill_window. + */ + s->ins_h = s->window[0]; + UPDATE_HASH(s, s->ins_h, s->window[1]); + for (n = 0; n <= length - MIN_MATCH; n++) { + INSERT_STRING(s, n, hash_head); + } + if (hash_head) hash_head = 0; /* to make compiler happy */ + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + lm_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + strm->state->bi_valid = bits; + strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_RLE) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if (func != configuration_table[level].func && strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_PARTIAL_FLUSH); + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds + * for every combination of windowBits and memLevel, as well as wrap. + * But even the conservative upper bound of about 14% expansion does not + * seem onerous for output buffer allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong destLen; + + /* conservative upper bound */ + destLen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; + + /* if can't get parameters, return conservative bound */ + if (strm == Z_NULL || strm->state == Z_NULL) + return destLen; + + /* if not default parameters, return conservative bound */ + s = strm->state; + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return destLen; + + /* default settings: return tight bound for that case */ + return compressBound(sourceLen); +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len = strm->state->pending; + + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, strm->state->pending_out, len); + strm->next_out += len; + strm->state->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + strm->state->pending -= len; + if (strm->state->pending == 0) { + strm->state->pending_out = strm->state->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_FINISH || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, 255); + s->status = BUSY_STATE; + strm->adler = crc32(0L, Z_NULL, 0); + } + else +#endif + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && flush <= old_flush && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = (*(configuration_table[s->level].func))(s, flush); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + *dest = *source; + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + *ds = *ss; + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, strm->next_in, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, strm->next_in, len); + } +#endif + zmemcpy(buf, strm->next_in, len); + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2: + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ +#endif /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for level == 1 or strategy == Z_RLE only + */ +local uInt longest_match_fast(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) return; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead >= MIN_MATCH) { + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, eof) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (eof)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, eof) { \ + FLUSH_BLOCK_ONLY(s, eof); \ + if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ +#ifdef FASTEST + if ((s->strategy < Z_HUFFMAN_ONLY) || + (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { + s->match_length = longest_match_fast (s, hash_head); + } +#else + if (s->strategy < Z_HUFFMAN_ONLY) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } +#endif + /* longest_match() or longest_match_fast() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head = NIL; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + if (s->strategy < Z_HUFFMAN_ONLY) { + s->match_length = longest_match (s, hash_head); + } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { + s->match_length = longest_match_fast (s, hash_head); + } + /* longest_match() or longest_match_fast() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + FLUSH_BLOCK(s, flush == Z_FINISH); + return flush == Z_FINISH ? finish_done : block_done; +} +#endif /* FASTEST */ diff --git a/src/libz/deflate.h b/src/libz/deflate.h new file mode 100644 index 0000000..e31f66b --- /dev/null +++ b/src/libz/deflate.h @@ -0,0 +1,326 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2002 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define INIT_STATE 42 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + int pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + Byte data_type; /* UNKNOWN, BINARY or ASCII */ + Byte method; /* STORED (for zip only) or DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to supress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + int last_eob_len; /* bit length of EOB code for last block */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + + /* in trees.c */ +void _tr_init OF((deflate_state *s)); +int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); +void _tr_align OF((deflate_state *s)); +void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, + int eof)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch _length_code[]; + extern uch _dist_code[]; +#else + extern const uch _length_code[]; + extern const uch _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/src/libz/gzio.c b/src/libz/gzio.c new file mode 100644 index 0000000..5ae2478 --- /dev/null +++ b/src/libz/gzio.c @@ -0,0 +1,1012 @@ +/* gzio.c -- IO on .gz files + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Compile this file with -DNO_GZCOMPRESS to avoid the compression code. + */ + +/* @(#) $Id$ */ + +#if defined _MSC_VER || defined __MINGW32__ +#define fseeko fseek +#define ftello ftell +#endif + + +#include + +#include "zutil.h" + +#ifdef NO_DEFLATE /* for compatiblity with old definition */ +# define NO_GZCOMPRESS +#endif + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +#ifndef Z_BUFSIZE +# ifdef MAXSEG_64K +# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ +# else +# define Z_BUFSIZE 16384 +# endif +#endif +#ifndef Z_PRINTF_BUFSIZE +# define Z_PRINTF_BUFSIZE 4096 +#endif + +#ifdef __MVS__ +# pragma map (fdopen , "\174\174FDOPEN") + FILE *fdopen(int, const char *); +#endif + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern void free OF((voidpf ptr)); +#endif + +#define ALLOC(size) malloc(size) +#define TRYFREE(p) {if (p) free(p);} + +static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ + +/* gzip flag byte */ +#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ +#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ +#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ +#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ +#define COMMENT 0x10 /* bit 4 set: file comment present */ +#define RESERVED 0xE0 /* bits 5..7: reserved */ + +typedef struct gz_stream { + z_stream stream; + int z_err; /* error code for last stream operation */ + int z_eof; /* set if end of input file */ + FILE *file; /* .gz file */ + Byte *inbuf; /* input buffer */ + Byte *outbuf; /* output buffer */ + uLong crc; /* crc32 of uncompressed data */ + char *msg; /* error message */ + char *path; /* path name for debugging only */ + int transparent; /* 1 if input file is not a .gz file */ + char mode; /* 'w' or 'r' */ + z_off_t start; /* start of compressed data in file (header skipped) */ + z_off_t in; /* bytes into deflate or inflate */ + z_off_t out; /* bytes out of deflate or inflate */ + int back; /* one character push-back */ + int last; /* true if push-back is last character */ +} gz_stream; + + +local gzFile gz_open OF((const char *path, const char *mode, int fd)); +local int do_flush OF((gzFile file, int flush)); +local int get_byte OF((gz_stream *s)); +local void check_header OF((gz_stream *s)); +local int destroy OF((gz_stream *s)); +local void putLong OF((FILE *file, uLong x)); +local uLong getLong OF((gz_stream *s)); + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb"). The file is given either by file descriptor + or path name (if fd == -1). + gz_open returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). +*/ +local gzFile gz_open (path, mode, fd) + const char *path; + const char *mode; + int fd; +{ + int err; + int level = Z_DEFAULT_COMPRESSION; /* compression level */ + int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ + char *p = (char*)mode; + gz_stream *s; + char fmode[80]; /* copy of mode, without the compression level */ + char *m = fmode; + + if (!path || !mode) return Z_NULL; + + s = (gz_stream *)ALLOC(sizeof(gz_stream)); + if (!s) return Z_NULL; + + s->stream.zalloc = (alloc_func)0; + s->stream.zfree = (free_func)0; + s->stream.opaque = (voidpf)0; + s->stream.next_in = s->inbuf = Z_NULL; + s->stream.next_out = s->outbuf = Z_NULL; + s->stream.avail_in = s->stream.avail_out = 0; + s->file = NULL; + s->z_err = Z_OK; + s->z_eof = 0; + s->in = 0; + s->out = 0; + s->back = EOF; + s->crc = crc32(0L, Z_NULL, 0); + s->msg = NULL; + s->transparent = 0; + + s->path = (char*)ALLOC(strlen(path)+1); + if (s->path == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + strcpy(s->path, path); /* do this early for debugging */ + + s->mode = '\0'; + do { + if (*p == 'r') s->mode = 'r'; + if (*p == 'w' || *p == 'a') s->mode = 'w'; + if (*p >= '0' && *p <= '9') { + level = *p - '0'; + } else if (*p == 'f') { + strategy = Z_FILTERED; + } else if (*p == 'h') { + strategy = Z_HUFFMAN_ONLY; + } else if (*p == 'R') { + strategy = Z_RLE; + } else { + *m++ = *p; /* copy the mode */ + } + } while (*p++ && m != fmode + sizeof(fmode)); + if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + err = Z_STREAM_ERROR; +#else + err = deflateInit2(&(s->stream), level, + Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); + /* windowBits is passed < 0 to suppress zlib header */ + + s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); +#endif + if (err != Z_OK || s->outbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } else { + s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); + + err = inflateInit2(&(s->stream), -MAX_WBITS); + /* windowBits is passed < 0 to tell that there is no zlib header. + * Note that in this case inflate *requires* an extra "dummy" byte + * after the compressed stream in order to complete decompression and + * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are + * present after the compressed stream. + */ + if (err != Z_OK || s->inbuf == Z_NULL) { + return destroy(s), (gzFile)Z_NULL; + } + } + s->stream.avail_out = Z_BUFSIZE; + + errno = 0; + s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); + + if (s->file == NULL) { + return destroy(s), (gzFile)Z_NULL; + } + if (s->mode == 'w') { + /* Write a very simple .gz header: + */ + fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], + Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); + s->start = 10L; + /* We use 10L instead of ftell(s->file) to because ftell causes an + * fflush on some systems. This version of the library doesn't use + * start anyway in write mode, so this initialization is not + * necessary. + */ + } else { + check_header(s); /* skip the .gz header */ + s->start = ftello(s->file) - s->stream.avail_in; + } + + return (gzFile)s; +} + +/* =========================================================================== + Opens a gzip (.gz) file for reading or writing. +*/ +gzFile ZEXPORT gzopen (path, mode) + const char *path; + const char *mode; +{ + return gz_open (path, mode, -1); +} + +/* =========================================================================== + Associate a gzFile with the file descriptor fd. fd is not dup'ed here + to mimic the behavio(u)r of fdopen. +*/ +gzFile ZEXPORT gzdopen (fd, mode) + int fd; + const char *mode; +{ + char name[20]; + + if (fd < 0) return (gzFile)Z_NULL; + sprintf(name, "", fd); /* for debugging */ + + return gz_open (name, mode, fd); +} + +/* =========================================================================== + * Update the compression level and strategy + */ +int ZEXPORT gzsetparams (file, level, strategy) + gzFile file; + int level; + int strategy; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + /* Make room to allow flushing */ + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + } + s->stream.avail_out = Z_BUFSIZE; + } + + return deflateParams (&(s->stream), level, strategy); +} + +/* =========================================================================== + Read a byte from a gz_stream; update next_in and avail_in. Return EOF + for end of file. + IN assertion: the stream s has been sucessfully opened for reading. +*/ +local int get_byte(s) + gz_stream *s; +{ + if (s->z_eof) return EOF; + if (s->stream.avail_in == 0) { + errno = 0; + s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) s->z_err = Z_ERRNO; + return EOF; + } + s->stream.next_in = s->inbuf; + } + s->stream.avail_in--; + return *(s->stream.next_in)++; +} + +/* =========================================================================== + Check the gzip header of a gz_stream opened for reading. Set the stream + mode to transparent if the gzip magic header is not present; set s->err + to Z_DATA_ERROR if the magic header is present but the rest of the header + is incorrect. + IN assertion: the stream s has already been created sucessfully; + s->stream.avail_in is zero for the first time, but may be non-zero + for concatenated .gz files. +*/ +local void check_header(s) + gz_stream *s; +{ + int method; /* method byte */ + int flags; /* flags byte */ + uInt len; + int c; + + /* Assure two bytes in the buffer so we can peek ahead -- handle case + where first byte of header is at the end of the buffer after the last + gzip segment */ + len = s->stream.avail_in; + if (len < 2) { + if (len) s->inbuf[0] = s->stream.next_in[0]; + errno = 0; + len = fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); + if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; + s->stream.avail_in += len; + s->stream.next_in = s->inbuf; + if (s->stream.avail_in < 2) { + s->transparent = s->stream.avail_in; + return; + } + } + + /* Peek ahead to check the gzip magic header */ + if (s->stream.next_in[0] != gz_magic[0] || + s->stream.next_in[1] != gz_magic[1]) { + s->transparent = 1; + return; + } + s->stream.avail_in -= 2; + s->stream.next_in += 2; + + /* Check the rest of the gzip header */ + method = get_byte(s); + flags = get_byte(s); + if (method != Z_DEFLATED || (flags & RESERVED) != 0) { + s->z_err = Z_DATA_ERROR; + return; + } + + /* Discard time, xflags and OS code: */ + for (len = 0; len < 6; len++) (void)get_byte(s); + + if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ + len = (uInt)get_byte(s); + len += ((uInt)get_byte(s))<<8; + /* len is garbage if EOF but the loop below will quit anyway */ + while (len-- != 0 && get_byte(s) != EOF) ; + } + if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ + while ((c = get_byte(s)) != 0 && c != EOF) ; + } + if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ + for (len = 0; len < 2; len++) (void)get_byte(s); + } + s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; +} + + /* =========================================================================== + * Cleanup then free the given gz_stream. Return a zlib error code. + Try freeing in the reverse order of allocations. + */ +local int destroy (s) + gz_stream *s; +{ + int err = Z_OK; + + if (!s) return Z_STREAM_ERROR; + + TRYFREE(s->msg); + + if (s->stream.state != NULL) { + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + err = Z_STREAM_ERROR; +#else + err = deflateEnd(&(s->stream)); +#endif + } else if (s->mode == 'r') { + err = inflateEnd(&(s->stream)); + } + } + if (s->file != NULL && fclose(s->file)) { +#ifdef ESPIPE + if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ +#endif + err = Z_ERRNO; + } + if (s->z_err < 0) err = s->z_err; + + TRYFREE(s->inbuf); + TRYFREE(s->outbuf); + TRYFREE(s->path); + TRYFREE(s); + return err; +} + +/* =========================================================================== + Reads the given number of uncompressed bytes from the compressed file. + gzread returns the number of bytes actually read (0 for end of file). +*/ +int ZEXPORT gzread (file, buf, len) + gzFile file; + voidp buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + Bytef *start = (Bytef*)buf; /* starting point for crc computation */ + Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ + + if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; + + if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; + if (s->z_err == Z_STREAM_END) return 0; /* EOF */ + + next_out = (Byte*)buf; + s->stream.next_out = (Bytef*)buf; + s->stream.avail_out = len; + + if (s->stream.avail_out && s->back != EOF) { + *next_out++ = s->back; + s->stream.next_out++; + s->stream.avail_out--; + s->back = EOF; + s->out++; + if (s->last) { + s->z_err = Z_STREAM_END; + return 1; + } + } + + while (s->stream.avail_out != 0) { + + if (s->transparent) { + /* Copy first the lookahead bytes: */ + uInt n = s->stream.avail_in; + if (n > s->stream.avail_out) n = s->stream.avail_out; + if (n > 0) { + zmemcpy(s->stream.next_out, s->stream.next_in, n); + next_out += n; + s->stream.next_out = next_out; + s->stream.next_in += n; + s->stream.avail_out -= n; + s->stream.avail_in -= n; + } + if (s->stream.avail_out > 0) { + s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out, + s->file); + } + len -= s->stream.avail_out; + s->in += len; + s->out += len; + if (len == 0) s->z_eof = 1; + return (int)len; + } + if (s->stream.avail_in == 0 && !s->z_eof) { + + errno = 0; + s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); + if (s->stream.avail_in == 0) { + s->z_eof = 1; + if (ferror(s->file)) { + s->z_err = Z_ERRNO; + break; + } + } + s->stream.next_in = s->inbuf; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = inflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + + if (s->z_err == Z_STREAM_END) { + /* Check CRC and original size */ + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + start = s->stream.next_out; + + if (getLong(s) != s->crc) { + s->z_err = Z_DATA_ERROR; + } else { + (void)getLong(s); + /* The uncompressed length returned by above getlong() may be + * different from s->out in case of concatenated .gz files. + * Check for such files: + */ + check_header(s); + if (s->z_err == Z_OK) { + inflateReset(&(s->stream)); + s->crc = crc32(0L, Z_NULL, 0); + } + } + } + if (s->z_err != Z_OK || s->z_eof) break; + } + s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); + + return (int)(len - s->stream.avail_out); +} + + +/* =========================================================================== + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ +int ZEXPORT gzgetc(file) + gzFile file; +{ + unsigned char c; + + return gzread(file, &c, 1) == 1 ? c : -1; +} + + +/* =========================================================================== + Push one byte back onto the stream. +*/ +int ZEXPORT gzungetc(c, file) + int c; + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF; + s->back = c; + s->out--; + s->last = (s->z_err == Z_STREAM_END); + if (s->last) s->z_err = Z_OK; + s->z_eof = 0; + return c; +} + + +/* =========================================================================== + Reads bytes from the compressed file until len-1 characters are + read, or a newline character is read and transferred to buf, or an + end-of-file condition is encountered. The string is then terminated + with a null character. + gzgets returns buf, or Z_NULL in case of error. + + The current implementation is not optimized at all. +*/ +char * ZEXPORT gzgets(file, buf, len) + gzFile file; + char *buf; + int len; +{ + char *b = buf; + if (buf == Z_NULL || len <= 0) return Z_NULL; + + while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; + *buf = '\0'; + return b == buf && len > 0 ? Z_NULL : b; +} + + +#ifndef NO_GZCOMPRESS +/* =========================================================================== + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of bytes actually written (0 in case of error). +*/ +int ZEXPORT gzwrite (file, buf, len) + gzFile file; + voidpc buf; + unsigned len; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.next_in = (Bytef*)buf; + s->stream.avail_in = len; + + while (s->stream.avail_in != 0) { + + if (s->stream.avail_out == 0) { + + s->stream.next_out = s->outbuf; + if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { + s->z_err = Z_ERRNO; + break; + } + s->stream.avail_out = Z_BUFSIZE; + } + s->in += s->stream.avail_in; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), Z_NO_FLUSH); + s->in -= s->stream.avail_in; + s->out -= s->stream.avail_out; + if (s->z_err != Z_OK) break; + } + s->crc = crc32(s->crc, (const Bytef *)buf, len); + + return (int)(len - s->stream.avail_in); +} + + +/* =========================================================================== + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). +*/ +#ifdef STDC +#include + +int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) +{ + char buf[Z_PRINTF_BUFSIZE]; + va_list va; + int len; + + buf[sizeof(buf) - 1] = 0; + va_start(va, format); +#ifdef NO_vsnprintf +# ifdef HAS_vsprintf_void + (void)vsprintf(buf, format, va); + va_end(va); + for (len = 0; len < sizeof(buf); len++) + if (buf[len] == 0) break; +# else + len = vsprintf(buf, format, va); + va_end(va); +# endif +#else +# ifdef HAS_vsnprintf_void + (void)vsnprintf(buf, sizeof(buf), format, va); + va_end(va); + len = strlen(buf); +# else + len = vsnprintf(buf, sizeof(buf), format, va); + va_end(va); +# endif +#endif + if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0) + return 0; + return gzwrite(file, buf, (unsigned)len); +} +#else /* not ANSI C */ + +int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) + gzFile file; + const char *format; + int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, + a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; +{ + char buf[Z_PRINTF_BUFSIZE]; + int len; + + buf[sizeof(buf) - 1] = 0; +#ifdef NO_snprintf +# ifdef HAS_sprintf_void + sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + for (len = 0; len < sizeof(buf); len++) + if (buf[len] == 0) break; +# else + len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#else +# ifdef HAS_snprintf_void + snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = strlen(buf); +# else + len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); +# endif +#endif + if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0) + return 0; + return gzwrite(file, buf, len); +} +#endif + +/* =========================================================================== + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ +int ZEXPORT gzputc(file, c) + gzFile file; + int c; +{ + unsigned char cc = (unsigned char) c; /* required for big endian systems */ + + return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; +} + + +/* =========================================================================== + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ +int ZEXPORT gzputs(file, s) + gzFile file; + const char *s; +{ + return gzwrite(file, (char*)s, (unsigned)strlen(s)); +} + + +/* =========================================================================== + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. +*/ +local int do_flush (file, flush) + gzFile file; + int flush; +{ + uInt len; + int done = 0; + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; + + s->stream.avail_in = 0; /* should be zero already anyway */ + + for (;;) { + len = Z_BUFSIZE - s->stream.avail_out; + + if (len != 0) { + if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { + s->z_err = Z_ERRNO; + return Z_ERRNO; + } + s->stream.next_out = s->outbuf; + s->stream.avail_out = Z_BUFSIZE; + } + if (done) break; + s->out += s->stream.avail_out; + s->z_err = deflate(&(s->stream), flush); + s->out -= s->stream.avail_out; + + /* Ignore the second of two consecutive flushes: */ + if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; + + /* deflate has finished flushing only when it hasn't used up + * all the available space in the output buffer: + */ + done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); + + if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; + } + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} + +int ZEXPORT gzflush (file, flush) + gzFile file; + int flush; +{ + gz_stream *s = (gz_stream*)file; + int err = do_flush (file, flush); + + if (err) return err; + fflush(s->file); + return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; +} +#endif /* NO_GZCOMPRESS */ + +/* =========================================================================== + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error. + SEEK_END is not implemented, returns error. + In this version of the library, gzseek can be extremely slow. +*/ +z_off_t ZEXPORT gzseek (file, offset, whence) + gzFile file; + z_off_t offset; + int whence; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || whence == SEEK_END || + s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { + return -1L; + } + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + return -1L; +#else + if (whence == SEEK_SET) { + offset -= s->in; + } + if (offset < 0) return -1L; + + /* At this point, offset is the number of zero bytes to write. */ + if (s->inbuf == Z_NULL) { + s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ + if (s->inbuf == Z_NULL) return -1L; + zmemzero(s->inbuf, Z_BUFSIZE); + } + while (offset > 0) { + uInt size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (uInt)offset; + + size = gzwrite(file, s->inbuf, size); + if (size == 0) return -1L; + + offset -= size; + } + return s->in; +#endif + } + /* Rest of function is for reading only */ + + /* compute absolute position */ + if (whence == SEEK_CUR) { + offset += s->out; + } + if (offset < 0) return -1L; + + if (s->transparent) { + /* map to fseek */ + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + + if (fseeko(s->file, offset, SEEK_SET) < 0) return -1L; + + s->in = s->out = offset; + return offset; + } + + /* For a negative seek, rewind and use positive seek */ + if (offset >= s->out) { + offset -= s->out; + } else if (gzrewind(file) < 0) { + return -1L; + } + /* offset is now the number of bytes to skip. */ + + if (offset != 0 && s->outbuf == Z_NULL) { + s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); + if (s->outbuf == Z_NULL) return -1L; + } + if (offset && s->back != EOF) { + s->back = EOF; + s->out++; + offset--; + if (s->last) s->z_err = Z_STREAM_END; + } + while (offset > 0) { + int size = Z_BUFSIZE; + if (offset < Z_BUFSIZE) size = (int)offset; + + size = gzread(file, s->outbuf, (uInt)size); + if (size <= 0) return -1L; + offset -= size; + } + return s->out; +} + +/* =========================================================================== + Rewinds input file. +*/ +int ZEXPORT gzrewind (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL || s->mode != 'r') return -1; + + s->z_err = Z_OK; + s->z_eof = 0; + s->back = EOF; + s->stream.avail_in = 0; + s->stream.next_in = s->inbuf; + s->crc = crc32(0L, Z_NULL, 0); + if (!s->transparent) (void)inflateReset(&s->stream); + s->in = 0; + s->out = 0; + return fseeko(s->file, s->start, SEEK_SET); +} + +/* =========================================================================== + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. +*/ +z_off_t ZEXPORT gztell (file) + gzFile file; +{ + return gzseek(file, 0L, SEEK_CUR); +} + +/* =========================================================================== + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ +int ZEXPORT gzeof (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + /* With concatenated compressed files that can have embedded + * crc trailers, z_eof is no longer the only/best indicator of EOF + * on a gz_stream. Handle end-of-stream error explicitly here. + */ + if (s == NULL || s->mode != 'r') return 0; + if (s->z_eof) return 1; + return s->z_err == Z_STREAM_END; +} + +/* =========================================================================== + Outputs a long in LSB order to the given file +*/ +local void putLong (file, x) + FILE *file; + uLong x; +{ + int n; + for (n = 0; n < 4; n++) { + fputc((int)(x & 0xff), file); + x >>= 8; + } +} + +/* =========================================================================== + Reads a long in LSB order from the given gz_stream. Sets z_err in case + of error. +*/ +local uLong getLong (s) + gz_stream *s; +{ + uLong x = (uLong)get_byte(s); + int c; + + x += ((uLong)get_byte(s))<<8; + x += ((uLong)get_byte(s))<<16; + c = get_byte(s); + if (c == EOF) s->z_err = Z_DATA_ERROR; + x += ((uLong)c)<<24; + return x; +} + +/* =========================================================================== + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. +*/ +int ZEXPORT gzclose (file) + gzFile file; +{ + int err; + gz_stream *s = (gz_stream*)file; + + if (s == NULL) return Z_STREAM_ERROR; + + if (s->mode == 'w') { +#ifdef NO_GZCOMPRESS + return Z_STREAM_ERROR; +#else + err = do_flush (file, Z_FINISH); + if (err != Z_OK) return destroy((gz_stream*)file); + + putLong (s->file, s->crc); + putLong (s->file, (uLong)(s->in & 0xffffffff)); +#endif + } + return destroy((gz_stream*)file); +} + +/* =========================================================================== + Returns the error message for the last error which occured on the + given compressed file. errnum is set to zlib error number. If an + error occured in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ +const char * ZEXPORT gzerror (file, errnum) + gzFile file; + int *errnum; +{ + char *m; + gz_stream *s = (gz_stream*)file; + + if (s == NULL) { + *errnum = Z_STREAM_ERROR; + return (const char*)ERR_MSG(Z_STREAM_ERROR); + } + *errnum = s->z_err; + if (*errnum == Z_OK) return (const char*)""; + + m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); + + if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); + + TRYFREE(s->msg); + s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); + if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); + strcpy(s->msg, s->path); + strcat(s->msg, ": "); + strcat(s->msg, m); + return (const char*)s->msg; +} + +/* =========================================================================== + Clear the error and end-of-file flags, and do the same for the real file. +*/ +void ZEXPORT gzclearerr (file) + gzFile file; +{ + gz_stream *s = (gz_stream*)file; + + if (s == NULL) return; + if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; + s->z_eof = 0; + clearerr(s->file); +} diff --git a/src/libz/infback.c b/src/libz/infback.c new file mode 100644 index 0000000..110b03b --- /dev/null +++ b/src/libz/infback.c @@ -0,0 +1,619 @@ +/* infback.c -- inflate using a call-back interface + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + This code is largely copied from inflate.c. Normally either infback.o or + inflate.o would be linked into an application--not both. The interface + with inffast.c is retained so that optimized assembler-coded versions of + inflate_fast() can be used with either inflate.c or infback.c. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); + +/* + strm provides memory allocation functions in zalloc and zfree, or + Z_NULL to use the library memory allocation functions. + + windowBits is in the range 8..15, and window is a user-supplied + window and output buffer that is 2**windowBits bytes. + */ +int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) +z_stream FAR *strm; +int windowBits; +unsigned char FAR *window; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL || window == Z_NULL || + windowBits < 8 || windowBits > 15) + return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *)ZALLOC(strm, 1, + sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (voidpf)state; + state->wbits = windowBits; + state->wsize = 1U << windowBits; + state->window = window; + state->write = 0; + state->whave = 0; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +/* Macros for inflateBack(): */ + +/* Load returned state from inflate_fast() */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Set state from registers for inflate_fast() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Assure that some input is available. If input is requested, but denied, + then return a Z_BUF_ERROR from inflateBack(). */ +#define PULL() \ + do { \ + if (have == 0) { \ + have = in(in_desc, &next); \ + if (have == 0) { \ + next = Z_NULL; \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflateBack() + with an error if there is no input available. */ +#define PULLBYTE() \ + do { \ + PULL(); \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflateBack() with + an error. */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Assure that some output space is available, by writing out the window + if it's full. If the write fails, return from inflateBack() with a + Z_BUF_ERROR. */ +#define ROOM() \ + do { \ + if (left == 0) { \ + put = state->window; \ + left = state->wsize; \ + state->whave = left; \ + if (out(out_desc, put, left)) { \ + ret = Z_BUF_ERROR; \ + goto inf_leave; \ + } \ + } \ + } while (0) + +/* + strm provides the memory allocation functions and window buffer on input, + and provides information on the unused input on return. For Z_DATA_ERROR + returns, strm will also provide an error message. + + in() and out() are the call-back input and output functions. When + inflateBack() needs more input, it calls in(). When inflateBack() has + filled the window with output, or when it completes with data in the + window, it calls out() to write out the data. The application must not + change the provided input until in() is called again or inflateBack() + returns. The application must not change the window/output buffer until + inflateBack() returns. + + in() and out() are called with a descriptor parameter provided in the + inflateBack() call. This parameter can be a structure that provides the + information required to do the read or write, as well as accumulated + information on the input and output such as totals and check values. + + in() should return zero on failure. out() should return non-zero on + failure. If either in() or out() fails, than inflateBack() returns a + Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it + was in() or out() that caused in the error. Otherwise, inflateBack() + returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format + error, or Z_MEM_ERROR if it could not allocate memory for the state. + inflateBack() can also return Z_STREAM_ERROR if the input parameters + are not correct, i.e. strm is Z_NULL or the state was not initialized. + */ +int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) +z_stream FAR *strm; +in_func in; +void FAR *in_desc; +out_func out; +void FAR *out_desc; +{ + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code this; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + /* Check that the strm exists and that the state was initialized */ + if (strm == Z_NULL || strm->state == Z_NULL) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* Reset the state */ + strm->msg = Z_NULL; + state->mode = TYPE; + state->last = 0; + state->whave = 0; + next = strm->next_in; + have = next != Z_NULL ? strm->avail_in : 0; + hold = 0; + bits = 0; + put = state->window; + left = state->wsize; + + /* Inflate until end of block marked as last */ + for (;;) + switch (state->mode) { + case TYPE: + /* determine and dispatch block type */ + if (state->last) { + BYTEBITS(); + state->mode = DONE; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + + case STORED: + /* get and verify stored block length */ + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + + /* copy stored block from input to output */ + while (state->length != 0) { + copy = state->length; + PULL(); + ROOM(); + if (copy > have) copy = have; + if (copy > left) copy = left; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + + case TABLE: + /* get dynamic table entries descriptor */ + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + + /* get code length code lengths (not a typo) */ + state->have = 0; + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + + /* get length and distance code code lengths */ + state->have = 0; + while (state->have < state->nlen + state->ndist) { + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } + else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = (unsigned)(state->lens[state->have - 1]); + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(this.bits + 7); + DROPBITS(this.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* build code tables */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + + case LEN: + /* use inflate_fast() if we have enough input and output */ + if (have >= 6 && left >= 258) { + RESTORE(); + if (state->whave < state->wsize) + state->whave = state->wsize - left; + inflate_fast(strm, state->wsize); + LOAD(); + break; + } + + /* get a literal, length, or end-of-block code */ + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + + /* process literal */ + if (this.op == 0) { + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + ROOM(); + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + } + + /* process end of block */ + if (this.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + + /* invalid code */ + if (this.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + + /* length code -- get extra bits, if any */ + state->extra = (unsigned)(this.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + + /* get distance code */ + for (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + + /* get distance extra bits, if any */ + state->extra = (unsigned)(this.op) & 15; + if (state->extra != 0) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->wsize - (state->whave < state->wsize ? + left : 0)) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + + /* copy match from window to output */ + do { + ROOM(); + copy = state->wsize - state->offset; + if (copy < left) { + from = put + copy; + copy = left - copy; + } + else { + from = put - state->offset; + copy = left; + } + if (copy > state->length) copy = state->length; + state->length -= copy; + left -= copy; + do { + *put++ = *from++; + } while (--copy); + } while (state->length != 0); + break; + + case DONE: + /* inflate stream terminated properly -- write leftover output */ + ret = Z_STREAM_END; + if (left < state->wsize) { + if (out(out_desc, state->window, state->wsize - left)) + ret = Z_BUF_ERROR; + } + goto inf_leave; + + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + + default: /* can't happen, but makes compilers happy */ + ret = Z_STREAM_ERROR; + goto inf_leave; + } + + /* Return unused input */ + inf_leave: + strm->next_in = next; + strm->avail_in = have; + return ret; +} + +int ZEXPORT inflateBackEnd(strm) +z_stream FAR *strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} diff --git a/src/libz/inffast.c b/src/libz/inffast.c new file mode 100644 index 0000000..c716440 --- /dev/null +++ b/src/libz/inffast.c @@ -0,0 +1,305 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifndef ASMINF + +/* Allow machine dependent optimization for post-increment or pre-increment. + Based on testing to date, + Pre-increment preferred for: + - PowerPC G3 (Adler) + - MIPS R5000 (Randers-Pehrson) + Post-increment preferred for: + - none + No measurable difference: + - Pentium III (Anderson) + - 68060 (Nikl) + */ +#ifdef POSTINC +# define OFF 0 +# define PUP(a) *(a)++ +#else +# define OFF 1 +# define PUP(a) *++(a) +#endif + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + unsigned char FAR *in; /* local strm->next_in */ + unsigned char FAR *last; /* while in < last, enough input available */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned write; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code this; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); + wsize = state->wsize; + whave = state->whave; + write = state->write; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + this = lcode[hold & lmask]; + dolen: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op == 0) { /* literal */ + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + PUP(out) = (unsigned char)(this.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(this.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + this = dcode[hold & dmask]; + dodist: + op = (unsigned)(this.bits); + hold >>= op; + bits -= op; + op = (unsigned)(this.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(this.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + from = window - OFF; + if (write == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (write < op) { /* wrap around window */ + from += wsize + write - op; + op -= write; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (write < len) { /* some from start of window */ + op = write; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += write - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + this = dcode[this.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + this = lcode[this.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and write == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/src/libz/inffast.h b/src/libz/inffast.h new file mode 100644 index 0000000..1e88d2d --- /dev/null +++ b/src/libz/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/src/libz/inffixed.h b/src/libz/inffixed.h new file mode 100644 index 0000000..75ed4b5 --- /dev/null +++ b/src/libz/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. It + is part of the implementation of the compression library and + is subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/src/libz/inflate.c b/src/libz/inflate.c new file mode 100644 index 0000000..a53b5c7 --- /dev/null +++ b/src/libz/inflate.c @@ -0,0 +1,1270 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common write == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, unsigned out)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, + unsigned len)); + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->wsize = 0; + state->whave = 0; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; + } + if (strm->zfree == (free_func)0) strm->zfree = zcfree; + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (voidpf)state; + if (windowBits < 0) { + state->wrap = 0; + windowBits = -windowBits; + } + else { + state->wrap = (windowBits >> 4) + 1; +#ifdef GUNZIP + if (windowBits < 48) windowBits &= 15; +#endif + } + if (windowBits < 8 || windowBits > 15) { + ZFREE(strm, state); + strm->state = Z_NULL; + return Z_STREAM_ERROR; + } + state->wbits = (unsigned)windowBits; + state->window = Z_NULL; + return inflateReset(strm); +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, + state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, out) +z_streamp strm; +unsigned out; +{ + struct inflate_state FAR *state; + unsigned copy, dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->write = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + copy = out - strm->avail_out; + if (copy >= state->wsize) { + zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); + state->write = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->write; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->write, strm->next_out - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, strm->next_out - copy, copy); + state->write = copy; + state->whave = state->wsize; + } + else { + state->write += dist; + if (state->write == state->wsize) state->write = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* Reverse the bytes in a 32-bit value */ +#define REVERSE(q) \ + ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code this; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + if (BITS(4) + 8 > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + } + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + } while (len && copy < have); + if (state->flags & 0x02000) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + } while (len && copy < have); + if (state->flags & 0x02000) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if (hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = REVERSE(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN; /* decode codes */ + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.val < 16) { + NEEDBITS(this.bits); + DROPBITS(this.bits); + state->lens[state->have++] = this.val; + } + else { + if (this.val == 16) { + NEEDBITS(this.bits + 2); + DROPBITS(this.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (this.val == 17) { + NEEDBITS(this.bits + 3); + DROPBITS(this.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(this.bits + 7); + DROPBITS(this.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* build code tables */ + state->next = state->codes; + state->lencode = (code const FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (code const FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + break; + } + for (;;) { + this = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if (this.op && (this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + state->length = (unsigned)this.val; + if ((int)(this.op) == 0) { + Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", this.val)); + state->mode = LIT; + break; + } + if (this.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + if (this.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(this.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->mode = DIST; + case DIST: + for (;;) { + this = state->distcode[BITS(state->distbits)]; + if ((unsigned)(this.bits) <= bits) break; + PULLBYTE(); + } + if ((this.op & 0xf0) == 0) { + last = this; + for (;;) { + this = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + this.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + } + DROPBITS(this.bits); + if (this.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)this.val; + state->extra = (unsigned)(this.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + } + if (state->offset > state->whave + out - left) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->write) { + copy -= state->write; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->write - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if (out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if (( +#ifdef GUNZIP + state->flags ? hold : +#endif + REVERSE(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) + if (updatewindow(strm, out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if (state->wrap && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long id; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->mode != DICT) return Z_STREAM_ERROR; + + /* check for correct dictionary id */ + id = adler32(0L, Z_NULL, 0); + id = adler32(id, dictionary, dictLength); + if (id != state->check) return Z_DATA_ERROR; + + /* copy dictionary to window */ + if (updatewindow(strm, strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + if (dictLength > state->wsize) { + zmemcpy(state->window, dictionary + dictLength - state->wsize, + state->wsize); + state->whave = state->wsize; + } + else { + zmemcpy(state->window + state->wsize - dictLength, dictionary, + dictLength); + state->whave = dictLength; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + + /* check input */ + if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || + source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + *dest = *source; + *copy = *state; + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) + zmemcpy(window, state->window, 1U << state->wbits); + copy->window = window; + dest->state = (voidpf)copy; + return Z_OK; +} diff --git a/src/libz/inflate.h b/src/libz/inflate.h new file mode 100644 index 0000000..9a12c8f --- /dev/null +++ b/src/libz/inflate.h @@ -0,0 +1,117 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD, /* i: waiting for magic header */ +#ifdef GUNZIP + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ +#endif + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN, /* i: waiting for length/lit code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ +#ifdef GUNZIP + LENGTH, /* i: waiting for 32-bit length (gzip) */ +#endif + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to the BAD or MEM mode -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME + NAME -> COMMENT -> HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + Read deflate blocks: + TYPE -> STORED or TABLE or LEN or CHECK + STORED -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN + Read deflate codes: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* state maintained between inflate() calls. Approximately 7K bytes. */ +struct inflate_state { + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned write; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ +}; diff --git a/src/libz/inftrees.c b/src/libz/inftrees.c new file mode 100644 index 0000000..3bb5639 --- /dev/null +++ b/src/libz/inftrees.c @@ -0,0 +1,321 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.1 Copyright 1995-2003 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int inflate_table(type, lens, codes, table, bits, work) +codetype type; +unsigned short FAR *lens; +unsigned codes; +code FAR * FAR *table; +unsigned FAR *bits; +unsigned short FAR *work; +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code this; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 76, 66}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) return -1; /* no codes! */ + for (min = 1; min <= MAXBITS; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || (codes - count[0] != 1))) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked when a LENS table is being made + against the space in *table, ENOUGH, minus the maximum space needed by + the worst case distance code, MAXD. This should never happen, but the + sufficiency of ENOUGH has not been proven exhaustively, hence the check. + This assumes that when type == LENS, bits == 9. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if (type == LENS && used >= ENOUGH - MAXD) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + this.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + this.op = (unsigned char)0; + this.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + this.op = (unsigned char)(extra[work[sym]]); + this.val = base[work[sym]]; + } + else { + this.op = (unsigned char)(32 + 64); /* end of block */ + this.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + do { + fill -= incr; + next[(huff >> drop) + fill] = this; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += 1U << curr; + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if (type == LENS && used >= ENOUGH - MAXD) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* + Fill in rest of table for incomplete codes. This loop is similar to the + loop above in incrementing huff for table indices. It is assumed that + len is equal to curr + drop, so there is no loop needed to increment + through high index bits. When the current sub-table is filled, the loop + drops back to the root table to fill in any remaining entries there. + */ + this.op = (unsigned char)64; /* invalid code marker */ + this.bits = (unsigned char)(len - drop); + this.val = (unsigned short)0; + while (huff != 0) { + /* when done with sub-table, drop back to root table */ + if (drop != 0 && (huff & mask) != low) { + drop = 0; + len = root; + next = *table; + curr = root; + this.bits = (unsigned char)len; + } + + /* put invalid code marker in table */ + next[huff >> drop] = this; + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/src/libz/inftrees.h b/src/libz/inftrees.h new file mode 100644 index 0000000..82d365a --- /dev/null +++ b/src/libz/inftrees.h @@ -0,0 +1,55 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2003 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of dynamic tree. The maximum found in a long but non- + exhaustive search was 1004 code structures (850 for length/literals + and 154 for distances, the latter actually the result of an + exhaustive search). The true maximum is not known, but the value + below is more than safe. */ +#define ENOUGH 1440 +#define MAXD 154 + +/* Type of code to build for inftable() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +extern int inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/src/libz/trees.c b/src/libz/trees.c new file mode 100644 index 0000000..bb09554 --- /dev/null +++ b/src/libz/trees.c @@ -0,0 +1,1215 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2003 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +#define Buf_size (8 * 2*sizeof(char)) +/* Number of bits used within bi_buf. (bi_buf might be implemented on + * more than 16 bits on some systems.) + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, ct_data *ltree, + ct_data *dtree)); +local void set_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (value << s->bi_valid); + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (val << s->bi_valid);\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; + s->last_eob_len = 8; /* enough lookahead for inflate */ +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if (tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void _tr_stored_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + * The current inflate code requires 9 bits of lookahead. If the + * last two codes for the previous block (real code plus EOB) were coded + * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode + * the last real code. In this case we send two empty static blocks instead + * of one. (There are no problems if the previous block is stored or fixed.) + * To simplify the code, we assume the worst case of last real code encoded + * on one bit only. + */ +void _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); + /* Of the 10 bits for the empty block, we have already sent + * (10 - bi_valid) bits. The lookahead for the last real code (before + * the EOB of the previous block) was thus at least one plus the length + * of the EOB plus what we have just sent of the empty static block. + */ + if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; +#endif + bi_flush(s); + } + s->last_eob_len = 7; +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void _tr_flush_block(s, buf, stored_len, eof) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int eof; /* true if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is ascii or binary */ + if (s->data_type == Z_UNKNOWN) set_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, eof); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+eof, 3); + compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+eof, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#endif + } + Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (eof) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*eof)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + ct_data *ltree; /* literal tree */ + ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); + s->last_eob_len = ltree[END_BLOCK].Len; +} + +/* =========================================================================== + * Set the data type to ASCII or BINARY, using a crude approximation: + * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. + * IN assertion: the fields freq of dyn_ltree are set and the total of all + * frequencies does not exceed 64K (to fit in an int on 16 bit machines). + */ +local void set_data_type(s) + deflate_state *s; +{ + int n = 0; + unsigned ascii_freq = 0; + unsigned bin_freq = 0; + while (n < 7) bin_freq += s->dyn_ltree[n++].Freq; + while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq; + while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq; + s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII); +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + s->last_eob_len = 8; /* enough lookahead for inflate */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} diff --git a/src/libz/trees.h b/src/libz/trees.h new file mode 100644 index 0000000..72facf9 --- /dev/null +++ b/src/libz/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/src/libz/uncompr.c b/src/libz/uncompr.c new file mode 100644 index 0000000..b59e3d0 --- /dev/null +++ b/src/libz/uncompr.c @@ -0,0 +1,61 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *destLen = stream.total_out; + + err = inflateEnd(&stream); + return err; +} diff --git a/src/libz/zconf.h b/src/libz/zconf.h new file mode 100644 index 0000000..50092c2 --- /dev/null +++ b/src/libz/zconf.h @@ -0,0 +1,322 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflatePrime z_deflatePrime +# define deflateParams z_deflateParams +# define deflateBound z_deflateBound +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateCopy z_inflateCopy +# define inflateReset z_inflateReset +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table + +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32) +# define WIN32 +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +# include /* for off_t */ +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# define z_off_t off_t + +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif +#ifndef z_off_t +# define z_off_t long +#endif + +#if defined(__OS400__) +#define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +# ifdef FAR +# undef FAR +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) +# pragma map(deflateInit_,"DEIN") +# pragma map(deflateInit2_,"DEIN2") +# pragma map(deflateEnd,"DEEND") +# pragma map(deflateBound,"DEBND") +# pragma map(inflateInit_,"ININ") +# pragma map(inflateInit2_,"ININ2") +# pragma map(inflateEnd,"INEND") +# pragma map(inflateSync,"INSY") +# pragma map(inflateSetDictionary,"INSEDI") +# pragma map(compressBound,"CMBND") +# pragma map(inflate_table,"INTABL") +# pragma map(inflate_fast,"INFA") +# pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/src/libz/zlib.h b/src/libz/zlib.h new file mode 100644 index 0000000..92edf96 --- /dev/null +++ b/src/libz/zlib.h @@ -0,0 +1,1200 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.1, November 17th, 2003 + + Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.1" +#define ZLIB_VERNUM 0x1210 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed + data. This version of the library supports only one compression method + (deflation) but other algorithms will be added later and will have the same + stream interface. + + Compression can be done in a single step if the buffers are large + enough (for example if an input file is mmap'ed), or can be done by + repeated calls of the compression function. In the latter case, the + application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by the in-memory functions is the zlib + format, which is a zlib wrapper documented in RFC 1950, wrapped around a + deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + This library does not provide any functions to write gzip files in memory. + However such functions could be easily written using zlib's deflate function, + the documentation in the gzip RFC, and the examples in gzio.c. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never + crash even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: ascii or binary */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + The application must update next_in and avail_in when avail_in has + dropped to zero. It must update next_out and avail_out when avail_out + has dropped to zero. The application must initialize zalloc, zfree and + opaque before calling the init function. All other fields are set by the + compression library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this + if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + pointers returned by zalloc for objects of exactly 65536 bytes *must* + have their offset normalized to zero. The default allocation function + provided by this library ensures this (see zutil.c). To reduce memory + requirements and avoid any allocation of 64K objects, at the expense of + compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or + progress reports. After compression, total_in holds the total size of + the uncompressed data and may be saved for use in the decompressor + (particularly if the decompressor wants to decompress everything in + a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative + * values are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_ASCII 1 +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is + not compatible with the zlib.h header file used by the application. + This check is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. + If zalloc and zfree are set to Z_NULL, deflateInit updates them to + use default allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at + all (the input data is simply copied a block at a time). + Z_DEFAULT_COMPRESSION requests a default compromise between speed and + compression (currently equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if level is not a valid compression level, + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). + msg is set to null if there is no error message. deflateInit does not + perform any compression: this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce some + output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). + Some output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating avail_in or avail_out accordingly; avail_out + should never be zero before the call. The application can consume the + compressed output when it wants, for example when the output buffer is full + (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + and with zero avail_out, it must be called again after making room in the + output buffer because there might be more output pending. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In particular + avail_in is zero after the call if enough output space has been provided + before the call.) Flushing may degrade compression for some compression + algorithms and so it should be used only when necessary. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + the compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there + was enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the + stream are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least + the value returned by deflateBound (see below). If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update data_type if it can make a good guess about + the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered + binary. This field is only for information purposes and does not affect + the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, + msg may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller. msg is set to null if there is no error + message. inflateInit does not perform any decompression apart from reading + the zlib header if present: this will be done by inflate(). (So next_in and + avail_in may be modified, but next_out and avail_out are unchanged.) +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing + will resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there + is no more input data or no more space in the output buffer (see below + about the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating the next_* and avail_* values accordingly. + The application can consume the uncompressed output when it wants, for + example when the output buffer is full (avail_out == 0), or after each + call of inflate(). If inflate returns Z_OK and with zero avail_out, it + must be called again after making room in the output buffer because there + might be more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, + Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() stop + if and when it get to the next deflate block boundary. When decoding the zlib + or gzip format, this will cause inflate() to return immediately after the + header and before the first block. When doing a raw inflate, inflate() will + go ahead and process the first block, and will return when it gets to the end + of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 + if inflate() is currently decoding the last block in the deflate stream, + plus 128 if inflate() returned immediately after decoding an end-of-block + code or decoding the complete header up to just before the first byte of the + deflate stream. The end-of-block will not be indicated until all of the + uncompressed data from that block has been written to strm->next_out. The + number of unused bits may in general be greater than seven, except when + bit 7 of data_type is set, in which case the number of unused bits will be + less than eight. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step + (a single call of inflate), the parameter flush should be set to + Z_FINISH. In this case all pending input is processed and all pending + output is flushed; avail_out must be large enough to hold all the + uncompressed data. (The size of the uncompressed data may have been saved + by the compressor for this purpose.) The next operation on this stream must + be inflateEnd to deallocate the decompression state. The use of Z_FINISH + is never required, but can be used to inform inflate that a faster approach + may be used for the single inflate() call. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the only effect of the flush parameter in this implementation + is on the return value of inflate(), as noted below, or when it returns early + because Z_BLOCK is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm-adler to the adler32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the adler32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() will decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically. Any information + contained in the gzip header is not retained, so applications that need that + information should instead use raw inflate, see inflateInit2() below, or + inflateBack() and perform their own processing of the gzip header and + trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may then + call inflateSync() to look for a good compression block if a partial recovery + of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by + the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), + no header crc, and the operating system will be set to 255 (unknown). + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but + is slow and reduces compression ratio; memLevel=9 uses maximum memory + for optimal speed. The default value is 8. See zconf.h for total memory + usage as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as + Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy + parameter only affects the compression ratio but not the correctness of the + compressed output even if it is not set appropriately. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + method). msg is set to null if there is no error message. deflateInit2 does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any + call of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size in + deflate or deflate2. Thus the strings most likely to be useful should be + put at the end of the dictionary, not at the front. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and + can consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. + The stream will keep the same compression level and any other attributes + that may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different + strategy. If the compression level is changed, the input available so far + is compressed with the old level (and may be flushed); the new level will + take effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to + be compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + if strm->avail_out was zero. +*/ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() + or deflateInit2(). This would be used to allocate an output buffer + for deflation in a single pass, and so would be called before deflate(). +*/ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the + bits leftover from a previous deflate stream when appending to it. As such, + this function can only be used for raw deflate, and must be used before the + first deflate() call after a deflateInit2() or deflateReset(). bits must be + less than or equal to 16, and that many of the least significant bits of + value will be inserted in the output. + + deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative + memLevel). msg is set to null if there is no error message. inflateInit2 + does not perform any decompression apart from reading the zlib header if + present: this will be done by inflate(). (So next_in and avail_in may be + modified, but next_out and avail_out are unchanged.) +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate + if this call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by this call of + inflate. The compressor and decompressor must use exactly the same + dictionary (see deflateSetDictionary). + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been found, + or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + case, the application may save the current current value of total_in which + indicates where valid compressed data was found. In the error case, the + application may repeatedly call inflateSync, providing more input each time, + until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. + The stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the paramaters are invalid, Z_MEM_ERROR if the internal state could not + be allocated, or Z_VERSION_ERROR if the version of the library does not + match the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is more efficient than inflate() for + file i/o applications in that it avoids copying between the output and the + sliding window by simply making the window itself the output buffer. This + function trusts the application to not change the output buffer passed by + the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free + the allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects + only the raw deflate stream to decompress. This is different from the + normal behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format + error in the deflate stream (in which case strm->msg is set to indicate the + nature of the error), or Z_STREAM_ERROR if the stream was not properly + initialized. In the case of Z_BUF_ERROR, an input or output error can be + distinguished using strm->next_in which will be Z_NULL only if in() returned + an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to + out() returning non-zero. (in() will always be called before out(), so + strm->next_in is assured to be defined if out() returns non-zero.) Note + that inflateBack() cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_stream FAR *strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the + basic stream-oriented functions. To simplify the interface, some + default options are assumed (compression level and memory usage, + standard memory allocation functions). The source code of these + utility functions can easily be modified if you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be at least the value returned + by compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + This function can be used to compress a whole file at once if the + input file is mmap'ed. + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before + a compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. +*/ + + +typedef voidp gzFile; + +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); +/* + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb") but can also include a compression level + ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + Huffman only compression as in "wb1h", or 'R' for run-length encoding + as in "wb1R". (See the description of deflateInit2 for more information + about the strategy parameter.) + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). */ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen() associates a gzFile with the file descriptor fd. File + descriptors are obtained from calls like open, dup, creat, pipe or + fileno (in the file has been previously opened with fopen). + The mode parameter is as in gzopen. + The next call of gzclose on the returned gzFile will also close the + file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + gzdopen returns NULL if there was insufficient memory to allocate + the (de)compression state. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. + If the input file was not in gzip format, gzread copies the given number + of bytes into the buffer. + gzread returns the number of uncompressed bytes actually read (0 for + end of file, -1 for error). */ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes actually written + (0 in case of error). +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). The number of + uncompressed bytes written is limited to 4095. The caller should assure that + this limit is not exceeded. If it is exceeded, then gzprintf() will return + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or + a newline character is read and transferred to buf, or an end-of-file + condition is encountered. The string is then terminated with a null + character. + gzgets returns buf, or Z_NULL in case of error. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read again later. + Only one character of push-back is allowed. gzungetc() returns the + character pushed, or -1 on failure. gzungetc() will fail if a + character has been pushed but not read yet, or if c is -1. The pushed + character will be discarded if the stream is repositioned with gzseek() + or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. The return value is the zlib + error number (see function gzerror below). gzflush returns Z_OK if + the flush parameter is Z_FINISH and all output could be flushed. + gzflush should be called only when strictly necessary because it can + degrade compression. +*/ + +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); +/* + Sets the starting position for the next gzread or gzwrite on the + given compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); +/* + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. The return value is the zlib + error number (see function gzerror below). +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the + given compressed file. errnum is set to zlib error number. If an + error occurred in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the + compression library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); + +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is NULL, this function returns + the required initial value for the checksum. + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running crc with the bytes buf[0..len-1] and return the updated + crc. If buf is NULL, this function returns the required initial value + for the crc. Pre- and post-conditioning (one's complement) is performed + within this function so it shouldn't be done by the application. + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_stream FAR *strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + + +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; /* hack for buggy compilers */ +#endif + +ZEXTERN const char * ZEXPORT zError OF((int err)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/src/libz/zutil.c b/src/libz/zutil.c new file mode 100644 index 0000000..0ef4f99 --- /dev/null +++ b/src/libz/zutil.c @@ -0,0 +1,319 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +#ifndef STDC +extern void exit OF((int)); +#endif + +const char * const z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch (sizeof(uInt)) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch (sizeof(uLong)) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch (sizeof(voidpf)) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch (sizeof(z_off_t)) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1 << 16; +#endif +#ifdef NO_GZIP + flags += 1 << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1 << 20; +#endif +#ifdef FASTEST + flags += 1 << 21; +#endif +#ifdef STDC +# ifdef NO_vsnprintf + flags += 1 << 25; +# ifdef HAS_vsprintf_void + flags += 1 << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1 << 26; +# endif +# endif +#else + flags += 1 << 24; +# ifdef NO_snprintf + flags += 1 << 25; +# ifdef HAS_sprintf_void + flags += 1 << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1 << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int z_verbose = verbose; + +void z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* does not exist on WCE */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ diff --git a/src/libz/zutil.h b/src/libz/zutil.h new file mode 100644 index 0000000..87b70ac --- /dev/null +++ b/src/libz/zutil.h @@ -0,0 +1,258 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#define ZLIB_INTERNAL +#include "zlib.h" + +#ifdef STDC +# include +# include +# include +#endif +#ifdef NO_ERRNO_H + extern int errno; +#else +# include +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = (char*)ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS + /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 + /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# define vsnprintf _vsnprintf +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +#endif + +#ifdef HAVE_STRERROR + extern char *strerror OF((int)); +# define zstrerror(errnum) strerror(errnum) +#else +# define zstrerror(errnum) "" +#endif + +#if defined(pyr) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + extern void zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include + extern int z_verbose; + extern void z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + + +voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); +void zcfree OF((voidpf opaque, voidpf ptr)); + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +#endif /* ZUTIL_H */ diff --git a/src/lx2.c b/src/lx2.c index 701542d..4ccc8af 100644 --- a/src/lx2.c +++ b/src/lx2.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 2003. + * Copyright (c) Tony Bybell 2003-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -10,7 +10,9 @@ #include #include "lx2.h" +#ifndef _MSC_VER #include +#endif #include #include @@ -18,26 +20,20 @@ #include "aet.h" #include "vcd.h" #include "lxt.h" +#include "vzt.h" #include "lxt2_read.h" #include "debug.h" + /* * globals */ -char is_lx2 = 0; +unsigned char is_lx2 = LXT2_IS_INACTIVE; static struct lxt2_rd_trace *lx2=NULL; static TimeType first_cycle, last_cycle, total_cycles; -static TimeType time_scale=1; /* multiplier is 1, 10, 100 */ - -struct lx2_entry -{ -struct HistEnt *histent_head, *histent_curr; -int numtrans; -nptr np; -}; - -struct lx2_entry *lx2_table = NULL; + +static struct lx2_entry *lx2_table = NULL; static struct fac *mvlfacs=NULL; @@ -50,6 +46,7 @@ struct Node *n; struct symbol *s, *prevsymroot=NULL, *prevsym=NULL; signed char scale; +unsigned int numalias = 0; lx2 = lxt2_rd_init(fname); if(!lx2) @@ -61,45 +58,14 @@ /* lxt2_rd_set_max_block_mem_usage(lx2, 0); */ scale=(signed char)lxt2_rd_get_timescale(lx2); -switch(scale) - { - case 0: time_dimension = 's'; break; - - case -1: time_scale = LLDescriptor(100); time_dimension = 'm'; break; - case -2: time_scale = LLDescriptor(10); - case -3: time_dimension = 'm'; break; - - case -4: time_scale = LLDescriptor(100); time_dimension = 'u'; break; - case -5: time_scale = LLDescriptor(10); - case -6: time_dimension = 'u'; break; - - case -10: time_scale = LLDescriptor(100); time_dimension = 'p'; break; - case -11: time_scale = LLDescriptor(10); - case -12: time_dimension = 'p'; break; - - case -13: time_scale = LLDescriptor(100); time_dimension = 'f'; break; - case -14: time_scale = LLDescriptor(10); - case -15: time_dimension = 'f'; break; - - case -7: time_scale = LLDescriptor(100); time_dimension = 'n'; break; - case -8: time_scale = LLDescriptor(10); - case -9: - default: time_dimension = 'n'; break; - } - +exponent_to_time_scale(scale); numfacs=lxt2_rd_get_num_facs(lx2); -mvlfacs=(struct fac *)calloc(numfacs,sizeof(struct fac)); -lx2_table=(struct lx2_entry *)calloc(numfacs, sizeof(struct lx2_entry)); +mvlfacs=(struct fac *)calloc_2(numfacs,sizeof(struct fac)); +lx2_table=(struct lx2_entry *)calloc_2(numfacs, sizeof(struct lx2_entry)); for(i=0;i1) + { + free_2(mvlfacs[i-2].name); + mvlfacs[i-2].name = NULL; + } + if(mvlfacs[i].flags&LXT2_RD_SYM_F_ALIAS) { int alias = mvlfacs[i].array_height; @@ -135,6 +125,8 @@ { f=mvlfacs+f->array_height; } + + numalias++; } else { @@ -153,13 +145,15 @@ { strcpy_vcdalt(str, buf, alt_hier_delimeter); } - s=symadd(str,hash(str)); + s=symadd_name_exists(str,hash(str)); prevsymroot = prevsym = NULL; } - else if ( (f->len==1)&&(!(f->flags&(LXT2_RD_SYM_F_INTEGER|LXT2_RD_SYM_F_DOUBLE|LXT2_RD_SYM_F_STRING)))&& - ((i!=numfacs-1)&&(!strcmp(mvlfacs[i].name, mvlfacs[i+1].name))) || - ((i!=0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) && - (mvlfacs[i].msb!=-1)&&(mvlfacs[i].lsb!=-1) + else if ( + ((f->len==1)&&(!(f->flags&(LXT2_RD_SYM_F_INTEGER|LXT2_RD_SYM_F_DOUBLE|LXT2_RD_SYM_F_STRING)))&& + ((i!=numfacs-1)&&(!strcmp(mvlfacs[i].name, mvlfacs[i+1].name)))) + || + (((i!=0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) && + (mvlfacs[i].msb!=-1)&&(mvlfacs[i].lsb!=-1)) ) { sprintf(buf, "%s[%d]", mvlfacs[i].name,mvlfacs[i].msb); @@ -172,7 +166,7 @@ { strcpy_vcdalt(str, buf, alt_hier_delimeter); } - s=symadd(str,hash(str)); + s=symadd_name_exists(str,hash(str)); if((prevsym)&&(i>0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) /* allow chaining for search functions.. */ { prevsym->vec_root = prevsymroot; @@ -196,7 +190,7 @@ { strcpy_vcdalt(str, mvlfacs[i].name, alt_hier_delimeter); } - s=symadd(str,hash(str)); + s=symadd_name_exists(str,hash(str)); prevsymroot = prevsym = NULL; if(f->flags&LXT2_RD_SYM_F_INTEGER) @@ -235,51 +229,131 @@ s->n=n; } +for(i=0;((i<2)&&(iname))>longestname) longestname=len; - curnode=curnode->nextinaet; - while((ch=(*subst))) - { - if(ch==hier_delimeter) { *subst=0x01; } /* forces sort at hier boundaries */ - subst++; - } - } - -fprintf(stderr, LXT2_RDLOAD"Sorting facilities at hierarchy boundaries.\n"); -wave_heapsort(facs,numfacs); + +if(fast_tree_sort) + { + curnode=firstnode; + for(i=0;iname))>longestname) longestname=len; + curnode=curnode->nextinaet; + } + + if(numalias) + { + unsigned int idx_lft = 0; + unsigned int idx_lftmax = numfacs - numalias; + unsigned int idx_rgh = numfacs - numalias; + struct symbol **facs_merge=(struct symbol **)malloc_2(numfacs*sizeof(struct symbol *)); + + fprintf(stderr, LXT2_RDLOAD"Merging in %d aliases.\n", numalias); + + for(i=0;iname, facs[idx_rgh]->name) <= 0) + { + facs_merge[i] = facs[idx_lft++]; + + if(idx_lft == idx_lftmax) + { + for(i++;iname, i); + } + treeprune(treeroot); + + fprintf(stderr, LXT2_RDLOAD"Sorting facility hierarchy tree.\n"); + treesort(treeroot, NULL); + order_facs_from_treesort(treeroot, &facs); + + facs_are_sorted=1; + } + else + { + curnode=firstnode; + for(i=0;iname))>longestname) longestname=len; + curnode=curnode->nextinaet; + while((ch=(*subst))) + { + if(ch==hier_delimeter) { *subst=0x01; } /* forces sort at hier boundaries */ + subst++; + } + } + + fprintf(stderr, LXT2_RDLOAD"Sorting facilities at hierarchy boundaries.\n"); + wave_heapsort(facs,numfacs); -for(i=0;iname; - while((ch=(*subst))) - { - if(ch==0x01) { *subst=hier_delimeter; } /* restore back to normal */ - subst++; - } - } - -facs_are_sorted=1; - -fprintf(stderr, LXT2_RDLOAD"Building facility hierarchy tree.\n"); - -init_tree(); -for(i=0;iname, i); -} -treeprune(treeroot); + for(i=0;iname; + while((ch=(*subst))) + { + if(ch==0x01) { *subst=hier_delimeter; } /* restore back to normal */ + subst++; + } + } + + facs_are_sorted=1; + + fprintf(stderr, LXT2_RDLOAD"Building facility hierarchy tree.\n"); + + init_tree(); + for(i=0;iname, i); + } + treeprune(treeroot); + } min_time = first_cycle; max_time=last_cycle; -is_lx2 = ~0; +is_lx2 = LXT2_IS_LXT2; if(skip_start || skip_end) { @@ -320,7 +394,7 @@ /* * lx2 callback (only does bits for now) */ -void lx2_callback(struct lxt2_rd_trace **lt, lxtint64_t *time, lxtint32_t *facidx, char **value) +static void lx2_callback(struct lxt2_rd_trace **lt, lxtint64_t *time, lxtint32_t *facidx, char **value) { struct HistEnt *htemp = histent_calloc(); struct lx2_entry *l2e = lx2_table+(*facidx); @@ -400,10 +474,19 @@ void import_lx2_trace(nptr np) { struct HistEnt *htemp, *histent_tail; -int len, i, j; +int len, i; struct fac *f; int txidx; nptr nold = np; + +switch(is_lx2) + { +#ifdef AET2_IS_PRESENT + case LXT2_IS_AET2: import_ae2_trace(np); return; +#endif + case LXT2_IS_VZT: import_vzt_trace(np); return; + default: break; /* fallthrough */ + } if(!(f=np->mvlfac)) return; /* already imported */ @@ -502,11 +585,18 @@ */ void lx2_set_fac_process_mask(nptr np) { -struct HistEnt *htemp, *histent_tail; -int len, i, j; struct fac *f; int txidx; +switch(is_lx2) + { +#ifdef AET2_IS_PRESENT + case LXT2_IS_AET2: ae2_set_fac_process_mask(np); return; +#endif + case LXT2_IS_VZT: vzt_set_fac_process_mask(np); return; + default: break; /* fallthrough */ + } + if(!(f=np->mvlfac)) return; /* already imported */ txidx = f-mvlfacs; @@ -527,10 +617,20 @@ } -void lx2_import_masked() +void lx2_import_masked(void) { -int txidx, i, cnt=0; - +int txidx, i, cnt; + +switch(is_lx2) + { +#ifdef AET2_IS_PRESENT + case LXT2_IS_AET2: ae2_import_masked(); return; +#endif + case LXT2_IS_VZT: vzt_import_masked(); return; + default: break; /* fallthrough */ + } + +cnt = 0; for(txidx=0;txidx +#endif + #include "vcd.h" +#include "ae2.h" -extern char is_lx2; +enum LXT2_Loader_Type_Encodings { LXT2_IS_INACTIVE, LXT2_IS_LXT2, LXT2_IS_VZT, LXT2_IS_AET2 }; + +struct lx2_entry +{ +struct HistEnt *histent_head, *histent_curr; +int numtrans; +nptr np; +}; + +extern unsigned char is_lx2; TimeType lx2_main(char *fname, char *skip_start, char *skip_end); void import_lx2_trace(nptr np); void lx2_set_fac_process_mask(nptr np); -void lx2_import_masked(); +void lx2_import_masked(void); #endif diff --git a/src/lxt.c b/src/lxt.c index 82ad0c4..c95012e 100644 --- a/src/lxt.c +++ b/src/lxt.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 2001-2002. + * Copyright (c) Tony Bybell 2001-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -8,11 +8,16 @@ */ #include -#include -#include - +#include "zlib.h" +#include "bzlib.h" + +#if !defined __MINGW32__ && !defined _MSC_VER #include #include +#else +#include +#include +#endif #include #include @@ -25,6 +30,7 @@ #include "bsearch.h" #include "debug.h" + /****************************************************************************/ /* @@ -102,24 +108,22 @@ static struct fac *mvlfacs=NULL; static TimeType first_cycle, last_cycle, total_cycles; -static TimeType time_scale=1; /* multiplier is 1, 10, 100 */ static int maxchange=0, maxindex=0; -static int trace_start=0; static off_t f_len; static int *positional_information=NULL; TimeType *time_information=NULL; -static unsigned int change_field_offset=0; -static unsigned int facname_offset=0; -static unsigned int facgeometry_offset=0; -static unsigned int time_table_offset=0; -static unsigned int time_table_offset64=0; -static unsigned int sync_table_offset=0; -static unsigned int initial_value_offset=0; -static unsigned int timescale_offset=0; -static unsigned int double_test_offset=0; -static unsigned int zdictionary_offset=0; +static off_t change_field_offset=0; +static off_t facname_offset=0; +static off_t facgeometry_offset=0; +static off_t time_table_offset=0; +static off_t time_table_offset64=0; +static off_t sync_table_offset=0; +static off_t initial_value_offset=0; +static off_t timescale_offset=0; +static off_t double_test_offset=0; +static off_t zdictionary_offset=0; static unsigned int zfacname_predec_size=0; static unsigned int zfacname_size=0; @@ -134,19 +138,50 @@ static unsigned int dict_num_entries; static unsigned int dict_string_mem_required; -static unsigned int dict_16_offset; -static unsigned int dict_24_offset; -static unsigned int dict_32_offset; +static off_t dict_16_offset; +static off_t dict_24_offset; +static off_t dict_32_offset; static unsigned int dict_width; static char **dict_string_mem_array=NULL; -static unsigned int exclude_offset=0; +static off_t exclude_offset=0; static char *lt_buf=NULL; /* max memory ever needed for parse_offset() */ static int lt_len = 0; static int fd; /* XXX : win32 requires decompression tempfiles since */ /* its mmap() variant doesn't use file descriptors */ +#if defined __MINGW32__ || defined _MSC_VER +#define PROT_READ (0) +#define MAP_SHARED (0) + +HANDLE hIn, hInMap; +char *win_fname = NULL; + +void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) +{ +close(fd); +hIn = CreateFile(win_fname, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +if(hIn == INVALID_HANDLE_VALUE) +{ + fprintf(stderr, "Could not open '%s' with CreateFile(), exiting.\n", win_fname); + exit(255); +} + +hInMap = CreateFileMapping(hIn, NULL, PAGE_READONLY, 0, 0, NULL); +return(MapViewOfFile(hInMap, FILE_MAP_READ, 0, 0, 0)); +} + +int munmap(void *start, size_t length) +{ +UnmapViewOfFile(start); +CloseHandle(hInMap); hInMap = NULL; +CloseHandle(hIn); hIn = NULL; +return(0); +} + + +#endif /****************************************************************************/ @@ -174,11 +209,11 @@ * of a big-endian integer. x86 specific version... */ -#ifdef __i386__ +#if defined(__i386__) || defined(__x86_64__) #define get_byte(offset) ((unsigned int)(*((unsigned char *)mm+offset))) -inline static unsigned int get_16(int offset) +inline static unsigned int get_16(off_t offset) { unsigned short x = *((unsigned short *)((unsigned char *)mm+offset)); @@ -189,7 +224,7 @@ return (unsigned int) x; } -inline static unsigned int get_32(int offset) /* note that bswap is really 486+ */ +inline static unsigned int get_32(off_t offset) /* note that bswap is really 486+ */ { unsigned int x = *((unsigned int *)((unsigned char *)mm+offset)); @@ -211,7 +246,7 @@ */ #define get_byte(offset) ((unsigned int)(*((unsigned char *)mm+offset))) -static unsigned int get_16(int offset) +static unsigned int get_16(off_t offset) { unsigned char *nn=(unsigned char *)mm+offset; unsigned int m1=*((unsigned char *)(nn++)); @@ -219,7 +254,7 @@ return((m1<<8)|m2); } -static unsigned int get_24(int offset) +static unsigned int get_24(off_t offset) { unsigned char *nn=(unsigned char *)mm+offset; unsigned int m1=*((unsigned char *)(nn++)); @@ -228,7 +263,7 @@ return((m1<<16)|(m2<<8)|m3); } -static unsigned int get_32(int offset) +static unsigned int get_32(off_t offset) { unsigned char *nn=(unsigned char *)mm+offset; unsigned int m1=*((unsigned char *)(nn++)); @@ -238,7 +273,7 @@ return((m1<<24)|(m2<<16)|(m3<<8)|m4); } -static UTimeType get_64(int offset) +static UTimeType get_64(off_t offset) { return( (((UTimeType)get_32(offset))<<32) @@ -251,7 +286,7 @@ /****************************************************************************/ -static char double_mask[8]={0,0,0,0,0,0,0,0}; +static unsigned char double_mask[8]={0,0,0,0,0,0,0,0}; static char double_is_native=0; static void create_double_endian_mask(int offset) @@ -359,13 +394,14 @@ */ static void build_dict(void) { -FILE *tmp; gzFile zhandle; -int offs = zdictionary_offset+24; +off_t offs = zdictionary_offset+24; int total_mem, rc, i; char *decmem=NULL; char *pnt; -unsigned char *t; +#if defined __MINGW32__ || defined _MSC_VER +FILE *tmp; +#endif dict_num_entries = get_32(zdictionary_offset+0); dict_string_mem_required = get_32(zdictionary_offset+4); @@ -382,10 +418,19 @@ DEBUG(fprintf(stderr, LXTHDR"dict_24_offset = %d\n", dict_24_offset)); DEBUG(fprintf(stderr, LXTHDR"dict_32_offset = %d\n", dict_32_offset)); -printf(LXTHDR"Dictionary compressed MVL2 change records detected...\n"); - -if(offs!=lseek(fd, offs, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", offs); exit(255); } +fprintf(stderr, LXTHDR"Dictionary compressed MVL2 change records detected...\n"); + +#if defined __MINGW32__ || defined _MSC_VER +{ +unsigned char *t = (char *)mm+offs; +tmp = tmpfile(); if(!tmp) { fprintf(stderr, LXTHDR"could not open decompression tempfile, exiting.\n"); exit(255); } +fwrite(t, zdictionary_predec_size, 1, tmp); fseek(tmp, 0, SEEK_SET); +zhandle = gzdopen(dup(fileno(tmp)), "rb"); +} +#else +if(offs!=lseek(fd, offs, SEEK_SET)) { fprintf(stderr, LXTHDR"dict lseek error at offset %08x\n", (unsigned int)offs); exit(255); } zhandle = gzdopen(dup(fd), "rb"); +#endif decmem = malloc_2(total_mem = dict_string_mem_required); rc=gzread(zhandle, decmem, total_mem); @@ -403,8 +448,11 @@ } gzclose(zhandle); - -printf(LXTHDR"...expanded %d entries from %08x into %08x bytes.\n", dict_num_entries, zdictionary_predec_size, dict_string_mem_required); +#if defined __MINGW32__ || defined _MSC_VER +fclose(tmp); +#endif + +fprintf(stderr, LXTHDR"...expanded %d entries from %08x into %08x bytes.\n", dict_num_entries, zdictionary_predec_size, dict_string_mem_required); } @@ -414,12 +462,16 @@ static void build_facs(char *fname) { char *buf, *bufprev, *bufcurr; -int offs=facname_offset+8; +off_t offs=facname_offset+8; int i, j, clone; char *pnt; int total_mem = get_32(facname_offset+4); -gzFile zhandle; +gzFile zhandle = NULL; char *decmem=NULL; + +#if defined __MINGW32__ || defined _MSC_VER +FILE *tmp; +#endif buf=malloc_2(total_mem); pnt=bufprev=buf; @@ -427,9 +479,15 @@ if(zfacname_size) { int rc; - - if(offs!=lseek(fd, offs, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", offs); exit(255); } +#if defined __MINGW32__ || defined _MSC_VER + unsigned char *t = (char *)mm+offs; + tmp = tmpfile(); if(!tmp) { fprintf(stderr, LXTHDR"could not open decompression tempfile, exiting.\n"); exit(255); } + fwrite(t, zfacname_size, 1, tmp); fseek(tmp, 0, SEEK_SET); + zhandle = gzdopen(dup(fileno(tmp)), "rb"); +#else + if(offs!=lseek(fd, offs, SEEK_SET)) { fprintf(stderr, LXTHDR"zfacname lseek error at offset %08x\n", (unsigned int)offs); exit(255); } zhandle = gzdopen(dup(fd), "rb"); +#endif mmcache = mm; decmem = malloc_2(total_mem = zfacname_predec_size); mm = decmem; @@ -442,7 +500,7 @@ offs=0; /* we're in our new memory region now.. */ } -printf(LXTHDR"Building %d facilities.\n", numfacs); +fprintf(stderr, LXTHDR"Building %d facilities.\n", numfacs); for(i=0;i 128*1024*1024) { char *nam = tmpnam(NULL); @@ -730,13 +832,13 @@ unlink(nam); - printf(LXTHDR"Compressed change records detected, making tempfile...\n"); - if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", change_field_offset); exit(255); } + fprintf(stderr, LXTHDR"Compressed change records detected, making tempfile...\n"); + if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", (unsigned int)change_field_offset); exit(255); } read(fd, &testbyte, 2); is_bz2 = (testbyte[0]=='B')&&(testbyte[1]=='Z'); - if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", change_field_offset); exit(255); } + if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", (unsigned int)change_field_offset); exit(255); } if(is_bz2) { @@ -747,11 +849,11 @@ int siz = (len>32768) ? 32768 : len; rc = BZ2_bzread(zhandle, buf, siz); if(rc!=siz) { fprintf(stderr, LXTHDR"gzread error to tempfile %d (act) vs %d (exp), exiting.\n", rc, siz); exit(255); } - if(1 != fwrite(buf, siz, 1, tmp)) { fprintf(stderr, LXTHDR"fwrite error to tempfile, exiting.\n", rc, siz); exit(255); }; + if(1 != fwrite(buf, siz, 1, tmp)) { fprintf(stderr, LXTHDR"fwrite error to tempfile, exiting.\n"); exit(255); }; len -= siz; } - printf(LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); + fprintf(stderr, LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); BZ2_bzclose(zhandle); } else @@ -763,23 +865,25 @@ int siz = (len>32768) ? 32768 : len; rc = gzread(zhandle, buf, siz); if(rc!=siz) { fprintf(stderr, LXTHDR"gzread error to tempfile %d (act) vs %d (exp), exiting.\n", rc, siz); exit(255); } - if(1 != fwrite(buf, siz, 1, tmp)) { fprintf(stderr, LXTHDR"fwrite error to tempfile, exiting.\n", rc, siz); exit(255); }; + if(1 != fwrite(buf, siz, 1, tmp)) { fprintf(stderr, LXTHDR"fwrite error to tempfile, exiting.\n"); exit(255); }; len -= siz; } - printf(LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); + fprintf(stderr, LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); gzclose(zhandle); } munmap(mm, f_len); close(fd); fflush(tmp); - fseek(tmp, 0, SEEK_SET); + fseeko(tmp, 0, SEEK_SET); fclose(tmp); fd = fd2; mm=mmap(NULL, zchg_predec_size, PROT_READ, MAP_SHARED, fd, 0); - mm-=4; /* because header and version don't exist in packed change records */ + + mm=(void *)((char *)mm-4); /* because header and version don't exist in packed change records */ } else +#endif { unsigned int len=zchg_predec_size; int rc; @@ -787,19 +891,32 @@ char *pnt = buf; char testbyte[2]={0,0}; char is_bz2; - - printf(LXTHDR"Compressed change records detected...\n"); - if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", change_field_offset); exit(255); } + + fprintf(stderr, LXTHDR"Compressed change records detected...\n"); +#if defined __MINGW32__ || defined _MSC_VER + { + unsigned char *t = (char *)mm+change_field_offset; + tmp = tmpfile(); if(!tmp) { fprintf(stderr, LXTHDR"could not open decompression tempfile, exiting.\n"); exit(255); } + fwrite(t, zchg_size, 1, tmp); fseek(tmp, 0, SEEK_SET); + is_bz2 = (get_byte(change_field_offset)=='B') && (get_byte(change_field_offset+1)=='Z'); + } +#else + if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", (unsigned int)change_field_offset); exit(255); } read(fd, &testbyte, 2); is_bz2 = (testbyte[0]=='B')&&(testbyte[1]=='Z'); - if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", change_field_offset); exit(255); } + if(change_field_offset != lseek(fd, change_field_offset, SEEK_SET)) { fprintf(stderr, LXTHDR"lseek error at offset %08x\n", (unsigned int)change_field_offset); exit(255); } +#endif if(is_bz2) { +#if defined __MINGW32__ || defined _MSC_VER + zhandle = BZ2_bzdopen(dup(fileno(tmp)), "rb"); +#else zhandle = BZ2_bzdopen(dup(fd), "rb"); - +#endif + while(len) { int siz = (len>32768) ? 32768 : len; @@ -809,13 +926,16 @@ len -= siz; } - printf(LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); + fprintf(stderr, LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); BZ2_bzclose(zhandle); } else { +#if defined __MINGW32__ || defined _MSC_VER + zhandle = gzdopen(dup(fileno(tmp)), "rb"); +#else zhandle = gzdopen(dup(fd), "rb"); - +#endif while(len) { int siz = (len>32768) ? 32768 : len; @@ -825,12 +945,18 @@ len -= siz; } - printf(LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); + fprintf(stderr, LXTHDR"...expanded %08x into %08x bytes.\n", zchg_size, zchg_predec_size); gzclose(zhandle); - } - - munmap(mm, f_len); close(fd); - +#if defined __MINGW32__ || defined _MSC_VER + fclose(tmp); +#endif + } + + munmap(mm, f_len); +#if !defined __MINGW32__ && !defined _MSC_VER + close(fd); +#endif + fd=-1; mm=buf-4; /* because header and version don't exist in packed change records */ } @@ -839,8 +965,8 @@ if(!sync_table_offset) { - unsigned int vlen = zchg_predec_size ? zchg_predec_size+4 : 0; - unsigned int offs = zchg_predec_size ? 4 : 0; + off_t vlen = zchg_predec_size ? zchg_predec_size+4 : 0; + off_t offs = zchg_predec_size ? 4 : 0; unsigned int numfacs_bytes; unsigned int num_records = 0; unsigned int last_change_delta, numbytes; @@ -856,7 +982,7 @@ FILE *tmp; int recfd; - printf(LXTHDR"Linear LXT encountered...\n"); + fprintf(stderr, LXTHDR"Linear LXT encountered...\n"); if(!zchg_predec_size) { @@ -892,10 +1018,9 @@ while(offs < vlen) { - unsigned int facidx; + unsigned int facidx = 0; unsigned char cmd; - unsigned int offscache = offs; - unsigned int offscache2, offscache3; + off_t offscache2, offscache3; unsigned int height; unsigned char cmdkill; @@ -922,7 +1047,7 @@ if(facidx>numfacs) { - fprintf(stderr, LXTHDR"Facidx %d out of range (vs %d) at offset %08x, exiting.\n", facidx, numfacs, offs); + fprintf(stderr, LXTHDR"Facidx %d out of range (vs %d) at offset %08x, exiting.\n", facidx, numfacs, (unsigned int)offs); exit(255); } @@ -935,7 +1060,7 @@ if(cmd>0xf) { - fprintf(stderr, LXTHDR"Command byte %02x invalid at offset %08x, exiting.\n", cmd, offs); + fprintf(stderr, LXTHDR"Command byte %02x invalid at offset %08x, exiting.\n", cmd, (unsigned int)offs); exit(0); } @@ -1101,7 +1226,7 @@ if(offs-offscache2) { - fpos += fwrite(mm+offscache2, 1, offs-offscache2, tmp); /* copy rest of relevant info */ + fpos += fwrite((char *)mm+offscache2, 1, offs-offscache2, tmp); /* copy rest of relevant info */ } } @@ -1110,22 +1235,27 @@ dict_32_offset = dict_32_offset_new; fflush(tmp); - fseek(tmp, 0, SEEK_SET); + fseeko(tmp, 0, SEEK_SET); fclose(tmp); - printf(LXTHDR"%d linear records converted into %08x bytes.\n", num_records, fpos-4); - + fprintf(stderr, LXTHDR"%d linear records converted into %08x bytes.\n", num_records, fpos-4); + +#if !defined __MINGW32__ && !defined _MSC_VER if(zchg_predec_size > 128*1024*1024) { - munmap(mm+4, zchg_predec_size); close(fd); + munmap((char *)mm+4, zchg_predec_size); close(fd); } else - { - free(mm+4); - } - - fd = recfd; +#endif + { + free((char *)mm+4); + } + + fd = recfd; +#if defined __MINGW32__ || defined _MSC_VER + win_fname = nam; +#endif mm=mmap(NULL, fpos-4, PROT_READ, MAP_SHARED, recfd, 0); - mm-=4; /* because header and version don't exist in packed change records */ + mm=(void *)((char *)mm-4); /* because header and version don't exist in packed change records */ } } @@ -1133,7 +1263,7 @@ /* * given a fac+offset, return the binary data for it */ -static char *parse_offset(struct fac *which, unsigned int offs) +static char *parse_offset(struct fac *which, off_t offs) { int v, v2, j; int k, l; @@ -1191,7 +1321,7 @@ } else { - fprintf(stderr, LXTHDR"dict entry at offset %08x [%d] out of range, ignoring!\n", dictpos, offs); + fprintf(stderr, LXTHDR"dict entry at offset %08x [%d] out of range, ignoring!\n", dictpos, (unsigned int)offs); for(j=0;jLT_VERSION) +if((version=get_16((off_t)2))>LT_VERSION) { fprintf(stderr, "Version %d of LXT format AETs not supported, exiting.\n", version); exit(255); @@ -1332,7 +1465,7 @@ tagpnt = f_len-2; while((tag=get_byte(tagpnt))!=LT_SECTION_END) { - int offset = get_32(tagpnt-4); + off_t offset = get_32(tagpnt-4); tagpnt-=5; switch(tag) @@ -1366,7 +1499,7 @@ if(exclude_offset) { - unsigned int offset = exclude_offset; + off_t offset = exclude_offset; int i, num_blackouts = get_32(offset); TimeType bs, be; struct blackout_region_t *bt; @@ -1397,31 +1530,7 @@ signed char scale; scale=(signed char)get_byte(timescale_offset); - switch(scale) - { - case 0: time_dimension = 's'; break; - - case -1: time_scale = LLDescriptor(100); time_dimension = 'm'; break; - case -2: time_scale = LLDescriptor(10); - case -3: time_dimension = 'm'; break; - - case -4: time_scale = LLDescriptor(100); time_dimension = 'u'; break; - case -5: time_scale = LLDescriptor(10); - case -6: time_dimension = 'u'; break; - - case -10: time_scale = LLDescriptor(100); time_dimension = 'p'; break; - case -11: time_scale = LLDescriptor(10); - case -12: time_dimension = 'p'; break; - - case -13: time_scale = LLDescriptor(100); time_dimension = 'f'; break; - case -14: time_scale = LLDescriptor(10); - case -15: time_dimension = 'f'; break; - - case -7: time_scale = LLDescriptor(100); time_dimension = 'n'; break; - case -8: time_scale = LLDescriptor(10); - case -9: - default: time_dimension = 'n'; break; - } + exponent_to_time_scale(scale); } else { @@ -1455,6 +1564,7 @@ initial_value = 1; } + if(zdictionary_offset) { if(zdictionary_predec_size) @@ -1512,13 +1622,15 @@ { strcpy_vcdalt(str, buf, alt_hier_delimeter); } - s=symadd(str,hash(str)); + s=symadd_name_exists(str,hash(str)); prevsymroot = prevsym = NULL; } - else if ( (f->len==1)&&(!(f->flags&(LT_SYM_F_INTEGER|LT_SYM_F_DOUBLE|LT_SYM_F_STRING)))&& - ((i!=numfacs-1)&&(!strcmp(mvlfacs[i].name, mvlfacs[i+1].name))) || - ((i!=0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) && - (mvlfacs[i].msb!=-1)&&(mvlfacs[i].lsb!=-1) + else if ( + ((f->len==1)&&(!(f->flags&(LT_SYM_F_INTEGER|LT_SYM_F_DOUBLE|LT_SYM_F_STRING)))&& + ((i!=numfacs-1)&&(!strcmp(mvlfacs[i].name, mvlfacs[i+1].name)))) + || + (((i!=0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) && + (mvlfacs[i].msb!=-1)&&(mvlfacs[i].lsb!=-1)) ) { sprintf(buf, "%s[%d]", mvlfacs[i].name,mvlfacs[i].msb); @@ -1531,7 +1643,7 @@ { strcpy_vcdalt(str, buf, alt_hier_delimeter); } - s=symadd(str,hash(str)); + s=symadd_name_exists(str,hash(str)); if((prevsym)&&(i>0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) /* allow chaining for search functions.. */ { prevsym->vec_root = prevsymroot; @@ -1555,7 +1667,7 @@ { strcpy_vcdalt(str, mvlfacs[i].name, alt_hier_delimeter); } - s=symadd(str,hash(str)); + s=symadd_name_exists(str,hash(str)); prevsymroot = prevsym = NULL; if(f->flags<_SYM_F_INTEGER) @@ -1593,6 +1705,12 @@ s->n=n; } +free(mvlfacs[0].name); /* the start of the big decompression buffer */ +for(i=0;iname, i); } treeprune(treeroot); -printf("built.\n\n"); +fprintf(stderr, "built.\n\n"); #ifdef DEBUG_FACILITIES treedebug(treeroot,""); #endif min_time = first_cycle*time_scale; max_time=last_cycle*time_scale; -printf("["TTFormat"] start time.\n["TTFormat"] end time.\n", min_time, max_time); +fprintf(stderr, "["TTFormat"] start time.\n["TTFormat"] end time.\n", min_time, max_time); is_lxt = ~0; return(max_time); @@ -1677,9 +1793,8 @@ */ void import_lxt_trace(nptr np) { -unsigned int offs, offsdelta; +off_t offs, offsdelta; int v, w; -int ary_indx, ary_skip; TimeType tmval; TimeType prevtmval; struct HistEnt *htemp; @@ -1763,11 +1878,11 @@ if(f->array_height < 1) /* sorry, arrays not supported */ while(offs) { - unsigned char val; + unsigned char val = 0; if( (w=((v=get_byte(offs))&0xF)) >0xb) { - unsigned int offsminus1, offsminus2, offsminus3; + off_t offsminus1, offsminus2, offsminus3; TimeType delta, time_offsminus1; int skip; @@ -1790,7 +1905,7 @@ offsdelta=get_32(offs+1); break; default: - fprintf(stderr, "Unknown %02x at offset: %08x\n", v, offs); + fprintf(stderr, "Unknown %02x at offset: %08x\n", v, (unsigned int)offs); exit(0); } offsminus1 = offs-offsdelta-2; @@ -1810,7 +1925,7 @@ offsdelta=get_32(offsminus1+1); break; default: - fprintf(stderr, "Unknown %02x at offset: %08x\n", get_byte(offsminus1), offsminus1); + fprintf(stderr, "Unknown %02x at offset: %08x\n", get_byte(offsminus1), (unsigned int)offsminus1); exit(0); } offsminus2 = offsminus1-offsdelta-2; @@ -1825,7 +1940,7 @@ if(!lxt_clock_compress_to_z) { int val = get_byte(offsminus1)&0xF; - int reps; + int reps = 0; int rcnt; unsigned int reconstructm1 = 0; unsigned int reconstructm2 = 0; @@ -1835,7 +1950,7 @@ if((val!=0)&&(val!=3)&&(val!=4)) { - fprintf(stderr, "Unexpected clk compress byte %02x at offset: %08x\n", get_byte(offsminus1), offsminus1); + fprintf(stderr, "Unexpected clk compress byte %02x at offset: %08x\n", get_byte(offsminus1), (unsigned int)offsminus1); exit(0); } @@ -1884,7 +1999,7 @@ offsdelta=get_32(offsminus2+1); break; default: - fprintf(stderr, "Unknown %02x at offset: %08x\n", get_byte(offsminus2), offsminus2); + fprintf(stderr, "Unknown %02x at offset: %08x\n", get_byte(offsminus2), (unsigned int)offsminus2); exit(0); } offsminus3 = offsminus2-offsdelta-2; @@ -1955,12 +2070,12 @@ if(!lxt_clock_compress_to_z) { int val = get_byte(offsminus1)&0xF; - int reps; + int reps = 0; int rcnt; if((val<3)||(val>4)) { - fprintf(stderr, "Unexpected clk compress byte %02x at offset: %08x\n", get_byte(offsminus1), offsminus1); + fprintf(stderr, "Unexpected clk compress byte %02x at offset: %08x\n", get_byte(offsminus1), (unsigned int)offsminus1); exit(0); } @@ -2132,7 +2247,7 @@ break; default: - fprintf(stderr, "Unknown %02x at offset: %08x\n", v, offs); + fprintf(stderr, "Unknown %02x at offset: %08x\n", v, (unsigned int)offs); exit(0); } diff --git a/src/lxt.h b/src/lxt.h index 885fbd7..ed5f684 100644 --- a/src/lxt.h +++ b/src/lxt.h @@ -1,5 +1,18 @@ +/* + * Copyright (c) Tony Bybell 2001-2004. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + */ + #ifndef WAVE_LXT_H #define WAVE_LXT_H + +#if defined __MINGW32__ || defined _MSC_VER +#define fseeko fseek +#endif #include "vcd.h" diff --git a/src/main.c b/src/main.c index e464209..e53fba4 100644 --- a/src/main.c +++ b/src/main.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2003. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -9,21 +9,30 @@ #include #include +#include #ifdef __linux__ /* need to find getopt_long for non glibc platforms! */ #include #else +#ifndef _MSC_VER #include +#else +#include "getopt.c" +#define strcasecmp _stricmp +#endif #endif #include "aet.h" #include "lx2.h" +#include "ae2.h" +#include "vzt.h" #include "main.h" #include "menu.h" #include "vcd.h" #include "lxt.h" #include "lxt2_read.h" +#include "vzt_read.h" #include "pixmaps.h" #include "currenttime.h" #include "fgetdynamic.h" @@ -35,7 +44,13 @@ GtkWidget *wavewindow; char paned_pack_semantics=1; /* 1 for paned_pack, 0 for paned_add */ char zoom_was_explicitly_set=0; /* set on '*' encountered in .sav file read */ +#if defined _MSC_VER || defined __MINGW32__ +int initial_window_x=800, initial_window_y=400; /* initial window sizes */ +#else int initial_window_x=700, initial_window_y=400; /* initial window sizes */ +#endif + +int num_cpus=1; int initial_window_xpos=-1, initial_window_ypos=-1; /* initial window position (-1 == WM choice) */ char use_scrollbar_only=0; char force_toolbars=0; /* 1 sez use toolbar rendering */ @@ -47,45 +62,93 @@ printf( "Usage: %s [OPTION]... [DUMPFILE] [SAVEFILE] [RCFILE]\n\n" +" -n, --nocli=DIRPATH use file requester for dumpfile name\n" " -f, --dump=FILE specify dumpfile name\n" " -a, --save=FILE specify savefile name\n" " -r, --rcfile=FILE specify override .rcfile name\n" -" -s, --start=TIME specify start time for LXT2 block skip\n" -" -e, --end=TIME specify end time for LXT2 block skip\n" +" -i, --indirect=FILE specify indirect facs file name\n" +" -s, --start=TIME specify start time for LXT2/VZT block skip\n" +" -e, --end=TIME specify end time for LXT2/VZT block skip\n" +" -c, --cpu=NUMCPUS specify number of CPUs for parallelizable ops\n" " -v, --vcd use stdin as a VCD dumpfile\n" -" -h, --help display this help and exit\n" +" -V, --version display version banner then exit\n" +" -h, --help display this help then exit\n" " -x --exit exit after loading trace (for loader benchmarks)\n\n" -"VCD files and save files may be compressed with zip or gzip. LXT and\n" -"LXT2 files must remain uncompressed due to their non-linear access.\n" -"Note that DUMPFILE is optional provided the --dump option is specified.\n" +"VCD files and save files may be compressed with zip or gzip.\n" +"Other formats must remain uncompressed due to their non-linear access.\n" +"Note that DUMPFILE is optional if the --dump or --nocli options are specified.\n" "SAVEFILE and RCFILE are always optional.\n\n" -"Report bugs to .\n",nam); - -#else +"Report bugs to .\n",nam); + +#else + +#if !defined _MSC_VER && !defined __MINGW32__ && !defined __FreeBSD__ +#define WAVE_GETOPT_CPUS " -c NUMCPUS specify number of CPUs for parallelizable ops\n" +#else +#define WAVE_GETOPT_CPUS +#endif printf( "Usage: %s [OPTION]... [DUMPFILE] [SAVEFILE] [RCFILE]\n\n" +" -n DIRPATH use file requester for dumpfile name\n" " -f FILE specify dumpfile name\n" " -a FILE specify savefile name\n" " -r FILE specify override .rcfile name\n" -" -s TIME specify start time for LXT2 block skip\n" -" -e TIME specify end time for LXT2 block skip\n" +" -i FILE specify indirect facs file name\n" +" -s TIME specify start time for LXT2/VZT block skip\n" +" -e TIME specify end time for LXT2/VZT block skip\n" +WAVE_GETOPT_CPUS " -v use stdin as a VCD dumpfile\n" -" -h display this help and exit\n" +" -V display version banner then exit\n" +" -h display this help then exit\n" " -x exit after loading trace (for loader benchmarks)\n\n" -"VCD files and save files may be compressed with zip or gzip. LXT and\n" -"LXT2 files must remain uncompressed due to their non-linear access.\n" -"Note that DUMPFILE is optional provided the -f option is specified.\n" +"VCD files and save files may be compressed with zip or gzip.\n" +"Other formats must remain uncompressed due to their non-linear access.\n" +"Note that DUMPFILE is optional provided the -f or -n options are specified.\n" "SAVEFILE and RCFILE are always optional.\n\n" -"Report bugs to .\n",nam); - +"Report bugs to .\n",nam); + +#undef WAVE_GETOPT_CPUS #endif exit(0); +} + + +/* + * file selection for -n/--nocli flag + */ +static char *ftext_main = NULL; + +static void wave_get_filename_cleanup(GtkWidget *widget, gpointer data) { gtk_main_quit(); /* do nothing but exit gtk loop */ } + +static char *wave_get_filename(char *dfile) +{ +if(dfile) + { + int len = strlen(dfile); + ftext_main = malloc_2(strlen(dfile)+2); + strcpy(ftext_main, dfile); +#if !defined _MSC_VER && !defined __MINGW32__ + if((len)&&(dfile[len-1]!='/')) + { + strcpy(ftext_main + len, "/"); + } +#else + if((len)&&(dfile[len-1]!='\\')) + { + strcpy(ftext_main + len, "\\"); + } +#endif + } +fileselbox("GTKWave: Select a dumpfile...",&ftext_main,GTK_SIGNAL_FUNC(wave_get_filename_cleanup), GTK_SIGNAL_FUNC(wave_get_filename_cleanup)); +gtk_main(); + +return(ftext_main); } @@ -105,6 +168,7 @@ static char *winstd="GTKWave (stdio) "; static char *vcd_autosave_name="vcd_autosave.sav"; FILE *wave; +char *indirect_fname=NULL; GtkWidget *window; GtkWidget *main_vbox, *top_table, *whole_table; @@ -119,7 +183,7 @@ GtkWidget *timebox; GtkWidget *panedwindow; GtkWidget *dummy1, *dummy2; -GtkWidget *toolbar=NULL, *toolhandle=NULL; +GtkWidget *toolhandle=NULL; char *skip_start=NULL, *skip_end=NULL; @@ -140,25 +204,37 @@ static struct option long_options[] = { {"dump", 1, 0, 'f'}, + {"nocli", 1, 0, 'n'}, {"save", 1, 0, 'a'}, {"rcfile", 1, 0, 'r'}, + {"indirect", 1, 0, 'i'}, {"start", 1, 0, 's'}, {"end", 1, 0, 'e'}, + {"cpus", 1, 0, 'c'}, {"vcd", 0, 0, 'v'}, + {"version", 0, 0, 'V'}, {"help", 0, 0, 'h'}, {"exit", 0, 0, 'x'}, {0, 0, 0, 0} }; - c = getopt_long (argc, argv, "f:a:r:s:e:vhx", long_options, &option_index); -#else - c = getopt (argc, argv, "f:a:r:s:e:vhx"); + c = getopt_long (argc, argv, "f:n:a:r:i:s:e:c:vVhx", long_options, &option_index); +#else + c = getopt (argc, argv, "f:n:a:r:i:s:e:c:vVhx"); #endif if (c == -1) break; /* no more args */ switch (c) { + case 'V': + printf( + WAVE_VERSION_INFO"\n\n" + "This is free software; see the source for copying conditions. There is NO\n" + "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n" + ); + exit(0); + case 'v': is_vcd = 1; if(fname) free_2(fname); @@ -166,6 +242,16 @@ strcpy(fname, "-vcd"); break; + case 'n': + wave_get_filename(optarg); + if(filesel_ok) + { + if(fname) free_2(fname); + fname = ftext_main; + ftext_main = NULL; + } + break; + case 'h': print_help(argv[0]); break; @@ -193,6 +279,12 @@ strcpy(override_rc, optarg); break; + case 'i': + if(indirect_fname) free_2(indirect_fname); + indirect_fname = malloc_2(strlen(optarg)+1); + strcpy(indirect_fname, optarg); + break; + case 's': if(skip_start) free(skip_start); skip_start = malloc_2(strlen(optarg)+1); @@ -203,6 +295,14 @@ if(skip_end) free(skip_end); skip_end = malloc_2(strlen(optarg)+1); strcpy(skip_end, optarg); + break; + + case 'c': +#if !defined _MSC_VER && !defined __MINGW32__ + num_cpus = atoi(optarg); + if(num_cpus<1) num_cpus = 1; + if(num_cpus>8) num_cpus = 8; +#endif break; case '?': @@ -250,7 +350,7 @@ } read_rc_file(override_rc); -printf("\n%s\n\n",WAVE_VERSION_INFO); +fprintf(stderr, "\n%s\n\n",WAVE_VERSION_INFO); if((!wname)&&(make_vcd_save_file)) { @@ -274,7 +374,7 @@ strcat(winname,fname); -if((strlen(fname)>3)&&((!strcmp(fname+strlen(fname)-4,".lxt"))||(!strcmp(fname+strlen(fname)-4,".lx2")))) +if((strlen(fname)>3)&&((!strcasecmp(fname+strlen(fname)-4,".lxt"))||(!strcasecmp(fname+strlen(fname)-4,".lx2")))) { FILE *f = fopen(fname, "rb"); int typ = 0; @@ -299,20 +399,48 @@ else { lx2_main(fname, skip_start, skip_end); - if(skip_start) - { - free(skip_start); skip_start=NULL; - } - if(skip_end) - { - free(skip_end); skip_end=NULL; - } } - + } +else +if((strlen(fname)>3)&&(!strcasecmp(fname+strlen(fname)-4,".vzt"))) + { + vzt_main(fname, skip_start, skip_end); + } +else if ((strlen(fname)>3)&&((!strcasecmp(fname+strlen(fname)-4,".aet"))||(!strcasecmp(fname+strlen(fname)-4,".ae2")))) + { + ae2_main(fname, skip_start, skip_end, indirect_fname); + } +else if (strlen(fname)>4) /* case for .aet? type filenames */ + { + char sufbuf[5]; + memcpy(sufbuf, fname+strlen(fname)-5, 4); + sufbuf[4] = 0; + if(!strcasecmp(sufbuf, ".aet")) /* strncasecmp() in windows? */ + { + ae2_main(fname, skip_start, skip_end, indirect_fname); + } + else + { + vcd_main(fname); + } } else /* nothing else left so default to "something" */ { vcd_main(fname); + } + +if(indirect_fname) + { + free_2(indirect_fname); + indirect_fname=NULL; + } +if(skip_start) + { + free(skip_start); skip_start=NULL; + } +if(skip_end) + { + free(skip_end); skip_end=NULL; } for(i=0;i<26;i++) named_markers[i]=-1; /* reset all named markers */ @@ -322,11 +450,12 @@ tims.first=tims.start=tims.laststart=min_time; tims.zoom=tims.prevzoom=0; /* 1 pixel/ns default */ tims.marker=tims.lmbcache=-1; /* uninitialized at first */ +tims.baseline=-1; /* middle button toggle marker */ if((wname)||(vcd_save_handle)) { int wave_is_compressed; - char *str; + char *str = NULL; if(vcd_save_handle) { @@ -334,8 +463,8 @@ do_initial_zoom_fit=1; } - if(((strlen(wname)>2)&&(!strcmp(wname+strlen(wname)-3,".gz")))|| - ((strlen(wname)>3)&&(!strcmp(wname+strlen(wname)-4,".zip")))) + if(((strlen(wname)>2)&&(!strcasecmp(wname+strlen(wname)-3,".gz")))|| + ((strlen(wname)>3)&&(!strcasecmp(wname+strlen(wname)-4,".zip")))) { int dlen; dlen=strlen(WAVE_DECOMPRESSOR); @@ -368,7 +497,12 @@ free_2(iline); } - lx2_import_masked(); + switch(is_lx2) + { + case LXT2_IS_LXT2: lx2_import_masked(); break; + case LXT2_IS_AET2: ae2_import_masked(); break; + case LXT2_IS_VZT: vzt_import_masked(); break; + } if(wave_is_compressed) { @@ -436,6 +570,8 @@ GTK_SIGNAL_FUNC(file_quit_cmd_callback), "WM destroy"); gtk_widget_show(window); + +#if !defined __MINGW32__ && !defined _MSC_VER if((initial_window_xpos>=0)||(initial_window_ypos>=0)) { if (initial_window_xpos<0) { initial_window_xpos = 0; } @@ -446,6 +582,8 @@ gtk_window_reposition(GTK_WINDOW(window), initial_window_xpos, initial_window_ypos); #endif } +#endif + make_pixmaps(window); main_vbox = gtk_vbox_new(FALSE, 5); @@ -550,7 +688,7 @@ { int os; os=max_signal_name_pixel_width; - os=(os<30)?30:os; + os=(os<48)?48:os; gtk_widget_set_usize(GTK_WIDGET(signalwindow), os+30, -1); } @@ -587,6 +725,7 @@ update_markertime(time_trunc(tims.marker)); +#if !defined __MINGW32__ && !defined _MSC_VER if((initial_window_xpos>=0)||(initial_window_ypos>=0)) { if (initial_window_xpos<0) { initial_window_xpos = 0; } @@ -597,6 +736,7 @@ gtk_window_reposition(GTK_WINDOW(window), initial_window_xpos, initial_window_ypos); #endif } +#endif gtk_main(); diff --git a/src/markerbox.c b/src/markerbox.c index e7571a1..89d3cdc 100644 --- a/src/markerbox.c +++ b/src/markerbox.c @@ -9,6 +9,7 @@ #include #include +#include "gtk12compat.h" #include "debug.h" #include "analyzer.h" #include "currenttime.h" @@ -25,7 +26,7 @@ GtkWidget *entry; TimeType *modify; TimeType temp; -gchar *entry_text; +G_CONST_RETURN gchar *entry_text; char buf[49]; int len, i; int ent_idx; diff --git a/src/menu.c b/src/menu.c index b8f0d4e..f8e059d 100644 --- a/src/menu.c +++ b/src/menu.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2003. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -27,7 +27,7 @@ * or fireworks will result! */ enum WV_MenuItems { -#ifndef _MSC_VER +#if !defined __MINGW32__ && !defined _MSC_VER WV_MENU_FONV, WV_MENU_SEP0, #endif @@ -74,6 +74,9 @@ WV_MENU_EEX, WV_MENU_ESH, WV_MENU_SEP6A, +WV_MENU_EXA, +WV_MENU_CPA, +WV_MENU_SEP6A1, WV_MENU_EHR, WV_MENU_EUHR, WV_MENU_EHA, @@ -98,6 +101,7 @@ WV_MENU_TZZB, WV_MENU_TZZI, WV_MENU_TZZO, +WV_MENU_TZZBFL, WV_MENU_TZZBF, WV_MENU_TZZTS, WV_MENU_TZZTE, @@ -145,7 +149,7 @@ WV_MENU_HWV, }; -extern GtkItemFactoryEntry menu_items[]; +static GtkItemFactoryEntry menu_items[]; static GtkItemFactory *item_factory=NULL; static char regexp_string[129]=""; @@ -181,7 +185,7 @@ t->shift=LLDescriptor(0); found++; } - t=t->next; + t=t->t_next; } if(found) @@ -216,7 +220,7 @@ t->flags&=(~TR_HIGHLIGHT); found++; } - t=t->next; + t=t->t_next; } if(found) @@ -266,7 +270,7 @@ } t->flags&=(~TR_HIGHLIGHT); } - t=t->next; + t=t->t_next; } } @@ -305,13 +309,13 @@ found++; break; } - t=t->next; + t=t->t_next; } if(found) { reformat_time(gt, LLDescriptor(0), time_dimension); - entrybox("Warp Traces",200,gt,20,warp_cleanup); + entrybox("Warp Traces",200,gt,20,GTK_SIGNAL_FUNC(warp_cleanup)); } } @@ -527,7 +531,7 @@ } } } - t=t->next; + t=t->t_next; } } @@ -560,7 +564,7 @@ sprintf(za,"%d",hier_max_level); -entrybox("Max Hier Depth",200,za,20,max_hier_cleanup); +entrybox("Max Hier Depth",200,za,20,GTK_SIGNAL_FUNC(max_hier_cleanup)); } @@ -875,7 +879,7 @@ return; } -simplereqbox("Wave Version",300,WAVE_VERSION_INFO,"OK", NULL, NULL); +simplereqbox("Wave Version",400,WAVE_VERSION_INFO,"OK", NULL, NULL, 0); } /**/ static void menu_quit_callback(GtkWidget *widget, gpointer data) @@ -898,7 +902,7 @@ return; } -simplereqbox("Quit Program",300,"Do you really want to quit?","Yes", "No", menu_quit_callback); +simplereqbox("Quit Program",300,"Do you really want to quit?","Yes", "No", GTK_SIGNAL_FUNC(menu_quit_callback), 1); } /**/ static void must_sel(void) @@ -947,7 +951,7 @@ dirty=1; break; } - t=t->next; + t=t->t_next; } if(dirty) @@ -1015,7 +1019,7 @@ } } } - t=t->next; + t=t->t_next; } tmp=traces.buffer; traces.buffer=traces.first; traces.first=tmp; @@ -1073,7 +1077,7 @@ } } } - t=t->next; + t=t->t_next; } if(!dirty) @@ -1162,7 +1166,7 @@ } } if(nodepnt==dirty) break; - t=t->next; + t=t->t_next; } b=(struct Bits *)calloc_2(1,sizeof(struct Bits)+(nodepnt-1)* @@ -1380,7 +1384,7 @@ dirty=1; break; } - t=t->next; + t=t->t_next; } if(dirty) @@ -1424,7 +1428,7 @@ } } } - t=t->next; + t=t->t_next; } tmp=traces.buffer; traces.buffer=traces.first; traces.first=tmp; @@ -1470,12 +1474,17 @@ " \"Mark\" and \"Clear\" are used to modify the normal time" " vertical markings such that they can be used to indicate" " all the times that a specific pattern search condition is" - " true (e.g., every upclock of a specific signal)." - ); - return; - } - -for(t=traces.first;t;t=t->next) + " true (e.g., every upclock of a specific signal). The" + " \"Mark Count\" field indicates how many times the specific" + " pattern search condition was encountered." + " The \"Marking Begins at\" and \"Marking Stops at\" fields are" + " used to limit the time over which marking is applied" + " (but they have no effect on searching)." + ); + return; + } + +for(t=traces.first;t;t=t->t_next) { if ((t->flags&TR_BLANK)||(!(t->flags&TR_HIGHLIGHT))||(!(t->name))) { @@ -1483,7 +1492,7 @@ } else /* at least one good trace, so do it */ { - tracesearchbox("Waveform Display Search", menu_tracesearchbox_callback); + tracesearchbox("Waveform Display Search", GTK_SIGNAL_FUNC(menu_tracesearchbox_callback)); return; } } @@ -1492,7 +1501,7 @@ } /**/ -#ifndef _MSC_VER +#if !defined __MINGW32__ && !defined _MSC_VER static void menu_new_viewer_cleanup(GtkWidget *widget, gpointer data) @@ -1531,7 +1540,7 @@ return; } -fileselbox("Select a trace to view...",&filesel_newviewer,menu_new_viewer_cleanup); +fileselbox("Select a trace to view...",&filesel_newviewer,GTK_SIGNAL_FUNC(menu_new_viewer_cleanup), GTK_SIGNAL_FUNC(NULL)); } #endif @@ -1575,7 +1584,7 @@ return; } -markerbox("Markers", menu_markerbox_callback); +markerbox("Markers", GTK_SIGNAL_FUNC(menu_markerbox_callback)); } /**/ @@ -1596,12 +1605,12 @@ { Trptr t; - for(t=traces.first;t;t=t->next) + for(t=traces.first;t;t=t->t_next) { if(t->asciivalue) { free_2(t->asciivalue); t->asciivalue=NULL; } } - for(t=traces.buffer;t;t=t->next) + for(t=traces.buffer;t;t=t->t_next) { if(t->asciivalue) { free_2(t->asciivalue); t->asciivalue=NULL; } } @@ -1741,7 +1750,7 @@ if(dnd_state) { dnd_error(); return; } /* don't mess with sigs when dnd active */ -treebox("Signal Search Tree",menu_treesearch_cleanup); +treebox("Signal Search Tree",GTK_SIGNAL_FUNC(menu_treesearch_cleanup)); } /**/ static void @@ -1760,7 +1769,7 @@ { t->flags=flags; } - t=t->next; + t=t->t_next; } } @@ -1794,10 +1803,10 @@ { if((t->flags&TR_HIGHLIGHT)&&(!(t->flags&TR_BLANK))&&(t->name)) { - showchange("Show-Change All", showchangeall=t, menu_showchangeall_cleanup); + showchange("Show-Change All", showchangeall=t, GTK_SIGNAL_FUNC(menu_showchangeall_cleanup)); return; } - t=t->next; + t=t->t_next; } must_sel(); @@ -1838,10 +1847,10 @@ { if((t->flags&TR_HIGHLIGHT)&&(!(t->flags&TR_BLANK))&&(t->name)) { - showchange("Show-Change", t, menu_showchange_cleanup); + showchange("Show-Change", t, GTK_SIGNAL_FUNC(menu_showchange_cleanup)); return; } - t=t->next; + t=t->t_next; } must_sel(); @@ -1876,7 +1885,7 @@ if(!(t->flags&TR_BLANK)) t->name=t->n.nd->nname; else t->name=NULL; dirty=1; } - t=t->next; + t=t->t_next; } if(dirty) @@ -1972,12 +1981,12 @@ trace_to_alias=t; break; } - t=t->next; + t=t->t_next; } if(trace_to_alias) { - entrybox("Alias Highlighted Trace",300,"",128,alias_cleanup); + entrybox("Alias Highlighted Trace",300,"",128,GTK_SIGNAL_FUNC(alias_cleanup)); } else { @@ -2007,7 +2016,7 @@ if(dnd_state) { dnd_error(); return; } /* don't mess with sigs when dnd active */ -hier_searchbox("Hierarchy Search",menu_hiersearch_cleanup); +hier_searchbox("Hierarchy Search",GTK_SIGNAL_FUNC(menu_hiersearch_cleanup)); } /**/ static void menu_signalsearch_cleanup(GtkWidget *widget, gpointer data) @@ -2034,7 +2043,7 @@ if(dnd_state) { dnd_error(); return; } /* don't mess with sigs when dnd active */ -searchbox("Signal Search",menu_signalsearch_cleanup); +searchbox("Signal Search",GTK_SIGNAL_FUNC(menu_signalsearch_cleanup)); } /**/ static void @@ -2073,7 +2082,7 @@ dirty=1; } - t=t->next; + t=t->t_next; } if(dirty) @@ -2105,7 +2114,7 @@ return; } -entrybox("Regexp UnHighlight",300,regexp_string,128,regexp_unhighlight_cleanup); +entrybox("Regexp UnHighlight",300,regexp_string,128,GTK_SIGNAL_FUNC(regexp_unhighlight_cleanup)); } /**/ static void @@ -2129,7 +2138,7 @@ return; } -entrybox("Regexp Highlight",300,regexp_string,128,regexp_highlight_cleanup); +entrybox("Regexp Highlight",300,regexp_string,128,GTK_SIGNAL_FUNC(regexp_highlight_cleanup)); } /**/ static void @@ -2138,7 +2147,11 @@ FILE *wave; struct strace *st; -if(filesel_ok) +if(!filesel_ok) + { + return; + } + if(!(wave=fopen(*fileselbox_text,"wb"))) { fprintf(stderr, "Error opening save file '%s' for writing.\n",*fileselbox_text); @@ -2230,7 +2243,7 @@ if(!t->name) fprintf(wave,"-\n"); else fprintf(wave,"-%s\n",t->name); } - t=t->next; + t=t->t_next; } if(timearray) @@ -2242,7 +2255,7 @@ st=straces; if(straces) { - fprintf(wave, "!%d%d%d%d%d%d\n", logical_mutex[0], logical_mutex[1], logical_mutex[2], logical_mutex[3], logical_mutex[4], logical_mutex[5]); + fprintf(wave, "!%d%d%d%d%d%d%c%c\n", logical_mutex[0], logical_mutex[1], logical_mutex[2], logical_mutex[3], logical_mutex[4], logical_mutex[5], '@'+mark_idx_start, '@'+mark_idx_end); } while(st) @@ -2364,7 +2377,7 @@ return; } -fileselbox("Write Save File",&filesel_writesave,menu_write_save_cleanup); +fileselbox("Write Save File",&filesel_writesave,GTK_SIGNAL_FUNC(menu_write_save_cleanup), GTK_SIGNAL_FUNC(NULL)); } /**/ static void @@ -2375,7 +2388,7 @@ if(filesel_ok) { char *wname; - char *str; + char *str = NULL; int wave_is_compressed; DEBUG(printf("Read Save Fini: %s\n", *fileselbox_text)); @@ -2409,6 +2422,11 @@ char *iline; char any_shadow = 0; + if(traces.total) + { + AddBlankTrace(NULL); /* in order to terminate any possible collapsed groups */ + } + if(is_lx2) { while((iline=fgetmalloc(wave))) @@ -2495,7 +2513,7 @@ if(dnd_state) { dnd_error(); return; } /* don't mess with sigs when dnd active */ -fileselbox("Read Save File",&filesel_readsave,menu_read_save_cleanup); +fileselbox("Read Save File",&filesel_readsave,GTK_SIGNAL_FUNC(menu_read_save_cleanup), GTK_SIGNAL_FUNC(NULL)); } /**/ static void @@ -2550,7 +2568,7 @@ DEBUG(printf("Insert Comment Trace\n")); -entrybox("Insert Comment Trace",300,"",128,comment_trace_cleanup); +entrybox("Insert Comment Trace",300,"",128,GTK_SIGNAL_FUNC(comment_trace_cleanup)); } /**/ static void movetotime_cleanup(GtkWidget *widget, gpointer data) @@ -2606,7 +2624,7 @@ reformat_time(gt, tims.start, time_dimension); -entrybox("Move To Time",200,gt,20,movetotime_cleanup); +entrybox("Move To Time",200,gt,20,GTK_SIGNAL_FUNC(movetotime_cleanup)); } /**/ static void fetchsize_cleanup(GtkWidget *widget, gpointer data) @@ -2648,7 +2666,7 @@ reformat_time(fw, fetchwindow, time_dimension); -entrybox("New Fetch Size",200,fw,20,fetchsize_cleanup); +entrybox("New Fetch Size",200,fw,20,GTK_SIGNAL_FUNC(fetchsize_cleanup)); } /**/ static void zoomsize_cleanup(GtkWidget *widget, gpointer data) @@ -2701,7 +2719,7 @@ sprintf(za,"%g",(float)(tims.zoom)); -entrybox("New Zoom Amount",200,za,20,zoomsize_cleanup); +entrybox("New Zoom Amount",200,za,20,GTK_SIGNAL_FUNC(zoomsize_cleanup)); } /**/ static void zoombase_cleanup(GtkWidget *widget, gpointer data) @@ -2752,7 +2770,7 @@ sprintf(za,"%g",zoombase); -entrybox("New Zoom Base Amount",200,za,20,zoombase_cleanup); +entrybox("New Zoom Base Amount",200,za,20,GTK_SIGNAL_FUNC(zoombase_cleanup)); } /**/ static void dataformat(int mask, int patch) @@ -2769,7 +2787,7 @@ t->flags=((t->flags)&mask)|patch; fix=1; } - t=t->next; + t=t->t_next; } if(fix) { @@ -3038,7 +3056,7 @@ while(t) { t->flags|=TR_HIGHLIGHT; - t=t->next; + t=t->t_next; } signalarea_configure_event(signalarea, NULL); wavearea_configure_event(wavearea, NULL); @@ -3065,13 +3083,58 @@ while(t) { t->flags&=(~TR_HIGHLIGHT); - t=t->next; + t=t->t_next; } signalarea_configure_event(signalarea, NULL); wavearea_configure_event(wavearea, NULL); } } /**/ +static void +menu_collapse_all(GtkWidget *widget, gpointer data) +{ +if(helpbox_is_active) + { + help_text_bold("\n\nCollapse All Groups"); + help_text( + " causes all groups defined by comment traces to collapse." + " Groups are manually toggled collapsed and uncollapsed individually by holding" + " down CTRL and pressing the left mouse button on a comment" + " trace." + ); + return; + } + +CollapseAllGroups(); +signalwindow_width_dirty=1; +MaxSignalLength(); +signalarea_configure_event(signalarea, NULL); +wavearea_configure_event(wavearea, NULL); +} + +static void +menu_expand_all(GtkWidget *widget, gpointer data) +{ +if(helpbox_is_active) + { + help_text_bold("\n\nExpand All Groups"); + help_text( + " causes all groups defined by comment traces to expand." + " Groups are manually toggled collapsed and uncollapsed individually by holding" + " down CTRL and pressing the left mouse button on a comment" + " trace." + ); + return; + } + +ExpandAllGroups(); +signalwindow_width_dirty=1; +MaxSignalLength(); +signalarea_configure_event(signalarea, NULL); +wavearea_configure_event(wavearea, NULL); +} +/**/ + static void menu_lexize(GtkWidget *widget, gpointer data) { Trptr t; @@ -3323,7 +3386,7 @@ static GtkItemFactoryEntry menu_items[] = { -#ifndef _MSC_VER +#if !defined __MINGW32__ && !defined _MSC_VER WAVE_GTKIFE("/File/Open New Viewer", "Pause", menu_new_viewer, WV_MENU_FONV, ""), WAVE_GTKIFE("/File/", NULL, NULL, WV_MENU_SEP0, ""), #endif @@ -3371,6 +3434,9 @@ WAVE_GTKIFE("/Edit/Exclude", "E", menu_dataformat_exclude_on, WV_MENU_EEX, ""), WAVE_GTKIFE("/Edit/Show", "S", menu_dataformat_exclude_off, WV_MENU_ESH, ""), WAVE_GTKIFE("/Edit/", NULL, NULL, WV_MENU_SEP6A, ""), + WAVE_GTKIFE("/Edit/Expand All Groups", "F12", menu_expand_all, WV_MENU_EXA, ""), + WAVE_GTKIFE("/Edit/Collapse All Groups", "F12", menu_collapse_all, WV_MENU_CPA, ""), + WAVE_GTKIFE("/Edit/", NULL, NULL, WV_MENU_SEP6A1, ""), WAVE_GTKIFE("/Edit/Highlight Regexp", "R", menu_regexp_highlight, WV_MENU_EHR, ""), WAVE_GTKIFE("/Edit/UnHighlight Regexp", "R", menu_regexp_unhighlight, WV_MENU_EUHR, ""), WAVE_GTKIFE("/Edit/Highlight All", "H", menu_dataformat_highlight_all, WV_MENU_EHA, ""), @@ -3397,7 +3463,8 @@ WAVE_GTKIFE("/Time/Zoom/Zoom Base", "F2", menu_zoombase, WV_MENU_TZZB, ""), WAVE_GTKIFE("/Time/Zoom/Zoom In", "Z", service_zoom_in, WV_MENU_TZZI, ""), WAVE_GTKIFE("/Time/Zoom/Zoom Out", "Z", service_zoom_out, WV_MENU_TZZO, ""), - WAVE_GTKIFE("/Time/Zoom/Zoom Best Fit", "F", service_zoom_fit, WV_MENU_TZZBF, ""), + WAVE_GTKIFE("/Time/Zoom/Zoom Full", "F", service_zoom_full, WV_MENU_TZZBFL, ""), + WAVE_GTKIFE("/Time/Zoom/Zoom Best Fit", "F", service_zoom_fit, WV_MENU_TZZBF, ""), WAVE_GTKIFE("/Time/Zoom/Zoom To Start", "Home", service_zoom_left, WV_MENU_TZZTS, ""), WAVE_GTKIFE("/Time/Zoom/Zoom To End", "End", service_zoom_right, WV_MENU_TZZTE, ""), WAVE_GTKIFE("/Time/Zoom/Undo Zoom", "U", service_zoom_undo, WV_MENU_TZUZ, ""), @@ -3504,7 +3571,6 @@ { int nmenu_items = sizeof(menu_items) / sizeof(menu_items[0]); GtkAccelGroup *global_accel; - int i; global_accel = gtk_accel_group_new(); item_factory = gtk_item_factory_new(GTK_TYPE_MENU_BAR, "
    ", global_accel); diff --git a/src/pagebuttons.c b/src/pagebuttons.c index 8908527..d1d5823 100644 --- a/src/pagebuttons.c +++ b/src/pagebuttons.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -24,6 +24,9 @@ help_text( " scrolls the display window left one page worth of data." " The net action is that the data scrolls right a page." +#ifdef WAVE_USE_GTK2 + " Scrollwheel Up also performs this function." +#endif ); return; } @@ -52,6 +55,9 @@ help_text( " scrolls the display window right one page worth of data." " The net action is that the data scrolls left a page." +#ifdef WAVE_USE_GTK2 + " Scrollwheel Down also performs this function." +#endif ); return; } @@ -94,9 +100,9 @@ tooltips=gtk_tooltips_new_2(); gtk_tooltips_set_delay_2(tooltips,1500); -pixmapwid1=gtk_pixmap_new(larrow_pixmap, larrow_mask); +pixmapwid1=gtk_pixmap_new(prev_page_pixmap, prev_page_mask); gtk_widget_show(pixmapwid1); -pixmapwid2=gtk_pixmap_new(rarrow_pixmap, rarrow_mask); +pixmapwid2=gtk_pixmap_new(next_page_pixmap, next_page_mask); gtk_widget_show(pixmapwid2); /* Create a table to hold the text widget and scrollbars */ diff --git a/src/pixmaps.c b/src/pixmaps.c index 67158f5..e69c31d 100644 --- a/src/pixmaps.c +++ b/src/pixmaps.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -10,205 +10,2767 @@ #include "pixmaps.h" /* XPM */ -static char *icon_larrow[] = { -/* width height num_colors chars_per_pixel */ -" 21 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -"#########.###########", -"#######...###########", -"#####.....###########", -"###.......###########", -"#.........###########", -".....................", -"#.........###########", -"###.......###########", -"#####.....###########", -"#######...###########", -"#########.###########" -}; +static char * icon_larrow[] = { +"24 24 43 1", +" c None", +". c #000000", +"+ c #B9D0B9", +"@ c #CDDECB", +"# c #B6C7B6", +"$ c #B1C9B0", +"% c #B3C4B3", +"& c #B4CBB2", +"* c #B5CEB5", +"= c #B7CCB5", +"- c #B9CEB7", +"; c #BAD1BA", +"> c #BBCFBA", +", c #BBD0B9", +"' c #B2C9B0", +") c #7EAB78", +"! c #AAC7A8", +"~ c #B3CAB1", +"{ c #B0C9B0", +"] c #B0C9AE", +"^ c #AEC7AC", +"/ c #AAC5A8", +"( c #A9C4A7", +"_ c #698267", +": c #2D2D2D", +"< c #CFDFCC", +"[ c #ADC8AB", +"} c #B0C7AE", +"| c #ADC6AB", +"1 c #678C63", +"2 c #9BAD9A", +"3 c #85AE81", +"4 c #87AF84", +"5 c #87B083", +"6 c #88AF84", +"7 c #88B085", +"8 c #86AF82", +"9 c #547150", +"0 c #3C5235", +"a c #5B7950", +"b c #4A6342", +"c c #3B5035", +"d c #415639", +" ", +" ", +" ", +" . ", +" .. ", +" .+. ", +" .@#. ", +" .@$%........ ", +" .@&*=-;->,'). ", +" .@!~{]^///^(_. ", +" :<[}||[!^^}^[1. ", +" .23444445645789. ", +" .0aaaaaaaaaaab. ", +" .0aaaaaaaaaab. ", +" .0aabccccccd. ", +" .0ab........ ", +" .0b. ", +" .b. ", +" .. ", +" . ", +" ", +" ", +" ", +" "}; GdkPixmap *larrow_pixmap; GdkBitmap *larrow_mask; /* XPM */ -static char *icon_rarrow[] = { -/* width height num_colors chars_per_pixel */ -" 21 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -"###########.#########", -"###########...#######", -"###########.....#####", -"###########.......###", -"###########.........#", -".....................", -"###########.........#", -"###########.......###", -"###########.....#####", -"###########...#######", -"###########.#########" -}; +static char * icon_rarrow[] = { +"24 24 41 1", +" c None", +". c #000000", +"+ c #8CA782", +"@ c #B1CDAE", +"# c #77A16E", +"$ c #B4CEB1", +"% c #ACC8A9", +"& c #709867", +"* c #C1D6BD", +"= c #BDD3B8", +"- c #BFD4BB", +"; c #C2D7BE", +"> c #B0CAAD", +", c #B2CBB0", +"' c #AAC7A8", +") c #0F1308", +"! c #AEC5A8", +"~ c #AEC8AD", +"{ c #ABC7A8", +"] c #AAC6A7", +"^ c #A8C6A5", +"/ c #ADC8AD", +"( c #A8C7A8", +"_ c #A5C4A3", +": c #7F9F76", +"< c #A6BFA0", +"[ c #ABC7AA", +"} c #A7C5A4", +"| c #A9C7A6", +"1 c #AFC8AD", +"2 c #A4C3A2", +"3 c #6B9060", +"4 c #778E6F", +"5 c #698D60", +"6 c #6B9063", +"7 c #445B2C", +"8 c #6B8661", +"9 c #5B7950", +"0 c #6C8562", +"a c #65815C", +"b c #506B46", +" ", +" ", +" ", +" . ", +" .. ", +" .+. ", +" .@#. ", +" ........$%&. ", +" .*=-;;;;>,'&) ", +" .!~{{{]^'/(_:. ", +" .<[^}^|{%'{123. ", +" .45666666666657. ", +" .8999999999997. ", +" .099999999997. ", +" .abbbbbb9997. ", +" ........b97. ", +" .b7. ", +" .7. ", +" .. ", +" . ", +" ", +" ", +" ", +" "}; + GdkPixmap *rarrow_pixmap; GdkBitmap *rarrow_mask; /* XPM */ -static char *icon_zoomout[] = { -/* width height num_colors chars_per_pixel */ -" 27 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -"#########.#######.#########", -"#######...#######...#######", -"#####.....#######.....#####", -"###.......#######.......###", -"#.........#######.........#", -"...........................", -"#.........#######.........#", -"###.......#######.......###", -"#####.....#######.....#####", -"#######...#######...#######", -"#########.#######.#########" -}; +static char * icon_zoomin[] = { +"24 24 131 2", +" c None", +". c #343434", +"+ c #2D2D2D", +"@ c #292929", +"# c #262626", +"$ c #2E2E2E", +"% c #303030", +"& c #737373", +"* c #A1A1A1", +"= c #B4B4B4", +"- c #B2B2B2", +"; c #9D9D9D", +"> c #676767", +", c #202020", +"' c #1C1C1C", +") c #272727", +"! c #616161", +"~ c #CACACA", +"{ c #CFCFCF", +"] c #D0D0D0", +"^ c #CECECE", +"/ c #C9C9C9", +"( c #C1C1C1", +"_ c #A7A7A7", +": c #4C4C4C", +"< c #131313", +"[ c #222222", +"} c #757575", +"| c #D3D3D3", +"1 c #DBDBDB", +"2 c #E7E7E7", +"3 c #EFEFEF", +"4 c #F3F3F3", +"5 c #F1F1F1", +"6 c #E5E5E5", +"7 c #D2D2D2", +"8 c #BCBCBC", +"9 c #5E5E5E", +"0 c #101010", +"a c #212121", +"b c #5B5B5B", +"c c #CCCCCC", +"d c #D7D7D7", +"e c #F5F5F5", +"f c #FAFAFA", +"g c #FBFBFB", +"h c #F8F8F8", +"i c #F0F0F0", +"j c #E1E1E1", +"k c #C2C2C2", +"l c #434343", +"m c #0F0F0F", +"n c #1F1F1F", +"o c #B9B9B9", +"p c #D6D6D6", +"q c #F9F9F9", +"r c #FDFDFD", +"s c #FCFCFC", +"t c #F2F2F2", +"u c #ECECEC", +"v c #E4E4E4", +"w c #ABABAB", +"x c #0E0E0E", +"y c #1B1B1B", +"z c #6D6D6D", +"A c #FEFEFE", +"B c #EEEEEE", +"C c #E6E6E6", +"D c #575757", +"E c #090909", +"F c #141414", +"G c #A8A8A8", +"H c #D8D8D8", +"I c #F6F6F6", +"J c #F4F4F4", +"K c #DCDCDC", +"L c #9B9B9B", +"M c #060606", +"N c #111111", +"O c #C5C5C5", +"P c #DFDFDF", +"Q c #444444", +"R c #454545", +"S c #424242", +"T c #EDEDED", +"U c #BFBFBF", +"V c #C6C6C6", +"W c #E3E3E3", +"X c #414141", +"Y c #EAEAEA", +"Z c #E0E0E0", +"` c #BABABA", +" . c #050505", +".. c #0B0B0B", +"+. c #A5A5A5", +"@. c #D1D1D1", +"#. c #939393", +"$. c #020202", +"%. c #0A0A0A", +"&. c #5F5F5F", +"*. c #D9D9D9", +"=. c #EBEBEB", +"-. c #E9E9E9", +";. c #D4D4D4", +">. c #000000", +",. c #E2E2E2", +"'. c #DADADA", +"). c #CBCBCB", +"!. c #3B3B3B", +"~. c #D5D5D5", +"{. c #C8C8C8", +"]. c #BDBDBD", +"^. c #515151", +"/. c #C7C7C7", +"(. c #CDCDCD", +"_. c #B8B8B8", +":. c #030303", +"<. c #313131", +"[. c #999999", +"}. c #BBBBBB", +"|. c #B6B6B6", +"1. c #909090", +"2. c #2B2B2B", +"3. c #010101", +"4. c #7A7A7A", +"5. c #9A9A9A", +"6. c #777777", +"7. c #3C3C3C", +"8. c #686868", +"9. c #797979", +"0. c #3A3A3A", +" ", +" . + @ # # # ", +" $ % & * = - ; > , ' ", +" ) ! = ~ { ] ^ / ( _ : < ", +" [ } ~ | 1 2 3 4 5 6 7 8 9 0 ", +" a b c d 6 e f g f h e i j k l m ", +" n o p 2 q g r r s g h t u v w x ", +" y z 7 j e f r A A r s q e B C 1 D E ", +" F G H B I q s A A r g h J B C K L M ", +" N O P 3 e Q Q R R R Q l S T 6 1 U M ", +" x V W u t l Q Q Q Q l S X Y Z d ` . ", +" ..+.j 2 T 5 J I I e 4 3 u v 1 @.#.$. ", +" %.&.*.j C =.B 3 3 B T -.v 1 ;.~ : >. ", +" %.= H K ,.6 C C 2 W P '.;.).* $. ", +" M !.c 7 ;.'.1 '.1 H ~.] {.].$ >. ", +" .^.k /.).c (.).).{.k _.R >. ", +" :.<.[.}.].8 8 8 |.1.2.>.>.>. ", +" 3.:.X 4.5.5.6.7.>.>. >.>.>.>. ", +" >.>.>.>.>.>. , , >.>. ", +" >.8.. >.>. ", +" >.9.0.>.>. ", +" >.8.n >. ", +" >.>. ", +" "}; + +GdkPixmap *zoomin_pixmap; +GdkBitmap *zoomin_mask; + + +/* XPM */ +static char * icon_zoomout[] = { +"24 24 132 2", +" c None", +". c #343434", +"+ c #2D2D2D", +"@ c #292929", +"# c #262626", +"$ c #2E2E2E", +"% c #303030", +"& c #737373", +"* c #A1A1A1", +"= c #B4B4B4", +"- c #B2B2B2", +"; c #9D9D9D", +"> c #676767", +", c #202020", +"' c #1C1C1C", +") c #272727", +"! c #616161", +"~ c #CACACA", +"{ c #CFCFCF", +"] c #D0D0D0", +"^ c #CECECE", +"/ c #C9C9C9", +"( c #C1C1C1", +"_ c #A7A7A7", +": c #4C4C4C", +"< c #131313", +"[ c #222222", +"} c #757575", +"| c #D3D3D3", +"1 c #DBDBDB", +"2 c #E7E7E7", +"3 c #EFEFEF", +"4 c #F3F3F3", +"5 c #F1F1F1", +"6 c #E5E5E5", +"7 c #D2D2D2", +"8 c #BCBCBC", +"9 c #5E5E5E", +"0 c #101010", +"a c #212121", +"b c #5B5B5B", +"c c #CCCCCC", +"d c #D7D7D7", +"e c #F5F5F5", +"f c #FAFAFA", +"g c #FBFBFB", +"h c #F8F8F8", +"i c #F0F0F0", +"j c #E1E1E1", +"k c #C2C2C2", +"l c #434343", +"m c #0F0F0F", +"n c #1F1F1F", +"o c #B9B9B9", +"p c #D6D6D6", +"q c #F9F9F9", +"r c #FDFDFD", +"s c #454545", +"t c #F2F2F2", +"u c #ECECEC", +"v c #E4E4E4", +"w c #ABABAB", +"x c #0E0E0E", +"y c #1B1B1B", +"z c #6D6D6D", +"A c #FEFEFE", +"B c #FCFCFC", +"C c #EEEEEE", +"D c #E6E6E6", +"E c #575757", +"F c #090909", +"G c #141414", +"H c #A8A8A8", +"I c #D8D8D8", +"J c #F6F6F6", +"K c #F4F4F4", +"L c #DCDCDC", +"M c #9B9B9B", +"N c #060606", +"O c #111111", +"P c #C5C5C5", +"Q c #DFDFDF", +"R c #444444", +"S c #424242", +"T c #EDEDED", +"U c #BFBFBF", +"V c #C6C6C6", +"W c #E3E3E3", +"X c #414141", +"Y c #EAEAEA", +"Z c #E0E0E0", +"` c #BABABA", +" . c #050505", +".. c #0B0B0B", +"+. c #A5A5A5", +"@. c #D1D1D1", +"#. c #939393", +"$. c #020202", +"%. c #0A0A0A", +"&. c #5F5F5F", +"*. c #D9D9D9", +"=. c #EBEBEB", +"-. c #E9E9E9", +";. c #D4D4D4", +">. c #000000", +",. c #E2E2E2", +"'. c #3F3F3F", +"). c #DADADA", +"!. c #CBCBCB", +"~. c #3B3B3B", +"{. c #D5D5D5", +"]. c #C8C8C8", +"^. c #BDBDBD", +"/. c #515151", +"(. c #C7C7C7", +"_. c #CDCDCD", +":. c #B8B8B8", +"<. c #030303", +"[. c #313131", +"}. c #999999", +"|. c #BBBBBB", +"1. c #B6B6B6", +"2. c #909090", +"3. c #2B2B2B", +"4. c #010101", +"5. c #7A7A7A", +"6. c #9A9A9A", +"7. c #777777", +"8. c #3C3C3C", +"9. c #686868", +"0. c #797979", +"a. c #3A3A3A", +" ", +" . + @ # # # ", +" $ % & * = - ; > , ' ", +" ) ! = ~ { ] ^ / ( _ : < ", +" [ } ~ | 1 2 3 4 5 6 7 8 9 0 ", +" a b c d 6 e f g f h e i j k l m ", +" n o p 2 q g r s s g h t u v w x ", +" y z 7 j e f r A s s B q e C D 1 E F ", +" G H I C J q B A s s g h K C D L M N ", +" O P Q 3 e R R s s s R l S T 6 1 U N ", +" x V W u t l R R R R l S X Y Z d ` . ", +" ..+.j 2 T 5 K J l l 4 3 u v 1 @.#.$. ", +" %.&.*.j D =.C 3 X X T -.v 1 ;.~ : >. ", +" %.= I L ,.6 D '.'.W Q ).;.!.* $. ", +" N ~.c 7 ;.).1 ).1 I {.] ].^.$ >. ", +" ./.k (.!.c _.!.!.].k :.s >. ", +" <.[.}.|.^.8 8 8 1.2.3.>.>.>. ", +" 4.<.X 5.6.6.7.8.>.>. >.>.>.>. ", +" >.>.>.>.>.>. , , >.>. ", +" >.9.. >.>. ", +" >.0.a.>.>. ", +" >.9.n >. ", +" >.>. ", +" "}; GdkPixmap *zoomout_pixmap; GdkBitmap *zoomout_mask; /* XPM */ -static char *icon_zoomin[] = { -/* width height num_colors chars_per_pixel */ -" 27 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -"###.###################.###", -"###...###############...###", -"###.....###########.....###", -"###.......#######.......###", -"###.........###.........###", -"...........................", -"###.........###.........###", -"###.......#######.......###", -"###.....###########.....###", -"###...###############...###", -"###.###################.###" -}; - -GdkPixmap *zoomin_pixmap; -GdkBitmap *zoomin_mask; - - -/* XPM */ -static char *icon_zoomfit[] = { -/* width height num_colors chars_per_pixel */ -" 27 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -".########.#######.########.", -".######...#######...######.", -".####.....#######.....####.", -".##.......#######.......##.", -"..........#######..........", -"...........................", -"..........#######..........", -".##.......#######.......##.", -".####.....#######.....####.", -".######...#######...######.", -".########.#######.########." -}; +static char * icon_zoomfit[] = { +"24 24 140 2", +" c None", +". c #343434", +"+ c #2D2D2D", +"@ c #292929", +"# c #262626", +"$ c #2E2E2E", +"% c #303030", +"& c #737373", +"* c #A1A1A1", +"= c #B4B4B4", +"- c #B2B2B2", +"; c #9D9D9D", +"> c #676767", +", c #202020", +"' c #1C1C1C", +") c #272727", +"! c #616161", +"~ c #CACACA", +"{ c #CFCFCF", +"] c #D0D0D0", +"^ c #CECECE", +"/ c #C9C9C9", +"( c #C1C1C1", +"_ c #A7A7A7", +": c #4C4C4C", +"< c #131313", +"[ c #222222", +"} c #757575", +"| c #D3D3D3", +"1 c #DBDBDB", +"2 c #E7E7E7", +"3 c #EFEFEF", +"4 c #F3F3F3", +"5 c #F1F1F1", +"6 c #E5E5E5", +"7 c #D2D2D2", +"8 c #BCBCBC", +"9 c #5E5E5E", +"0 c #101010", +"a c #212121", +"b c #5B5B5B", +"c c #CCCCCC", +"d c #464646", +"e c #4B4B4B", +"f c #505050", +"g c #525252", +"h c #FBFBFB", +"i c #FAFAFA", +"j c #515151", +"k c #4F4F4F", +"l c #4A4A4A", +"m c #C2C2C2", +"n c #434343", +"o c #0F0F0F", +"p c #1F1F1F", +"q c #B9B9B9", +"r c #D6D6D6", +"s c #535353", +"t c #FDFDFD", +"u c #FCFCFC", +"v c #4D4D4D", +"w c #E4E4E4", +"x c #ABABAB", +"y c #0E0E0E", +"z c #1B1B1B", +"A c #6D6D6D", +"B c #E1E1E1", +"C c #FEFEFE", +"D c #F9F9F9", +"E c #4E4E4E", +"F c #E6E6E6", +"G c #575757", +"H c #090909", +"I c #141414", +"J c #A8A8A8", +"K c #D8D8D8", +"L c #EEEEEE", +"M c #F8F8F8", +"N c #DCDCDC", +"O c #9B9B9B", +"P c #060606", +"Q c #111111", +"R c #C5C5C5", +"S c #DFDFDF", +"T c #F5F5F5", +"U c #F7F7F7", +"V c #F2F2F2", +"W c #EDEDED", +"X c #BFBFBF", +"Y c #C6C6C6", +"Z c #E3E3E3", +"` c #ECECEC", +" . c #F4F4F4", +".. c #F0F0F0", +"+. c #EAEAEA", +"@. c #E0E0E0", +"#. c #D7D7D7", +"$. c #BABABA", +"%. c #050505", +"&. c #0B0B0B", +"*. c #A5A5A5", +"=. c #F6F6F6", +"-. c #D1D1D1", +";. c #939393", +">. c #020202", +",. c #0A0A0A", +"'. c #5F5F5F", +"). c #D9D9D9", +"!. c #E9E9E9", +"~. c #484848", +"{. c #D4D4D4", +"]. c #000000", +"^. c #494949", +"/. c #474747", +"(. c #454545", +"_. c #CBCBCB", +":. c #3B3B3B", +"<. c #DADADA", +"[. c #444444", +"}. c #414141", +"|. c #BDBDBD", +"1. c #C7C7C7", +"2. c #CDCDCD", +"3. c #C8C8C8", +"4. c #B8B8B8", +"5. c #030303", +"6. c #313131", +"7. c #999999", +"8. c #BBBBBB", +"9. c #B6B6B6", +"0. c #909090", +"a. c #2B2B2B", +"b. c #010101", +"c. c #7A7A7A", +"d. c #9A9A9A", +"e. c #777777", +"f. c #3C3C3C", +"g. c #686868", +"h. c #797979", +"i. c #3A3A3A", +" ", +" . + @ # # # ", +" $ % & * = - ; > , ' ", +" ) ! = ~ { ] ^ / ( _ : < ", +" [ } ~ | 1 2 3 4 5 6 7 8 9 0 ", +" a b c d e f g h i j f k l m n o ", +" p q r : g g s t u g j k v w x y ", +" z A 7 B f g t C C t u D f E F 1 G H ", +" I J K L j g u C C t h M f E F N O P ", +" Q R S 3 T M h t t u i U V W 6 1 X P ", +" y Y Z ` V T M i i i U ...+.@.#.$.%. ", +" &.*.B 2 E k .=.=.T 4 3 v e 1 -.;.>. ", +" ,.'.).B e v L 3 3 L W !.e ~.{.~ : ]. ", +" ,.= K ~.l e e F 2 l ^./.(._.* >. ", +" P :.c (.(./.~.<.1 /.d [.}.|.$ ]. ", +" %.j m 1._.c 2._._.3.m 4.(.]. ", +" 5.6.7.8.|.8 8 8 9.0.a.].].]. ", +" b.5.}.c.d.d.e.f.].]. ].].].]. ", +" ].].].].].]. , , ].]. ", +" ].g.. ].]. ", +" ].h.i.].]. ", +" ].g.p ]. ", +" ].]. ", +" "}; GdkPixmap *zoomfit_pixmap; GdkBitmap *zoomfit_mask; /* XPM */ -static char *icon_zoomundo[] = { -/* width height num_colors chars_per_pixel */ -" 27 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -"..##..#..##..#.....###....#", -"..##..#..##..#..##..#..##..", -"..##..#..##..#..##..#..##..", -"..##..#...#..#..##..#..##..", -"..##..#......#..##..#..##..", -"..##..#......#..##..#..##..", -"..##..#..#...#..##..#..##..", -"..##..#..##..#..##..#..##..", -"..##..#..##..#..##..#..##..", -"..##..#..##..#..##..#..##..", -"#....##..##..#.....###....#" -}; +static char * icon_zoomundo[] = { +"24 24 31 1", +" c None", +". c #000000", +"+ c #EFE5BA", +"@ c #EFE7C1", +"# c #EED680", +"$ c #EFE4B6", +"% c #D5B75D", +"& c #B29544", +"* c #D1B051", +"= c #C0AF73", +"- c #C0A048", +"; c #986B07", +"> c #D1940C", +", c #E0B74C", +"' c #D9C374", +") c #8F6406", +"! c #D59D1C", +"~ c #B1933F", +"{ c #DFB74A", +"] c #CCB76D", +"^ c #B8820A", +"/ c #D9A72E", +"( c #D7A62C", +"_ c #C7B26A", +": c #D4B150", +"< c #A39256", +"[ c #E2CB79", +"} c #C9B46B", +"| c #8D7E4A", +"1 c #AE9C5C", +"2 c #96864F", +" ", +" ", +" ", +" . ", +" .. ", +" .+. ", +" .@#.... ", +" .$####%&. ", +" .+#######*. ", +" .=#########-. ", +" .;>>>>>>,#'.. ", +" .)>>>>>>!#~. ", +" .)>...;>{]. ", +" .;. ..^/#. ", +" .. ..>#. ", +" . .(_. ", +" .:<. ", +" .[. ", +" .}|. ", +" .12. ", +" .. ", +" ", +" ", +" "}; GdkPixmap *zoomundo_pixmap; GdkBitmap *zoomundo_mask; /* XPM */ -static char *zoom_larrow[] = { -/* width height num_colors chars_per_pixel */ -" 27 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -"#.#########.###############", -"#.#######...###############", -"#.#####.....###############", -"#.###.......###############", -"#.#.........###############", -"#.......................###", -"#.#.........###############", -"#.###.......###############", -"#.#####.....###############", -"#.#######...###############", -"#.#########.###############" -}; +static char * zoom_larrow[] = { +"24 24 57 1", +" c None", +". c #000000", +"+ c #F7F7F7", +"@ c #CBD6CA", +"# c #E7EFE7", +"$ c #ACC8A9", +"% c #C9DBC9", +"& c #E6EEE5", +"* c #BFCEBF", +"= c #E7EFE6", +"- c #BBCFBA", +"; c #B3C4B3", +"> c #E6EEE6", +", c #B9CEB7", +"' c #B5CEB5", +") c #B7CCB5", +"! c #BFD4BF", +"~ c #C7D7C5", +"{ c #DBE5DB", +"] c #DAE5D9", +"^ c #CBDAC9", +"/ c #7EAB78", +"( c #BAD1B9", +"_ c #B3CAB1", +": c #B0C9B0", +"< c #B0C9AE", +"[ c #AEC7AC", +"} c #AAC5A8", +"| c #A9C4A7", +"1 c #698267", +"2 c #E4ECE3", +"3 c #2D2D2D", +"4 c #E0EADE", +"5 c #B3CCB1", +"6 c #B0C7AE", +"7 c #ADC6AB", +"8 c #ADC8AB", +"9 c #AAC7A8", +"0 c #678C63", +"a c #9FB79B", +"b c #6B9063", +"c c #C2CDC2", +"d c #8EB48A", +"e c #87AF84", +"f c #87B083", +"g c #88AF84", +"h c #88B085", +"i c #86AF82", +"j c #547150", +"k c #95A88F", +"l c #5B7950", +"m c #3C5235", +"n c #4A6342", +"o c #3B5035", +"p c #415639", +"q c #889D7F", +"r c #475E3E", +" ", +" ", +" ", +" .... . ", +" .+@. .. ", +" .#$. .%. ", +" .#$. .&*. ", +" .#$. .=-;........ ", +" .#$. .>,'),!~{]^/. ", +" .#$. .>(_:<[}}}[|1. ", +" .2$. 34567789[[6[80. ", +" .ab..cdeeeeefgefhij. ", +" .kl. .mllllllllllln. ", +" .kl. .mlllllllllln. ", +" .kl. .mllnoooooop. ", +" .kl. .mln........ ", +" .kl. .mn. ", +" .kl. .n. ", +" .qr. .. ", +" .... . ", +" ", +" ", +" ", +" "}; GdkPixmap *zoom_larrow_pixmap; GdkBitmap *zoom_larrow_mask; /* XPM */ -static char *zoom_rarrow[] = { -/* width height num_colors chars_per_pixel */ -" 27 11 2 1", -/* colors */ -". c #000000", -"# c None", -/* pixels */ -"###############.#########.#", -"###############...#######.#", -"###############.....#####.#", -"###############.......###.#", -"###############.........#.#", -"###.......................#", -"###############.........#.#", -"###############.......###.#", -"###############.....#####.#", -"###############...#######.#", -"###############.#########.#" -}; +static char * zoom_rarrow[] = { +"24 24 52 1", +" c None", +". c #000000", +"+ c #F7F7F7", +"@ c #CBD6CA", +"# c #BECEBA", +"$ c #E7EFE7", +"% c #ACC8A9", +"& c #EBF2EA", +"* c #77A16E", +"= c #E3EBE2", +"- c #709867", +"; c #F8F8F7", +"> c #F1F5F0", +", c #ECF2EB", +"' c #E5EEE3", +") c #E0EBDF", +"! c #D8E6D6", +"~ c #C6D9C2", +"{ c #C5D7C3", +"] c #B2CBB0", +"^ c #AAC7A8", +"/ c #0F1308", +"( c #DDE6DB", +"_ c #AEC8AD", +": c #ABC7A8", +"< c #AAC6A7", +"[ c #A8C6A5", +"} c #ADC8AD", +"| c #A8C7A8", +"1 c #A5C4A3", +"2 c #7F9F76", +"3 c #D6E1D4", +"4 c #ABC7AA", +"5 c #A7C5A4", +"6 c #A9C7A6", +"7 c #AFC8AD", +"8 c #A4C3A2", +"9 c #6B9060", +"0 c #E4ECE3", +"a c #A7B6A2", +"b c #698D60", +"c c #6B9063", +"d c #445B2C", +"e c #9FB79B", +"f c #9FB199", +"g c #5B7950", +"h c #95A88F", +"i c #9FAF99", +"j c #789171", +"k c #506B46", +"l c #889D7F", +"m c #475E3E", +" ", +" ", +" ", +" . .... ", +" .. .+@. ", +" .#. .$%. ", +" .&*. .$%. ", +" ........=%-. .$%. ", +" .;>,')!~{]^-/ .$%. ", +" .(_:::<[^}|12. .$%. ", +" .34[5[6:%^:789. .0%. ", +" .abccccccccccbd..ec. ", +" .fgggggggggggd. .hg. ", +" .iggggggggggd. .hg. ", +" .jkkkkkkgggd. .hg. ", +" ........kgd. .hg. ", +" .kd. .hg. ", +" .d. .hg. ", +" .. .lm. ", +" . .... ", +" ", +" ", +" ", +" "}; GdkPixmap *zoom_rarrow_pixmap; GdkBitmap *zoom_rarrow_mask; +/* XPM */ +static char * prev_page_xpm[] = { +"24 24 170 2", +" c None", +". c #000000", +"+ c #040506", +"@ c #0B0F12", +"# c #959FAA", +"$ c #C3C6CA", +"% c #82909E", +"& c #F1F1F1", +"* c #D5D7D8", +"= c #0A0D10", +"- c #11171C", +"; c #8693A0", +"> c #EFF0F0", +", c #DEDEDE", +"' c #D5D5D5", +") c #9B9FA4", +"! c #0E1317", +"~ c #85929F", +"{ c #DBDBDB", +"] c #CACACA", +"^ c #C8C8C8", +"/ c #C8C9CA", +"( c #0C0F13", +"_ c #141A20", +": c #798895", +"< c #D2D2D2", +"[ c #C3C3C3", +"} c #CDCDCD", +"| c #74797E", +"1 c #171F26", +"2 c #7F8D9A", +"3 c #DADADA", +"4 c #D3D3D3", +"5 c #C4C4C4", +"6 c #CECECE", +"7 c #C0C0C0", +"8 c #B1B1B1", +"9 c #0D1115", +"0 c #768592", +"a c #EEEFEF", +"b c #D9D9D9", +"c c #D0D0D0", +"d c #C2C2C2", +"e c #CBCBCB", +"f c #C9C9C9", +"g c #BCBCBC", +"h c #A4A7A9", +"i c #686B6C", +"j c #333333", +"k c #414F5D", +"l c #ADB5BC", +"m c #EAEAEA", +"n c #BFBFBF", +"o c #BDBDBD", +"p c #C6C6C6", +"q c #B5B6B7", +"r c #899096", +"s c #B8B8B8", +"t c #FFFFFF", +"u c #404142", +"v c #4D6074", +"w c #EBEBEB", +"x c #D1D1D1", +"y c #C1C1C1", +"z c #B7B7B7", +"A c #979FA7", +"B c #A1A3A4", +"C c #FCFDFD", +"D c #F3F4F4", +"E c #EBECED", +"F c #EAEBEC", +"G c #E9EAEB", +"H c #EEEFF1", +"I c #F6F7F8", +"J c #E4E5E6", +"K c #929395", +"L c #32414F", +"M c #8C98A2", +"N c #E7E7E7", +"O c #BBBBBB", +"P c #A4A7AB", +"Q c #939699", +"R c #D7D8D8", +"S c #FAFCFC", +"T c #F9FAFB", +"U c #F8F9FA", +"V c #F7F8F9", +"W c #F5F6F8", +"X c #F7F7F9", +"Y c #C6C7C7", +"Z c #4F5E6A", +"` c #4C5F72", +" . c #E8E8E8", +".. c #BEBEBE", +"+. c #1F1F1F", +"@. c #B5B5B6", +"#. c #979EA4", +"$. c #A8A8A8", +"%. c #FDFEFE", +"&. c #F5F6F6", +"*. c #E7E9E9", +"=. c #F0F1F2", +"-. c #E0E2E3", +";. c #8F969D", +">. c #151C22", +",. c #354453", +"'. c #8D99A2", +"). c #E3E3E3", +"!. c #8E949A", +"~. c #9D9F9F", +"{. c #F2F3F4", +"]. c #F1F2F3", +"^. c #F6F6F7", +"/. c #A6A8AB", +"(. c #737F8A", +"_. c #4B5F71", +":. c #CDDECB", +"<. c #97999B", +"[. c #E7E8E8", +"}. c #F4F5F5", +"|. c #FBFBFB", +"1. c #D8D8DA", +"2. c #939BA3", +"3. c #0F1418", +"4. c #B1C9B0", +"5. c #E6E7E8", +"6. c #FAFAFB", +"7. c #F5F5F7", +"8. c #AEB2B6", +"9. c #5C6C7C", +"0. c #B4CBB2", +"a. c #B5CEB5", +"b. c #B9CEB7", +"c. c #BAD1BA", +"d. c #BBD0B9", +"e. c #B2C9B0", +"f. c #7EAB78", +"g. c #FBFCFC", +"h. c #DEE1E3", +"i. c #9DA6AE", +"j. c #AAC7A8", +"k. c #B3CAB1", +"l. c #B0C9B0", +"m. c #AEC7AC", +"n. c #AAC5A8", +"o. c #A9C4A7", +"p. c #698267", +"q. c #F9F9FA", +"r. c #BBBFC4", +"s. c #566779", +"t. c #2D2D2D", +"u. c #CFDFCC", +"v. c #ADC8AB", +"w. c #B0C7AE", +"x. c #ADC6AB", +"y. c #678C63", +"z. c #D1D2D4", +"A. c #9AA3AC", +"B. c #3C5235", +"C. c #5B7950", +"D. c #4A6342", +"E. c #E8ECEE", +"F. c #B2B8BE", +"G. c #717D88", +"H. c #3B5035", +"I. c #415639", +"J. c #7A8695", +"K. c #768594", +"L. c #2C343D", +"M. c #21272E", +" . + ", +" @ # $ . ", +" @ % & * = ", +" - ; > , ' ) . ", +" ! ~ > { ] ^ / ( ", +" _ : & ' ] < [ } | . ", +" 1 2 > 3 4 5 6 7 ] 8 9 ", +". 0 a b 4 c d e f g h i j . . . . . . . ", +"k l m < n } e o p q r s t t t t t t t u . ", +". v w x [ y ^ z [ A B C D E F G H I J K . ", +" L M N f O 5 d P Q R C S T U V W X Y Z . ", +" . ` .p ..+.@.#.$.%.&.*.E F =.U -.;.>.. ", +" ,.'.).. . !.~.t %.C S {.].V ^./.(.+ ", +" . _.. :.. <.b t [.a }.T U |.1.2.3. ", +" . :.4.. . . . . . . 5.6.7.8.9.. ", +" . :.0.a.b.c.b.d.e.f.. T g.h.i.= ", +" . :.j.k.l.m.n.n.m.o.p.. g.q.r.s.. ", +"t.u.v.w.x.x.j.m.m.m.v.y.. t z.A.+ ", +" . B.C.C.C.C.C.C.C.C.D.. E.F.G.. ", +" . B.C.C.H.H.H.H.H.I.. J.K.. ", +" . B.C.. . . . . . . L.M. ", +" . B.. ", +" . . ", +" . "}; + +GdkPixmap *prev_page_pixmap; +GdkBitmap *prev_page_mask; + + +/* XPM */ +static char * next_page_xpm[] = { +"24 24 172 2", +" c None", +". c #000000", +"+ c #040506", +"@ c #0B0F12", +"# c #959FAA", +"$ c #C3C6CA", +"% c #82909E", +"& c #F1F1F1", +"* c #D5D7D8", +"= c #0A0D10", +"- c #11171C", +"; c #8693A0", +"> c #EFF0F0", +", c #DEDEDE", +"' c #D5D5D5", +") c #9B9FA4", +"! c #0E1317", +"~ c #85929F", +"{ c #DBDBDB", +"] c #CACACA", +"^ c #C8C8C8", +"/ c #C8C9CA", +"( c #0C0F13", +"_ c #141A20", +": c #798895", +"< c #D2D2D2", +"[ c #C3C3C3", +"} c #CDCDCD", +"| c #74797E", +"1 c #171F26", +"2 c #7F8D9A", +"3 c #DADADA", +"4 c #D3D3D3", +"5 c #C4C4C4", +"6 c #CECECE", +"7 c #C0C0C0", +"8 c #B1B1B1", +"9 c #0D1115", +"0 c #768592", +"a c #EEEFEF", +"b c #D9D9D9", +"c c #D0D0D0", +"d c #C2C2C2", +"e c #CBCBCB", +"f c #C9C9C9", +"g c #BCBCBC", +"h c #A4A7A9", +"i c #686B6C", +"j c #333333", +"k c #414F5D", +"l c #ADB5BC", +"m c #EAEAEA", +"n c #BFBFBF", +"o c #BDBDBD", +"p c #C6C6C6", +"q c #B5B6B7", +"r c #899096", +"s c #B8B8B8", +"t c #FFFFFF", +"u c #404142", +"v c #4D6074", +"w c #EBEBEB", +"x c #D1D1D1", +"y c #C1C1C1", +"z c #B7B7B7", +"A c #979FA7", +"B c #A1A3A4", +"C c #FCFDFD", +"D c #F3F4F4", +"E c #EBECED", +"F c #EAEBEC", +"G c #E9EAEB", +"H c #EEEFF1", +"I c #F6F7F8", +"J c #E4E5E6", +"K c #929395", +"L c #32414F", +"M c #8C98A2", +"N c #E7E7E7", +"O c #BBBBBB", +"P c #A4A7AB", +"Q c #939699", +"R c #D7D8D8", +"S c #FAFCFC", +"T c #F9FAFB", +"U c #F8F9FA", +"V c #F7F8F9", +"W c #F5F6F8", +"X c #F7F7F9", +"Y c #C6C7C7", +"Z c #4F5E6A", +"` c #4C5F72", +" . c #E8E8E8", +".. c #BEBEBE", +"+. c #B5B5B6", +"@. c #979EA4", +"#. c #A8A8A8", +"$. c #FDFEFE", +"%. c #F5F6F6", +"&. c #E7E9E9", +"*. c #F0F1F2", +"=. c #8F969D", +"-. c #151C22", +";. c #354453", +">. c #8D99A2", +",. c #E3E3E3", +"'. c #8E949A", +"). c #9D9F9F", +"!. c #F2F3F4", +"~. c #F1F2F3", +"{. c #F6F6F7", +"]. c #4B5F71", +"^. c #E5E5E5", +"/. c #9E9FA0", +"(. c #97999B", +"_. c #E7E8E8", +":. c #F4F5F5", +"<. c #FBFBFB", +"[. c #D8D8DA", +"}. c #77A16E", +"|. c #394957", +"1. c #828F97", +"2. c #8A8E92", +"3. c #B4B4B4", +"4. c #ACC8A9", +"5. c #709867", +"6. c #4A5D70", +"7. c #ABABAB", +"8. c #F8F8F8", +"9. c #C1D6BD", +"0. c #BDD3B8", +"a. c #BFD4BB", +"b. c #C2D7BE", +"c. c #B2CBB0", +"d. c #AAC7A8", +"e. c #0F1308", +"f. c #242F3A", +"g. c #696D71", +"h. c #777879", +"i. c #F2F3F3", +"j. c #AEC5A8", +"k. c #AEC8AD", +"l. c #ABC7A8", +"m. c #AAC6A7", +"n. c #A8C6A5", +"o. c #ADC8AD", +"p. c #A8C7A8", +"q. c #A5C4A3", +"r. c #7F9F76", +"s. c #4A5F74", +"t. c #313E4B", +"u. c #B3BDC6", +"v. c #D1D7DD", +"w. c #D9DEE3", +"x. c #F6F7F7", +"y. c #A6BFA0", +"z. c #ABC7AA", +"A. c #A9C7A6", +"B. c #AFC8AD", +"C. c #A4C3A2", +"D. c #6B9060", +"E. c #2B343C", +"F. c #29323B", +"G. c #4F5F70", +"H. c #5E7184", +"I. c #919EAB", +"J. c #6C8562", +"K. c #5B7950", +"L. c #445B2C", +"M. c #252D35", +"N. c #65815C", +"O. c #506B46", +" . + ", +" @ # $ . ", +" @ % & * = ", +" - ; > , ' ) . ", +" ! ~ > { ] ^ / ( ", +" _ : & ' ] < [ } | . ", +" 1 2 > 3 4 5 6 7 ] 8 9 ", +". 0 a b 4 c d e f g h i j . . . . . . . ", +"k l m < n } e o p q r s t t t t t t t u . ", +". v w x [ y ^ z [ A B C D E F G H I J K . ", +" L M N f O 5 d P Q R C S T U V W X Y Z . ", +" . ` .p ..s +.@.#.$.%.&.E F *.U . =.-.. ", +" ;.>.,.y ..'.).t $.C S !.~.V {.. . + ", +" . ].^.y /.(.b t _.a :.T U <.[.. }.. ", +" |.1.{ 2.3.t t $.. . . . . . . 4.5.. ", +" . 6.O 7.t 8.& > . 9.0.a.b.b.b.c.d.5.e. ", +" f.g.h.i.t t t . j.k.l.l.m.n.o.p.q.r.. ", +" . s.t.u.v.w.x.. y.z.n.n.A.l.d.l.B.C.D.. ", +" . E.F.G.H.I.. J.K.K.K.K.K.K.K.K.L.. ", +" . . M.. N.O.O.O.O.O.K.K.L.. ", +" . . . . . . . K.L.. ", +" . L.. ", +" . . ", +" . "}; + +GdkPixmap *next_page_pixmap; +GdkBitmap *next_page_mask; + + +/* XPM */ +static char * wave_info[] = { +"48 52 677 2", +" c None", +". c #000000", +"+ c #232323", +"@ c #1F1F1F", +"# c #DADADA", +"$ c #FFFFFF", +"% c #F6F6F6", +"& c #CFCFCF", +"* c #707070", +"= c #FEFEFE", +"- c #FBFBFB", +"; c #EDEDED", +"> c #C0C0C0", +", c #FF0000", +"' c #F7F7F7", +") c #D7D7D7", +"! c #F1F1F1", +"~ c #B7B7B7", +"{ c #D2D2D2", +"] c #AEAEAE", +"^ c #070707", +"/ c #FDFDFD", +"( c #B8B8B8", +"_ c #DCDCDC", +": c #A4A4A3", +"< c #0E0E0E", +"[ c #F5F5F4", +"} c #B5B5B5", +"| c #F9F9F9", +"1 c #FCFCFC", +"2 c #CBCBCB", +"3 c #A5A5A5", +"4 c #FDFDFC", +"5 c #F4F4F4", +"6 c #ACACAC", +"7 c #ECECEC", +"8 c #C3C3C3", +"9 c #C2C2C2", +"0 c #C9C9C8", +"a c #A8A8A8", +"b c #FCFCFB", +"c c #F4F4F3", +"d c #ABABAB", +"e c #515151", +"f c #474747", +"g c #464645", +"h c #464646", +"i c #5D5D5C", +"j c #A9A9A9", +"k c #FAFAFA", +"l c #F2F2F2", +"m c #F3F3F3", +"n c #AAAAAA", +"o c #A0A09F", +"p c #8A8A8A", +"q c #7A7A7A", +"r c #6C6C6C", +"s c #454545", +"t c #FAFAF9", +"u c #E7E7E7", +"v c #C6C6C5", +"w c #BABAB9", +"x c #F5F5F5", +"y c #EDEDEB", +"z c #B2B2B2", +"A c #949494", +"B c #7F7F7F", +"C c #8B8B8B", +"D c #8D8D8D", +"E c #EFEFEF", +"F c #737373", +"G c #727272", +"H c #666666", +"I c #4F4F4F", +"J c #4E4E4E", +"K c #4D4D4D", +"L c #505050", +"M c #CACACA", +"N c #4B4B4B", +"O c #4A4A4A", +"P c #4C4C4C", +"Q c #525252", +"R c #575757", +"S c #373737", +"T c #A1A1A1", +"U c #363636", +"V c #333333", +"W c #353535", +"X c #3F3F3F", +"Y c #5C5C5C", +"Z c #6B6B6B", +"` c #B1B1B1", +" . c #A6A6A6", +".. c #E4E4E4", +"+. c #2E2E2E", +"@. c #2D2D2D", +"#. c #252525", +"$. c #191919", +"%. c #1B1B1B", +"&. c #1C1C1C", +"*. c #1E1E1E", +"=. c #212121", +"-. c #B9B9B9", +";. c #1D1D1D", +">. c #171717", +",. c #242424", +"'. c #222222", +"). c #919191", +"!. c #292929", +"~. c #F3F3F2", +"{. c #9C9C9C", +"]. c #696969", +"^. c #030303", +"/. c #010101", +"(. c #B0B0B0", +"_. c #080808", +":. c #060606", +"<. c #868686", +"[. c #040404", +"}. c #0C0C0C", +"|. c #2A2A2A", +"1. c #F2F2F1", +"2. c #979797", +"3. c #5F5F5F", +"4. c #131413", +"5. c #222421", +"6. c #2B302A", +"7. c #B4BAB3", +"8. c #2B312A", +"9. c #2A3029", +"0. c #292E28", +"a. c #282D26", +"b. c #272D26", +"c. c #262C25", +"d. c #252C24", +"e. c #242B23", +"f. c #242B22", +"g. c #8B9289", +"h. c #1E241D", +"i. c #151814", +"j. c #101010", +"k. c #303030", +"l. c #F1F1F0", +"m. c #8E8E8E", +"n. c #D4D4D4", +"o. c #272A26", +"p. c #495546", +"q. c #64825E", +"r. c #6B9063", +"s. c #ABD3A2", +"t. c #658D5C", +"u. c #628C59", +"v. c #608A56", +"w. c #5E8B54", +"x. c #598550", +"y. c #57864D", +"z. c #54844A", +"A. c #518046", +"B. c #4F8143", +"C. c #84B779", +"D. c #46773C", +"E. c #344E2F", +"F. c #1C241A", +"G. c #F0F0F0", +"H. c #848484", +"I. c #D0D0D0", +"J. c #262825", +"K. c #5A6E56", +"L. c #86C476", +"M. c #8FE878", +"N. c #8DEC74", +"O. c #93F479", +"P. c #84E66A", +"Q. c #81E665", +"R. c #7DE661", +"S. c #7AE75C", +"T. c #75E259", +"U. c #72E653", +"V. c #6EE14F", +"W. c #6BE14A", +"X. c #67E446", +"Y. c #6FEC4D", +"Z. c #60E53D", +"`. c #53B13A", +" + c #32522B", +".+ c #141A13", +"++ c #0B0B0B", +"@+ c #2B2B2B", +"#+ c #EFEFEE", +"$+ c #EFEFED", +"%+ c #777777", +"&+ c #CDCDCD", +"*+ c #414B3F", +"=+ c #7FB372", +"-+ c #93F778", +";+ c #90F974", +">+ c #8AF06F", +",+ c #90F474", +"'+ c #81E666", +")+ c #79E55C", +"!+ c #76E758", +"~+ c #71E153", +"{+ c #6FE64E", +"]+ c #67E145", +"^+ c #63E441", +"/+ c #69EE46", +"(+ c #60F537", +"_+ c #5AF032", +":+ c #449030", +"<+ c #20301D", +"[+ c #080908", +"}+ c #0A0A0A", +"|+ c #EEEEED", +"1+ c #EEEEEC", +"2+ c #FBFBFA", +"3+ c #747474", +"4+ c #313131", +"5+ c #1C1E1C", +"6+ c #586D53", +"7+ c #8AD676", +"8+ c #90FB73", +"9+ c #87E66E", +"0+ c #74B065", +"a+ c #9FD095", +"b+ c #5E8B53", +"c+ c #5A8850", +"d+ c #57864C", +"e+ c #548649", +"f+ c #508145", +"g+ c #4E8242", +"h+ c #4B7F3F", +"i+ c #487E3C", +"j+ c #47823A", +"k+ c #73C060", +"l+ c #56DA34", +"m+ c #58F72C", +"n+ c #4BBE2D", +"o+ c #284821", +"p+ c #0F140E", +"q+ c #343434", +"r+ c #414141", +"s+ c #EDEDEC", +"t+ c #E2E2E2", +"u+ c #D8D8D8", +"v+ c #C6C6C6", +"w+ c #BEBEBE", +"x+ c #BABABA", +"y+ c #BDC1BC", +"z+ c #B0D6A8", +"A+ c #96F57C", +"B+ c #8FFA72", +"C+ c #9AE089", +"D+ c #A7C0A2", +"E+ c #A6B0A3", +"F+ c #A0A79F", +"G+ c #9CA39B", +"H+ c #989E96", +"I+ c #949B92", +"J+ c #90978E", +"K+ c #878F85", +"L+ c #828B80", +"M+ c #7E8C7B", +"N+ c #799972", +"O+ c #67C750", +"P+ c #56F62C", +"Q+ c #56E92E", +"R+ c #619E53", +"S+ c #606C5E", +"T+ c #565756", +"U+ c #5A5A5A", +"V+ c #7B7B7B", +"W+ c #828282", +"X+ c #ECECEB", +"Y+ c #757575", +"Z+ c #3B4439", +"`+ c #77B069", +" @ c #8AF66D", +".@ c #84EC68", +"+@ c #65965A", +"@@ c #313C2F", +"#@ c #9C9D9C", +"$@ c #050505", +"%@ c #0D0F0C", +"&@ c #758672", +"*@ c #3D832D", +"=@ c #4DE625", +"-@ c #4AF21E", +";@ c #369320", +">@ c #182E13", +",@ c #050704", +"'@ c #121212", +")@ c #494949", +"!@ c #565656", +"~@ c #2C2C2C", +"{@ c #171917", +"]@ c #4D6149", +"^@ c #7FCE6C", +"/@ c #87FB68", +"(@ c #7DDB65", +"_@ c #53744C", +":@ c #1F241E", +"<@ c #959595", +"[@ c #020202", +"}@ c #70786E", +"|@ c #2E5B24", +"1@ c #45CA22", +"2@ c #48F719", +"3@ c #39B719", +"4@ c #1A3E12", +"5@ c #050C04", +"6@ c #141514", +"7@ c #595959", +"8@ c #EBEBEA", +"9@ c #F8F8F8", +"0@ c #5E5E5E", +"a@ c #BCBCBC", +"b@ c #638A5A", +"c@ c #82E867", +"d@ c #83FA62", +"e@ c #72C15E", +"f@ c #40543C", +"g@ c #151714", +"h@ c #6B6E6A", +"i@ c #203B1B", +"j@ c #39A51E", +"k@ c #42F112", +"l@ c #3AD410", +"m@ c #1E5C10", +"n@ c #061103", +"o@ c #111211", +"p@ c #555555", +"q@ c #EAEAE9", +"r@ c #EAEAE8", +"s@ c #F8F8F7", +"t@ c #5B5B5B", +"u@ c #0D0D0D", +"v@ c #3A4638", +"w@ c #71AE62", +"x@ c #81F563", +"y@ c #7DF15E", +"z@ c #64A155", +"A@ c #313D2E", +"B@ c #646664", +"C@ c #162813", +"D@ c #2C7919", +"E@ c #3ADE0E", +"F@ c #36DF09", +"G@ c #21780D", +"H@ c #091A05", +"I@ c #0E0F0D", +"J@ c #444444", +"K@ c #E9E9E8", +"L@ c #E9E9E7", +"M@ c #5D5D5D", +"N@ c #B6B6B6", +"O@ c #1A1C19", +"P@ c #4B6146", +"Q@ c #75C262", +"R@ c #7EF65D", +"S@ c #75DA5A", +"T@ c #517949", +"U@ c #212720", +"V@ c #0C160A", +"W@ c #1E5213", +"X@ c #30BA0C", +"Y@ c #33DD04", +"Z@ c #25890C", +"`@ c #0C2507", +" # c #10130F", +".# c #F6F6F5", +"+# c #262B25", +"@# c #5A8052", +"## c #79E05E", +"$# c #7BF957", +"%# c #6BC554", +"&# c #3E5639", +"*# c #131613", +"=# c #878787", +"-# c #050A04", +";# c #13350B", +"># c #299E0B", +",# c #32DA04", +"'# c #2BB208", +")# c #133D0A", +"!# c #0F160E", +"~# c #3E3E3E", +"{# c #E8E8E7", +"]# c #E8E8E6", +"^# c #AFAFAF", +"/# c #323D30", +"(# c #66A257", +"_# c #7AF458", +":# c #75F553", +"<# c #5EA44E", +"[# c #2F3D2C", +"}# c #0A0B0A", +"|# c #838383", +"1# c #585858", +"2# c #010201", +"3# c #091D06", +"4# c #20720B", +"5# c #30D004", +"6# c #2FCB04", +"7# c #1B610A", +"8# c #0F1A0D", +"9# c #404040", +"0# c #131513", +"a# c #3F513B", +"b# c #6BB957", +"c# c #75F752", +"d# c #6EDC50", +"e# c #4D7A43", +"f# c #212A20", +"g# c #808080", +"h# c #545454", +"i# c #040D02", +"j# c #143F0A", +"k# c #29A807", +"l# c #2FCA04", +"m# c #1F760A", +"n# c #142511", +"o# c #404240", +"p# c #E7E7E6", +"q# c #E6E6E4", +"r# c #3C3C3C", +"s# c #151515", +"t# c #222721", +"u# c #507348", +"v# c #6FD654", +"w# c #72F94D", +"x# c #64C14B", +"y# c #3B5836", +"z# c #161A15", +"A# c #7D7D7D", +"B# c #010400", +"C# c #0B2006", +"D# c #218109", +"E# c #2EC903", +"F# c #249407", +"G# c #163210", +"H# c #3A3D3A", +"I# c #565655", +"J# c #E5E5E4", +"K# c #CCCCCC", +"L# c #C1C1C1", +"M# c #B4B4B4", +"N# c #AAABA9", +"O# c #A8B5A5", +"P# c #92D084", +"Q# c #77F555", +"R# c #73F84E", +"S# c #84CE72", +"T# c #93A38F", +"U# c #8C8D8B", +"V# c #7E7E7E", +"W# c #797979", +"X# c #717171", +"Y# c #686868", +"Z# c #636363", +"`# c #424342", +" $ c #3A4538", +".$ c #337622", +"+$ c #2EBC08", +"@$ c #2DB00A", +"#$ c #2F5F23", +"$$ c #515750", +"%$ c #686867", +"&$ c #E1E1E0", +"*$ c #E3E3E2", +"=$ c #111111", +"-$ c #FBFDFA", +";$ c #EDF2EC", +">$ c #2E342D", +",$ c #575D56", +"'$ c #3F453E", +")$ c #2B322A", +"!$ c #2A3129", +"~$ c #2A3128", +"{$ c #293127", +"]$ c #A9B5A7", +"^$ c #466341", +"/$ c #66C050", +"($ c #6DFA47", +"_$ c #66E644", +":$ c #477D3C", +"<$ c #212A1F", +"[$ c #040403", +"}$ c #040504", +"|$ c #787978", +"1$ c #020302", +"2$ c #030801", +"3$ c #103807", +"4$ c #26A305", +"5$ c #2AB602", +"6$ c #1D6809", +"7$ c #283725", +"8$ c #3F443E", +"9$ c #CFD1CD", +"0$ c #D7D8D5", +"a$ c #323831", +"b$ c #E3F8DE", +"c$ c #CAEFC1", +"d$ c #6A9460", +"e$ c #7AA670", +"f$ c #6C9A62", +"g$ c #619057", +"h$ c #608F54", +"i$ c #5C8C51", +"j$ c #5A8C4E", +"k$ c #96CD89", +"l$ c #5EA44D", +"m$ c #69DF4A", +"n$ c #6AF945", +"o$ c #63C949", +"p$ c #45693D", +"q$ c #2C3B28", +"r$ c #1C2919", +"s$ c #1B2817", +"t$ c #1D2D1A", +"u$ c #7A8B76", +"v$ c #172614", +"w$ c #10190E", +"x$ c #152312", +"y$ c #1A2C15", +"z$ c #1C2C19", +"A$ c #1D291A", +"B$ c #1C2819", +"C$ c #172214", +"D$ c #152013", +"E$ c #515B4E", +"F$ c #111C0F", +"G$ c #111F0D", +"H$ c #15350D", +"I$ c #25850C", +"J$ c #2AB603", +"K$ c #218D05", +"L$ c #1E5111", +"M$ c #2B4D22", +"N$ c #0C2A04", +"O$ c #99B392", +"P$ c #AEBBA9", +"Q$ c #A6A7A5", +"R$ c #51644D", +"S$ c #B4F4A4", +"T$ c #9BF783", +"U$ c #88EC6D", +"V$ c #86EB6B", +"W$ c #81EC65", +"X$ c #7DE860", +"Y$ c #79E85B", +"Z$ c #75E757", +"`$ c #71E651", +" % c #79F159", +".% c #6BE84A", +"+% c #6DF649", +"@% c #6EF44A", +"#% c #64BB4E", +"$% c #4C7E3F", +"%% c #39652E", +"&% c #315C26", +"*% c #2E5822", +"=% c #2D5921", +"-% c #73A266", +";% c #2A591E", +">% c #2C5821", +",% c #3A6E2C", +"'% c #407C30", +")% c #427634", +"!% c #38632E", +"~% c #346029", +"{% c #325D26", +"]% c #305C24", +"^% c #59864D", +"/% c #2C591F", +"(% c #2B5A1E", +"_% c #28571B", +":% c #265919", +"<% c #2C7818", +"[% c #2CAB08", +"}% c #26A603", +"|% c #259506", +"1% c #288E0B", +"2% c #1E8404", +"3% c #42A029", +"4% c #5EA14B", +"5% c #90998D", +"6% c #4F624A", +"7% c #B0F49F", +"8% c #97F77E", +"9% c #84EB67", +"0% c #83EA67", +"a% c #7DEC60", +"b% c #77E75A", +"c% c #75E857", +"d% c #70E552", +"e% c #6DE64D", +"f% c #74F053", +"g% c #6BE44A", +"h% c #71EC52", +"i% c #6ACE51", +"j% c #569546", +"k% c #416E35", +"l% c #336128", +"m% c #315E24", +"n% c #305F24", +"o% c #2E5E21", +"p% c #BEBCCB", +"q% c #736F79", +"r% c #2F362E", +"s% c #DFF7DA", +"t% c #C4EEBA", +"u% c #619056", +"v% c #71A165", +"w% c #639558", +"x% c #5B8E4F", +"y% c #588D4C", +"z% c #558A49", +"A% c #538945", +"B% c #8DC67F", +"C% c #538A46", +"D% c #59914C", +"E% c #4F7846", +"F% c #405A3A", +"G% c #364A31", +"H% c #34482F", +"I% c #32472D", +"J% c #32482D", +"K% c #30462B", +"L% c #625B81", +"M% c #272534", +"N% c #0F100F", +"O% c #FAFDF9", +"P% c #E8EEE5", +"Q% c #2A3228", +"R% c #60685F", +"S% c #4C544A", +"T% c #424B41", +"U% c #434C42", +"V% c #4F584D", +"W% c #50594E", +"X% c #ABB5A9", +"Y% c #4C554A", +"Z% c #3F473D", +"`% c #373D36", +" & c #3B3E3A", +".& c #515450", +"+& c #525652", +"@& c #535652", +"#& c #CAC8D5", +"$& c #ECECEA", +"%& c #555655", +"&& c #383938", +"*& c #474847", +"=& c #626262", +"-& c #616161", +";& c #606060", +">& c #A7A3B8", +",& c #847F9C", +"'& c #736D8E", +")& c #DBDAE2", +"!& c #9691AB", +"~& c #EBEBE9", +"{& c #B8B5C6", +"]& c #E7E7E5", +"^& c #E4E4E3", +"/& c #E4E4E2", +"(& c #EDECF0", +"_& c #E5E5E3", +":& c #E6E6E5", +"<& c #E3E3E1", +"[& c #A9A9A7", +"}& c #A3A3A2", +"|& c #A3A3A1", +"1& c #E2E2E0", +"2& c #E1E1DF", +"3& c #9A9A9A", +"4& c #8C8C8C", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + @ ", +". # $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ % & * . ", +". $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = - % ; > . ", +". $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = ' ) $ ! ~ . ", +". $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = = = ' { $ $ ; ] ^ ", +". $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = = = / / % ( $ / $ _ : < ", +". $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = / / / / / / [ } $ | 1 $ 2 3 . ", +". $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = / / / / / 4 1 1 1 5 6 7 8 2 ( 9 0 a . ", +". $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = / / / / / / 4 1 1 1 1 1 b c d e f g h h i j . ", +". $ $ $ $ $ $ $ $ = = = = = = = = = = / / / / / 4 1 1 1 1 1 1 b - - k l m > n o p q r s . ", +". $ $ $ $ $ $ = = = = = = = = / / / / / 1 / / / / 1 1 b - - - - k t t | - ' ' u v 0 w q . ", +". $ $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x y j . ", +". $ $ . z A q B C D E F G H e I J K L K M N h h O P Q R P S T U V W U V W X Y Z . m m ` . ", +". $ = . .B R Q h S ..+.@.#.$.%.&.$.*.=.-.$.;.>.$.@ *.,.'.>.).;.>.$.;.>.$.!.X X . ~.~.} . ", +". $ / . {.].U ;.^.. # . . . . . . /.^.^ (._.^ ^ :.^ :.^ ^ :.<.[.^.. . . . }.|.|.. 1.1.} . ", +". $ / . 2.3.@ ^.. . ) . . . . . :.4.5.6.7.8.9.0.a.b.c.d.e.f.g.h.i._.. . . j.k.k.. l.l.} . ", +". $ 1 . m.h ^.. . . n.. . . . _.o.p.q.r.s.t.u.v.w.x.y.z.A.B.C.D.E.F._.. . < @.@.. G.G.} . ", +". $ b . H.V . . . . I.. . . [.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z.`. +.+/.. ++!.@+. #+$+} . ", +". $ - . %+k.. . . . &+. . . j.*+=+-+;+>+,+'+R.)+!+~+{+W.]+^+/+(+_+:+<+[+. }+@+W . |+1+} . ", +". $ 2+. 3+4+. . . . M . . /.5+6+7+8+9+0+a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+. }+q+r+. s+s+} . ", +". $ k . E t+u+n.& 2 v+9 w+x+y+z+A+B+C+D+E+F+G+H+I+J+g.K+L+M+N+O+P+Q+R+S+T+U+V+W+. 7 X+} . ", +". $ t . Y+k.. . . . 8 . . < Z+`+ @.@+@@@#@^ :.^ $@^ :.:.:.%@&@*@=@-@;@>@,@'@)@!@. X+X+} . ", +". $ | . Z ~@. . . . > . . {@]@^@/@(@_@:@<@. . . . . . . . [@}@|@1@2@3@4@5@6@P 7@. 8@8@} . ", +". $ 9@. 0@#.. . . . a@. [.0.b@c@d@e@f@g@).. . . . . . . . . h@i@j@k@l@m@n@o@s p@. q@r@} . ", +". $ s@. t@#.. . . . -.. u@v@w@x@y@z@A@++D . . . . . . . . . B@C@D@E@F@G@H@I@J@R . K@L@} . ", +". $ % . M@!.. . . . N@/.O@P@Q@R@S@T@U@^.p . . . . . . . . . 0@V@W@X@Y@Z@`@ #J@t@. L@L@} . ", +". $ .#. U++ . . . . z [.+#@###$#%#&#*#. =#. . . . . . . . . U+-#;#>#,#'#)#!#~#R . {#]#} . ", +". $ x . t@#.. . . . ^#++/#(#_#:#<#[#}#. |#. . . . . . . . . 1#2#3#4#5#6#7#8#9#R . ]#]#} . ", +". $ c . t@#.. . . . 6 0#a#b#c#d#e#f#[.. g#. . . . . . . . . h#. i#j#k#l#m#n#o#U+. p#q#} . ", +". $ l . r#s#. . . . n t#u#v#w#x#y#z#/.. A#. . . . . . . . . e . B#C#D#E#F#G#H#I#. q#J#} . ", +"[@= 1.^ K#L#-.M#(.6 N#O#P#Q#R#S#T#U#W+V#W#Y+X#r Y#Z#3.t@!@Q J )@`# $.$+$@$#$$$%$. &$*$} . ", +"=$-$;$>$,$'$)$!$~${$]$^$/$($_$:$<$^ [$}$|$1$. . . . . . . . O . . 2$3$4$5$6$7$8$B#9$0$(.. ", +"a$b$c$d$e$f$g$h$i$j$k$l$m$n$o$p$q$r$s$t$u$v$w$x$y$z$A$B$C$D$E$w$F$G$H$I$J$K$L$M$N$O$P$Q$. ", +"R$S$T$U$V$W$X$Y$Z$`$ %.%+%@%#%$%%%&%*%=%-%;%>%,%'%)%!%~%{%]%^%/%(%_%:%<%[%}%|%1%2%3%4%5%. ", +"6%7%8%9%0%a%b%c%d%e%f%g%h%i%j%k%l%m%n%o%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%q%", +"r%s%t%u%v%w%x%y%z%A%B%C%D%E%F%G%H%I%J%K%p%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%M%", +"N%O%P%Q%R%S%T%U%V%W%X%Y%Z%`% &.&+&+&@&.&p%L%L%L%#&L%L%#&L%L%#&L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%M%", +"/.= $&^ %&`#&&*&=&-&( ;&`#q+r#h#R 1#R 7@p%L%L%L%>&,&'&)&>&L%#&L%'&!&'&L%,&L%L%,&L%'&,&L%L%L%L%M%", +". $ ~&. . . . . . . . . . . . . . . . . p%L%L%L%!&!&!&!&#&L%#&L%#&!&)&L%#&L%'&{&,&#&>&{&L%L%L%M%", +". $ q@q@q@r@r@K@K@{#]#]#]&q#q#J#^&/&/&/&p%L%L%L%L%#&{&'&#&!&!&L%,&{&(&L%{&,&{&,&#&!&!&)&L%L%L%M%", +". $ r@K@K@K@K@{#]#]#p#p#]&]&q#q#_&_&/&/&p%L%L%L%L%#&#&L%#&{&'&,&#&'&#&L%'&{&#&L%#&!&!&!&L%L%L%M%", +". $ K@K@K@]#p#p#p#p#]&]&]&:&:&q#_&_&_&_&p%L%L%L%L%>&{&L%,&)&L%,&#&>&(&'&L%#&>&L%,&#&!&)&L%L%L%M%", +". $ L@p#p#p#p#]&]&]&:&:&:&q#_&_&_&^&^&/&p%L%L%L%L%'&'&L%L%,&L%L%,&,&'&'&L%,&'&L%L%'&!&L%L%L%L%M%", +". $ p#]&]&]&:&:&:&:&q#q#_&^&^&^&/&/&/&/&p%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%M%", +". $ ]&:&:&:&q#q#q#q#^&^&/&/&/&/&/&/&/&/&q%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%", +". $ :&q#q#q#q#J#^&/&/&/&/&/&/&/&/&/&/&<&<&[&: }&}&}&}&|&|&|& |&|&|&|&|&|&|&|&|&D . . . ", +". # q#q#q#_&/&/&/&/&/&/&/&/&/&/&*$<&<&<&<&<&<&<&<&1&1&1&1&2&2&2&2&2&2&2&2&2&2&2&2&2&2&3&. ", +". 9 } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } 3&4&. ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" ", +" ", +" "}; + +GdkPixmap *wave_info_pixmap; +GdkBitmap *wave_info_mask; + + +/* XPM */ +static char * wave_alert[] = { +"48 52 677 2", +" c None", +". c #000000", +"+ c #232323", +"@ c #1F1F1F", +"# c #DADADA", +"$ c #FFFFFF", +"% c #F6F6F6", +"& c #CFCFCF", +"* c #707070", +"= c #FEFEFE", +"- c #FBFBFB", +"; c #EDEDED", +"> c #C0C0C0", +", c #FF0000", +"' c #F7F7F7", +") c #D7D7D7", +"! c #F1F1F1", +"~ c #B7B7B7", +"{ c #D2D2D2", +"] c #AEAEAE", +"^ c #070707", +"/ c #FDFDFD", +"( c #B8B8B8", +"_ c #DCDCDC", +": c #A4A4A3", +"< c #0E0E0E", +"[ c #F5F5F4", +"} c #B5B5B5", +"| c #F9F9F9", +"1 c #FCFCFC", +"2 c #CBCBCB", +"3 c #A5A5A5", +"4 c #FDFDFC", +"5 c #F4F4F4", +"6 c #ACACAC", +"7 c #ECECEC", +"8 c #C3C3C3", +"9 c #C2C2C2", +"0 c #C9C9C8", +"a c #A8A8A8", +"b c #FCFCFB", +"c c #F4F4F3", +"d c #ABABAB", +"e c #515151", +"f c #474747", +"g c #464645", +"h c #464646", +"i c #5D5D5C", +"j c #A9A9A9", +"k c #FAFAFA", +"l c #F2F2F2", +"m c #F3F3F3", +"n c #AAAAAA", +"o c #A0A09F", +"p c #8A8A8A", +"q c #7A7A7A", +"r c #6C6C6C", +"s c #454545", +"t c #FAFAF9", +"u c #E7E7E7", +"v c #C6C6C5", +"w c #BABAB9", +"x c #F5F5F5", +"y c #EDEDEB", +"z c #B2B2B2", +"A c #949494", +"B c #7F7F7F", +"C c #8B8B8B", +"D c #8D8D8D", +"E c #EFEFEF", +"F c #737373", +"G c #727272", +"H c #666666", +"I c #4F4F4F", +"J c #4E4E4E", +"K c #4D4D4D", +"L c #505050", +"M c #CACACA", +"N c #4B4B4B", +"O c #4A4A4A", +"P c #4C4C4C", +"Q c #525252", +"R c #575757", +"S c #373737", +"T c #A1A1A1", +"U c #363636", +"V c #333333", +"W c #353535", +"X c #3F3F3F", +"Y c #5C5C5C", +"Z c #6B6B6B", +"` c #B1B1B1", +" . c #A6A6A6", +".. c #E4E4E4", +"+. c #2E2E2E", +"@. c #2D2D2D", +"#. c #252525", +"$. c #191919", +"%. c #1B1B1B", +"&. c #1C1C1C", +"*. c #1E1E1E", +"=. c #212121", +"-. c #B9B9B9", +";. c #1D1D1D", +">. c #171717", +",. c #242424", +"'. c #222222", +"). c #919191", +"!. c #292929", +"~. c #F3F3F2", +"{. c #9C9C9C", +"]. c #696969", +"^. c #030303", +"/. c #010101", +"(. c #B0B0B0", +"_. c #080808", +":. c #060606", +"<. c #868686", +"[. c #040404", +"}. c #0C0C0C", +"|. c #2A2A2A", +"1. c #F2F2F1", +"2. c #979797", +"3. c #5F5F5F", +"4. c #131413", +"5. c #222421", +"6. c #2B302A", +"7. c #B4BAB3", +"8. c #2B312A", +"9. c #2A3029", +"0. c #292E28", +"a. c #282D26", +"b. c #272D26", +"c. c #262C25", +"d. c #252C24", +"e. c #242B23", +"f. c #242B22", +"g. c #8B9289", +"h. c #1E241D", +"i. c #151814", +"j. c #101010", +"k. c #303030", +"l. c #F1F1F0", +"m. c #8E8E8E", +"n. c #D4D4D4", +"o. c #272A26", +"p. c #495546", +"q. c #64825E", +"r. c #6B9063", +"s. c #ABD3A2", +"t. c #658D5C", +"u. c #628C59", +"v. c #608A56", +"w. c #5E8B54", +"x. c #598550", +"y. c #57864D", +"z. c #54844A", +"A. c #518046", +"B. c #4F8143", +"C. c #84B779", +"D. c #46773C", +"E. c #344E2F", +"F. c #1C241A", +"G. c #F0F0F0", +"H. c #848484", +"I. c #D0D0D0", +"J. c #262825", +"K. c #5A6E56", +"L. c #86C476", +"M. c #8FE878", +"N. c #8DEC74", +"O. c #93F479", +"P. c #84E66A", +"Q. c #81E665", +"R. c #7DE661", +"S. c #7AE75C", +"T. c #75E259", +"U. c #72E653", +"V. c #6EE14F", +"W. c #6BE14A", +"X. c #67E446", +"Y. c #6FEC4D", +"Z. c #60E53D", +"`. c #53B13A", +" + c #32522B", +".+ c #141A13", +"++ c #0B0B0B", +"@+ c #2B2B2B", +"#+ c #EFEFEE", +"$+ c #EFEFED", +"%+ c #777777", +"&+ c #CDCDCD", +"*+ c #414B3F", +"=+ c #7FB372", +"-+ c #93F778", +";+ c #90F974", +">+ c #8AF06F", +",+ c #90F474", +"'+ c #81E666", +")+ c #79E55C", +"!+ c #76E758", +"~+ c #71E153", +"{+ c #6FE64E", +"]+ c #67E145", +"^+ c #63E441", +"/+ c #69EE46", +"(+ c #60F537", +"_+ c #5AF032", +":+ c #449030", +"<+ c #20301D", +"[+ c #080908", +"}+ c #0A0A0A", +"|+ c #EEEEED", +"1+ c #EEEEEC", +"2+ c #FBFBFA", +"3+ c #747474", +"4+ c #313131", +"5+ c #1C1E1C", +"6+ c #586D53", +"7+ c #8AD676", +"8+ c #90FB73", +"9+ c #87E66E", +"0+ c #74B065", +"a+ c #9FD095", +"b+ c #5E8B53", +"c+ c #5A8850", +"d+ c #57864C", +"e+ c #548649", +"f+ c #508145", +"g+ c #4E8242", +"h+ c #4B7F3F", +"i+ c #487E3C", +"j+ c #47823A", +"k+ c #73C060", +"l+ c #56DA34", +"m+ c #58F72C", +"n+ c #4BBE2D", +"o+ c #284821", +"p+ c #0F140E", +"q+ c #343434", +"r+ c #414141", +"s+ c #EDEDEC", +"t+ c #E2E2E2", +"u+ c #D8D8D8", +"v+ c #C6C6C6", +"w+ c #BEBEBE", +"x+ c #BABABA", +"y+ c #BDC1BC", +"z+ c #B0D6A8", +"A+ c #96F57C", +"B+ c #8FFA72", +"C+ c #9AE089", +"D+ c #A7C0A2", +"E+ c #A6B0A3", +"F+ c #A0A79F", +"G+ c #9CA39B", +"H+ c #989E96", +"I+ c #949B92", +"J+ c #90978E", +"K+ c #878F85", +"L+ c #828B80", +"M+ c #7E8C7B", +"N+ c #799972", +"O+ c #67C750", +"P+ c #56F62C", +"Q+ c #56E92E", +"R+ c #619E53", +"S+ c #606C5E", +"T+ c #565756", +"U+ c #5A5A5A", +"V+ c #7B7B7B", +"W+ c #828282", +"X+ c #ECECEB", +"Y+ c #757575", +"Z+ c #3B4439", +"`+ c #77B069", +" @ c #8AF66D", +".@ c #84EC68", +"+@ c #65965A", +"@@ c #313C2F", +"#@ c #9C9D9C", +"$@ c #050505", +"%@ c #0D0F0C", +"&@ c #758672", +"*@ c #3D832D", +"=@ c #4DE625", +"-@ c #4AF21E", +";@ c #369320", +">@ c #182E13", +",@ c #050704", +"'@ c #121212", +")@ c #494949", +"!@ c #565656", +"~@ c #2C2C2C", +"{@ c #171917", +"]@ c #4D6149", +"^@ c #7FCE6C", +"/@ c #87FB68", +"(@ c #7DDB65", +"_@ c #53744C", +":@ c #1F241E", +"<@ c #959595", +"[@ c #020202", +"}@ c #70786E", +"|@ c #2E5B24", +"1@ c #45CA22", +"2@ c #48F719", +"3@ c #39B719", +"4@ c #1A3E12", +"5@ c #050C04", +"6@ c #141514", +"7@ c #595959", +"8@ c #EBEBEA", +"9@ c #F8F8F8", +"0@ c #5E5E5E", +"a@ c #BCBCBC", +"b@ c #638A5A", +"c@ c #82E867", +"d@ c #83FA62", +"e@ c #72C15E", +"f@ c #40543C", +"g@ c #151714", +"h@ c #6B6E6A", +"i@ c #203B1B", +"j@ c #39A51E", +"k@ c #42F112", +"l@ c #3AD410", +"m@ c #1E5C10", +"n@ c #061103", +"o@ c #111211", +"p@ c #555555", +"q@ c #EAEAE9", +"r@ c #EAEAE8", +"s@ c #F8F8F7", +"t@ c #5B5B5B", +"u@ c #0D0D0D", +"v@ c #3A4638", +"w@ c #71AE62", +"x@ c #81F563", +"y@ c #7DF15E", +"z@ c #64A155", +"A@ c #313D2E", +"B@ c #646664", +"C@ c #162813", +"D@ c #2C7919", +"E@ c #3ADE0E", +"F@ c #36DF09", +"G@ c #21780D", +"H@ c #091A05", +"I@ c #0E0F0D", +"J@ c #444444", +"K@ c #E9E9E8", +"L@ c #E9E9E7", +"M@ c #5D5D5D", +"N@ c #B6B6B6", +"O@ c #1A1C19", +"P@ c #4B6146", +"Q@ c #75C262", +"R@ c #7EF65D", +"S@ c #75DA5A", +"T@ c #517949", +"U@ c #212720", +"V@ c #0C160A", +"W@ c #1E5213", +"X@ c #30BA0C", +"Y@ c #33DD04", +"Z@ c #25890C", +"`@ c #0C2507", +" # c #10130F", +".# c #F6F6F5", +"+# c #262B25", +"@# c #5A8052", +"## c #79E05E", +"$# c #7BF957", +"%# c #6BC554", +"&# c #3E5639", +"*# c #131613", +"=# c #878787", +"-# c #050A04", +";# c #13350B", +"># c #299E0B", +",# c #32DA04", +"'# c #2BB208", +")# c #133D0A", +"!# c #0F160E", +"~# c #3E3E3E", +"{# c #E8E8E7", +"]# c #E8E8E6", +"^# c #AFAFAF", +"/# c #323D30", +"(# c #66A257", +"_# c #7AF458", +":# c #75F553", +"<# c #5EA44E", +"[# c #2F3D2C", +"}# c #0A0B0A", +"|# c #838383", +"1# c #585858", +"2# c #010201", +"3# c #091D06", +"4# c #20720B", +"5# c #30D004", +"6# c #2FCB04", +"7# c #1B610A", +"8# c #0F1A0D", +"9# c #404040", +"0# c #131513", +"a# c #3F513B", +"b# c #6BB957", +"c# c #75F752", +"d# c #6EDC50", +"e# c #4D7A43", +"f# c #212A20", +"g# c #808080", +"h# c #545454", +"i# c #040D02", +"j# c #143F0A", +"k# c #29A807", +"l# c #2FCA04", +"m# c #1F760A", +"n# c #142511", +"o# c #404240", +"p# c #E7E7E6", +"q# c #E6E6E4", +"r# c #3C3C3C", +"s# c #151515", +"t# c #222721", +"u# c #507348", +"v# c #6FD654", +"w# c #72F94D", +"x# c #64C14B", +"y# c #3B5836", +"z# c #161A15", +"A# c #7D7D7D", +"B# c #010400", +"C# c #0B2006", +"D# c #218109", +"E# c #2EC903", +"F# c #249407", +"G# c #163210", +"H# c #3A3D3A", +"I# c #565655", +"J# c #E5E5E4", +"K# c #CCCCCC", +"L# c #C1C1C1", +"M# c #B4B4B4", +"N# c #AAABA9", +"O# c #A8B5A5", +"P# c #92D084", +"Q# c #77F555", +"R# c #73F84E", +"S# c #84CE72", +"T# c #93A38F", +"U# c #8C8D8B", +"V# c #7E7E7E", +"W# c #797979", +"X# c #717171", +"Y# c #686868", +"Z# c #636363", +"`# c #424342", +" $ c #3A4538", +".$ c #337622", +"+$ c #2EBC08", +"@$ c #2DB00A", +"#$ c #2F5F23", +"$$ c #515750", +"%$ c #686867", +"&$ c #E1E1E0", +"*$ c #E3E3E2", +"=$ c #111111", +"-$ c #FBFDFA", +";$ c #EDF2EC", +">$ c #2E342D", +",$ c #575D56", +"'$ c #3F453E", +")$ c #2B322A", +"!$ c #2A3129", +"~$ c #2A3128", +"{$ c #293127", +"]$ c #A9B5A7", +"^$ c #466341", +"/$ c #66C050", +"($ c #6DFA47", +"_$ c #66E644", +":$ c #477D3C", +"<$ c #212A1F", +"[$ c #040403", +"}$ c #040504", +"|$ c #787978", +"1$ c #020302", +"2$ c #030801", +"3$ c #103807", +"4$ c #26A305", +"5$ c #2AB602", +"6$ c #1D6809", +"7$ c #283725", +"8$ c #3F443E", +"9$ c #CFD1CD", +"0$ c #D7D8D5", +"a$ c #323831", +"b$ c #E3F8DE", +"c$ c #CAEFC1", +"d$ c #6A9460", +"e$ c #7AA670", +"f$ c #6C9A62", +"g$ c #619057", +"h$ c #608F54", +"i$ c #5C8C51", +"j$ c #5A8C4E", +"k$ c #96CD89", +"l$ c #5EA44D", +"m$ c #69DF4A", +"n$ c #6AF945", +"o$ c #63C949", +"p$ c #45693D", +"q$ c #2C3B28", +"r$ c #1C2919", +"s$ c #1B2817", +"t$ c #1D2D1A", +"u$ c #7A8B76", +"v$ c #172614", +"w$ c #10190E", +"x$ c #152312", +"y$ c #1A2C15", +"z$ c #1C2C19", +"A$ c #1D291A", +"B$ c #1C2819", +"C$ c #172214", +"D$ c #152013", +"E$ c #515B4E", +"F$ c #111C0F", +"G$ c #111F0D", +"H$ c #15350D", +"I$ c #25850C", +"J$ c #2AB603", +"K$ c #218D05", +"L$ c #1E5111", +"M$ c #2B4D22", +"N$ c #0C2A04", +"O$ c #99B392", +"P$ c #AEBBA9", +"Q$ c #A6A7A5", +"R$ c #51644D", +"S$ c #B4F4A4", +"T$ c #9BF783", +"U$ c #88EC6D", +"V$ c #86EB6B", +"W$ c #81EC65", +"X$ c #7DE860", +"Y$ c #79E85B", +"Z$ c #75E757", +"`$ c #71E651", +" % c #79F159", +".% c #6BE84A", +"+% c #6DF649", +"@% c #6EF44A", +"#% c #64BB4E", +"$% c #4C7E3F", +"%% c #39652E", +"&% c #315C26", +"*% c #2E5822", +"=% c #2D5921", +"-% c #73A266", +";% c #2A591E", +">% c #2C5821", +",% c #3A6E2C", +"'% c #407C30", +")% c #427634", +"!% c #38632E", +"~% c #346029", +"{% c #325D26", +"]% c #305C24", +"^% c #59864D", +"/% c #2C591F", +"(% c #2B5A1E", +"_% c #28571B", +":% c #265919", +"<% c #2C7818", +"[% c #2CAB08", +"}% c #26A603", +"|% c #259506", +"1% c #288E0B", +"2% c #1E8404", +"3% c #42A029", +"4% c #5EA14B", +"5% c #90998D", +"6% c #4F624A", +"7% c #B0F49F", +"8% c #97F77E", +"9% c #84EB67", +"0% c #83EA67", +"a% c #7DEC60", +"b% c #77E75A", +"c% c #75E857", +"d% c #70E552", +"e% c #6DE64D", +"f% c #74F053", +"g% c #6BE44A", +"h% c #71EC52", +"i% c #6ACE51", +"j% c #569546", +"k% c #416E35", +"l% c #336128", +"m% c #315E24", +"n% c #305F24", +"o% c #2E5E21", +"p% c #BEBCCB", +"q% c #736F79", +"r% c #2F362E", +"s% c #DFF7DA", +"t% c #C4EEBA", +"u% c #619056", +"v% c #71A165", +"w% c #639558", +"x% c #5B8E4F", +"y% c #588D4C", +"z% c #558A49", +"A% c #538945", +"B% c #8DC67F", +"C% c #538A46", +"D% c #59914C", +"E% c #4F7846", +"F% c #405A3A", +"G% c #364A31", +"H% c #34482F", +"I% c #32472D", +"J% c #32482D", +"K% c #30462B", +"L% c #625B81", +"M% c #272534", +"N% c #0F100F", +"O% c #FAFDF9", +"P% c #E8EEE5", +"Q% c #2A3228", +"R% c #60685F", +"S% c #4C544A", +"T% c #424B41", +"U% c #434C42", +"V% c #4F584D", +"W% c #50594E", +"X% c #ABB5A9", +"Y% c #4C554A", +"Z% c #3F473D", +"`% c #373D36", +" & c #3B3E3A", +".& c #515450", +"+& c #525652", +"@& c #535652", +"#& c #CAC8D5", +"$& c #ECECEA", +"%& c #555655", +"&& c #383938", +"*& c #474847", +"=& c #626262", +"-& c #616161", +";& c #606060", +">& c #A7A3B8", +",& c #847F9C", +"'& c #736D8E", +")& c #DBDAE2", +"!& c #9691AB", +"~& c #EBEBE9", +"{& c #B8B5C6", +"]& c #E7E7E5", +"^& c #E4E4E3", +"/& c #E4E4E2", +"(& c #EDECF0", +"_& c #E5E5E3", +":& c #E6E6E5", +"<& c #E3E3E1", +"[& c #A9A9A7", +"}& c #A3A3A2", +"|& c #A3A3A1", +"1& c #E2E2E0", +"2& c #E1E1DF", +"3& c #9A9A9A", +"4& c #8C8C8C", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + @ ", +". # $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ % & * . ", +". $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = - % ; > . ", +". $ $ $ , $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = ' ) $ ! ~ . ", +". $ $ $ , $ $ $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = = = ' { $ $ ; ] ^ ", +". $ $ $ , $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = = = / / % ( $ / $ _ : < ", +". $ $ $ , $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = = / / / / / / [ } $ | 1 $ 2 3 . ", +". $ $ $ $ $ $ $ $ $ $ $ $ = = = = = = = = = = = = = / / / / / 4 1 1 1 5 6 7 8 2 ( 9 0 a . ", +". $ $ $ , $ $ $ $ $ $ = = = = = = = = = = = / / / / / / 4 1 1 1 1 1 b c d e f g h h i j . ", +". $ $ $ $ $ $ $ $ = = = = = = = = = = / / / / / 4 1 1 1 1 1 1 b - - k l m > n o p q r s . ", +". $ $ $ $ $ $ = = = = = = = = / / / / / 1 / / / / 1 1 b - - - - k t t | - ' ' u v 0 w q . ", +". $ $ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x y j . ", +". $ $ . z A q B C D E F G H e I J K L K M N h h O P Q R P S T U V W U V W X Y Z . m m ` . ", +". $ = . .B R Q h S ..+.@.#.$.%.&.$.*.=.-.$.;.>.$.@ *.,.'.>.).;.>.$.;.>.$.!.X X . ~.~.} . ", +". $ / . {.].U ;.^.. # . . . . . . /.^.^ (._.^ ^ :.^ :.^ ^ :.<.[.^.. . . . }.|.|.. 1.1.} . ", +". $ / . 2.3.@ ^.. . ) . . . . . :.4.5.6.7.8.9.0.a.b.c.d.e.f.g.h.i._.. . . j.k.k.. l.l.} . ", +". $ 1 . m.h ^.. . . n.. . . . _.o.p.q.r.s.t.u.v.w.x.y.z.A.B.C.D.E.F._.. . < @.@.. G.G.} . ", +". $ b . H.V . . . . I.. . . [.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z.`. +.+/.. ++!.@+. #+$+} . ", +". $ - . %+k.. . . . &+. . . j.*+=+-+;+>+,+'+R.)+!+~+{+W.]+^+/+(+_+:+<+[+. }+@+W . |+1+} . ", +". $ 2+. 3+4+. . . . M . . /.5+6+7+8+9+0+a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+. }+q+r+. s+s+} . ", +". $ k . E t+u+n.& 2 v+9 w+x+y+z+A+B+C+D+E+F+G+H+I+J+g.K+L+M+N+O+P+Q+R+S+T+U+V+W+. 7 X+} . ", +". $ t . Y+k.. . . . 8 . . < Z+`+ @.@+@@@#@^ :.^ $@^ :.:.:.%@&@*@=@-@;@>@,@'@)@!@. X+X+} . ", +". $ | . Z ~@. . . . > . . {@]@^@/@(@_@:@<@. . . . . . . . [@}@|@1@2@3@4@5@6@P 7@. 8@8@} . ", +". $ 9@. 0@#.. . . . a@. [.0.b@c@d@e@f@g@).. . . . . . . . . h@i@j@k@l@m@n@o@s p@. q@r@} . ", +". $ s@. t@#.. . . . -.. u@v@w@x@y@z@A@++D . . . . . . . . . B@C@D@E@F@G@H@I@J@R . K@L@} . ", +". $ % . M@!.. . . . N@/.O@P@Q@R@S@T@U@^.p . . . . . . . . . 0@V@W@X@Y@Z@`@ #J@t@. L@L@} . ", +". $ .#. U++ . . . . z [.+#@###$#%#&#*#. =#. . . . . . . . . U+-#;#>#,#'#)#!#~#R . {#]#} . ", +". $ x . t@#.. . . . ^#++/#(#_#:#<#[#}#. |#. . . . . . . . . 1#2#3#4#5#6#7#8#9#R . ]#]#} . ", +". $ c . t@#.. . . . 6 0#a#b#c#d#e#f#[.. g#. . . . . . . . . h#. i#j#k#l#m#n#o#U+. p#q#} . ", +". $ l . r#s#. . . . n t#u#v#w#x#y#z#/.. A#. . . . . . . . . e . B#C#D#E#F#G#H#I#. q#J#} . ", +"[@= 1.^ K#L#-.M#(.6 N#O#P#Q#R#S#T#U#W+V#W#Y+X#r Y#Z#3.t@!@Q J )@`# $.$+$@$#$$$%$. &$*$} . ", +"=$-$;$>$,$'$)$!$~${$]$^$/$($_$:$<$^ [$}$|$1$. . . . . . . . O . . 2$3$4$5$6$7$8$B#9$0$(.. ", +"a$b$c$d$e$f$g$h$i$j$k$l$m$n$o$p$q$r$s$t$u$v$w$x$y$z$A$B$C$D$E$w$F$G$H$I$J$K$L$M$N$O$P$Q$. ", +"R$S$T$U$V$W$X$Y$Z$`$ %.%+%@%#%$%%%&%*%=%-%;%>%,%'%)%!%~%{%]%^%/%(%_%:%<%[%}%|%1%2%3%4%5%. ", +"6%7%8%9%0%a%b%c%d%e%f%g%h%i%j%k%l%m%n%o%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p%q%", +"r%s%t%u%v%w%x%y%z%A%B%C%D%E%F%G%H%I%J%K%p%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%M%", +"N%O%P%Q%R%S%T%U%V%W%X%Y%Z%`% &.&+&+&@&.&p%L%L%L%#&L%L%#&L%L%#&L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%M%", +"/.= $&^ %&`#&&*&=&-&( ;&`#q+r#h#R 1#R 7@p%L%L%L%>&,&'&)&>&L%#&L%'&!&'&L%,&L%L%,&L%'&,&L%L%L%L%M%", +". $ ~&. . . . . . . . . . . . . . . . . p%L%L%L%!&!&!&!&#&L%#&L%#&!&)&L%#&L%'&{&,&#&>&{&L%L%L%M%", +". $ q@q@q@r@r@K@K@{#]#]#]&q#q#J#^&/&/&/&p%L%L%L%L%#&{&'&#&!&!&L%,&{&(&L%{&,&{&,&#&!&!&)&L%L%L%M%", +". $ r@K@K@K@K@{#]#]#p#p#]&]&q#q#_&_&/&/&p%L%L%L%L%#&#&L%#&{&'&,&#&'&#&L%'&{&#&L%#&!&!&!&L%L%L%M%", +". $ K@K@K@]#p#p#p#p#]&]&]&:&:&q#_&_&_&_&p%L%L%L%L%>&{&L%,&)&L%,&#&>&(&'&L%#&>&L%,&#&!&)&L%L%L%M%", +". $ L@p#p#p#p#]&]&]&:&:&:&q#_&_&_&^&^&/&p%L%L%L%L%'&'&L%L%,&L%L%,&,&'&'&L%,&'&L%L%'&!&L%L%L%L%M%", +". $ p#]&]&]&:&:&:&:&q#q#_&^&^&^&/&/&/&/&p%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%L%M%", +". $ ]&:&:&:&q#q#q#q#^&^&/&/&/&/&/&/&/&/&q%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%M%", +". $ :&q#q#q#q#J#^&/&/&/&/&/&/&/&/&/&/&<&<&[&: }&}&}&}&|&|&|& |&|&|&|&|&|&|&|&|&D . . . ", +". # q#q#q#_&/&/&/&/&/&/&/&/&/&/&*$<&<&<&<&<&<&<&<&1&1&1&1&2&2&2&2&2&2&2&2&2&2&2&2&2&2&3&. ", +". 9 } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } 3&4&. ", +" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ", +" ", +" ", +" "}; + +GdkPixmap *wave_alert_pixmap; +GdkBitmap *wave_alert_mask; void make_pixmaps(GtkWidget *window) @@ -235,4 +2797,14 @@ &style->bg[GTK_STATE_NORMAL], (gchar **)zoom_larrow); zoom_rarrow_pixmap=gdk_pixmap_create_from_xpm_d(window->window, &zoom_rarrow_mask, &style->bg[GTK_STATE_NORMAL], (gchar **)zoom_rarrow); + +prev_page_pixmap=gdk_pixmap_create_from_xpm_d(window->window, &prev_page_mask, + &style->bg[GTK_STATE_NORMAL], (gchar **)prev_page_xpm); +next_page_pixmap=gdk_pixmap_create_from_xpm_d(window->window, &next_page_mask, + &style->bg[GTK_STATE_NORMAL], (gchar **)next_page_xpm); + +wave_info_pixmap=gdk_pixmap_create_from_xpm_d(window->window, &wave_info_mask, + &style->bg[GTK_STATE_NORMAL], (gchar **)wave_info); +wave_alert_pixmap=gdk_pixmap_create_from_xpm_d(window->window, &wave_alert_mask, + &style->bg[GTK_STATE_NORMAL], (gchar **)wave_alert); } diff --git a/src/pixmaps.h b/src/pixmaps.h index 029d9ab..1e6dfdb 100644 --- a/src/pixmaps.h +++ b/src/pixmaps.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -33,4 +33,14 @@ extern GdkPixmap *zoom_rarrow_pixmap; extern GdkBitmap *zoom_rarrow_mask; +GdkPixmap *prev_page_pixmap; +GdkBitmap *prev_page_mask; +GdkPixmap *next_page_pixmap; +GdkBitmap *next_page_mask; + +GdkPixmap *wave_info_pixmap; +GdkBitmap *wave_info_mask; +GdkPixmap *wave_alert_pixmap; +GdkBitmap *wave_alert_mask; + #endif diff --git a/src/print.c b/src/print.c index bee350c..f9b14b8 100644 --- a/src/print.c +++ b/src/print.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2001. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free @@ -610,9 +610,9 @@ t = traces.first; trwhich = 0; while (t) { - if ((trwhich < trtarget) && (t->next)) { + if ((trwhich < trtarget) && (GiveNextTrace(t))) { trwhich++; - t = t->next; + t = GiveNextTrace(t); } else { break; } @@ -748,7 +748,7 @@ if (numchars > ps_nummaxchars) ps_nummaxchars = numchars; } - t = t->next; + t = GiveNextTrace(t); } maxlen += 6; /* endcap padding */ @@ -974,6 +974,18 @@ { gdouble pixstep; gint xl; + + if (tims.baseline != -1) { + if ((tims.baseline >= tims.start) && (tims.baseline <= tims.last) + && (tims.baseline <= tims.end)) { + pixstep = ((gdouble) nsperframe) / ((gdouble) pixelsperframe); + xl = ((gdouble) (tims.baseline - tims.start)) / pixstep; /* snap to integer */ + if ((xl >= 0) && (xl < wavewidth)) { + pr_setgray(prc, 0.65); + pr_draw_line(prc, xl, fontheight - 1, xl, liney_max); + } + } + } if (tims.marker != -1) { if ((tims.marker >= tims.start) && (tims.marker <= tims.last) @@ -1575,7 +1587,7 @@ } else { pr_draw_hptr_trace(prc, NULL, NULL, i, 0); } - t = t->next; + t = GiveNextTrace(t); } } pr_draw_named_markers(prc); @@ -1684,9 +1696,9 @@ t = traces.first; trwhich = 0; while (t) { - if ((trwhich < trtarget) && (t->next)) { + if ((trwhich < trtarget) && (GiveNextTrace(t))) { trwhich++; - t = t->next; + t = GiveNextTrace(t); } else { break; } @@ -1696,7 +1708,7 @@ if (t) { for (i = 0; (i < num_traces_displayable) && (t); i++) { pr_RenderSig(prc, t, i); - t = t->next; + t = GiveNextTrace(t); } } } diff --git a/src/rc.c b/src/rc.c index acfd6e0..5f6acbe 100644 --- a/src/rc.c +++ b/src/rc.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -27,11 +27,15 @@ #include "rc.h" #ifndef _MSC_VER +#ifndef __MINGW32__ #include #include static char *rcname=".gtkwaverc"; /* name of environment file--POSIX */ #else static char *rcname="gtkwave.ini"; /* name of environment file--WIN32 */ +#endif +#else + static char *rcname="gtkwave.ini"; /* name of environment file--WIN32 */ #define strcasecmp _stricmp #endif @@ -356,6 +360,13 @@ { DEBUG(printf("f_vcd_explicit_zero_subscripts(\"%s\")\n",str)); vcd_explicit_zero_subscripts=atoi_64(str)?0:-1; /* 0==yes, -1==no */ +return(0); +} + +static int f_vcd_preserve_glitches(char *str) +{ +DEBUG(printf("f_vcd_preserve_glitches(\"%s\")\n",str)); +vcd_preserve_glitches=atoi_64(str)?0:-1; /* 0==yes, -1==no */ return(0); } @@ -418,6 +429,7 @@ } color_make(back) +color_make(baseline) color_make(grid) color_make(high) color_make(low) @@ -446,6 +458,7 @@ { "autocoalesce_reversal", f_autocoalesce_reversal }, { "autoname_bundles", f_autoname_bundles }, { "color_back", f_color_back }, +{ "color_baseline", f_color_baseline }, { "color_grid", f_color_grid }, { "color_high", f_color_high }, { "color_low", f_color_low }, @@ -494,6 +507,7 @@ { "use_roundcaps", f_use_roundcaps }, { "use_scrollbar_only", f_use_scrollbar_only }, { "vcd_explicit_zero_subscripts", f_vcd_explicit_zero_subscripts }, +{ "vcd_preserve_glitches", f_vcd_preserve_glitches }, { "vector_padding", f_vector_padding }, { "wave_scrolling", f_wave_scrolling }, { "zoom_base", f_zoom_base }, @@ -512,7 +526,7 @@ /* good, we have a handle */ } else -#ifndef _MSC_VER +#if !defined __MINGW32__ && !defined _MSC_VER if(!(handle=fopen(rcname,"rb"))) { char *home; diff --git a/src/regex.c b/src/regex.c index 61ee13c..63ac310 100644 --- a/src/regex.c +++ b/src/regex.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -12,6 +12,11 @@ #include #include #else /* or for any other compiler that doesn't support POSIX.2 regexs properly like xlc or vc++ */ +#ifdef __MINGW32__ +#define bcopy(a,b,c) memcpy((b),(a),(c)) +#define bzero(a,b) memset((a),0,(b)) +#define bcmp(a,b,c) memcmp((a),(b),(c)) +#endif #ifdef _MSC_VER #include #define STDC_HEADERS @@ -20,7 +25,6 @@ #define REGEX_MAY_COMPILE #include "gnu_regex.c" #endif - static regex_t preg; static int regex_ok=0; @@ -49,3 +53,48 @@ return((rc)?0:1); } + +/* + * compile a regular expression and return the pointer to + * the regex_t if valid else return NULL + */ +void *wave_regex_alloc_compile(char *regex) +{ +regex_t *mreg = (regex_t *)malloc(sizeof(regex_t)); +int comp_rc=regcomp(mreg, regex, REG_ICASE|REG_NOSUB); + +if(comp_rc) + { + free(mreg); + mreg=NULL; + } + +return((void *)mreg); +} + + +/* + * do match + */ +int wave_regex_alloc_match(void *mreg, char *str) +{ +int rc=regexec((regex_t *)mreg, str, 0, NULL, 0); + +return((rc)?0:1); +} + + +/* + * free it + */ +void wave_regex_alloc_free(void *pnt) +{ +regex_t *mreg = (regex_t *)pnt; + +if(mreg) + { + regfree(mreg); + free(mreg); + } +} + diff --git a/src/renderopt.c b/src/renderopt.c index 3a91eb8..054cbc5 100644 --- a/src/renderopt.c +++ b/src/renderopt.c @@ -128,11 +128,11 @@ ps_fullpage=render_mutex[0]; if(target_mutex[0]) { - fileselbox("Print To PS File",&filesel_print_ps,ps_print_cleanup); + fileselbox("Print To PS File",&filesel_print_ps,GTK_SIGNAL_FUNC(ps_print_cleanup), GTK_SIGNAL_FUNC(NULL)); } else { - fileselbox("Print To MIF File (experimental)",&filesel_print_mif,mif_print_cleanup); + fileselbox("Print To MIF File (experimental)",&filesel_print_mif,GTK_SIGNAL_FUNC(mif_print_cleanup), GTK_SIGNAL_FUNC(NULL)); } } diff --git a/src/rgb.c b/src/rgb.c index 11f01f9..f6b60f4 100644 --- a/src/rgb.c +++ b/src/rgb.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -827,7 +827,7 @@ ((ch>='A')&&(ch<='F'))) continue; else { - #ifdef _MSC_VER + #if defined _MSC_VER || defined __MINGW32__ fprintf(stderr, "** gtkwave.ini (line %d): '%s' is an unknown color value; ignoring.\n", rc_line_no, str); #else fprintf(stderr, "** .gtkwaverc (line %d): '%s' is an unknown color value; ignoring.\n", rc_line_no, str); diff --git a/src/search.c b/src/search.c index e94d837..9a3e5c1 100644 --- a/src/search.c +++ b/src/search.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -8,6 +8,7 @@ */ #include +#include "gtk12compat.h" #include "analyzer.h" #include "aet.h" #include "vcd.h" @@ -35,7 +36,7 @@ static void enter_callback_e(GtkWidget *widget, GtkWidget *nothing) { - gchar *entry_text; + G_CONST_RETURN gchar *entry_text; int len; char *vname=""; entry_text = gtk_entry_get_text(GTK_ENTRY(entry_a)); @@ -187,7 +188,7 @@ DEBUG(printf("Selected_rows: %d\n",selected_rows)); if(selected_rows>0) { - entrybox_local("Enter Bundle Name",300,"",128,bundle_cleanup); + entrybox_local("Enter Bundle Name",300,"",128,GTK_SIGNAL_FUNC(bundle_cleanup)); } } @@ -477,7 +478,7 @@ { tfirst->flags |= TR_HIGHLIGHT; if(tfirst==tlast) break; - tfirst=tfirst->next; + tfirst=tfirst->t_next; } MaxSignalLength(); @@ -635,10 +636,10 @@ static void enter_callback(GtkWidget *widget, GtkWidget *do_warning) { GtkCList *cl; -gchar *entry_text; +G_CONST_RETURN gchar *entry_text; char *entry_suffixed; int len; -int i, j, k, row; +int i, row; int pixlen, maxpixlen; char *s, *tmp2; @@ -736,7 +737,7 @@ { char buf[256]; sprintf(buf, "Limiting results to first %d entries.", num_rows); - simplereqbox("Regex Search Warning",300,buf,"OK", NULL, NULL); + simplereqbox("Regex Search Warning",300,buf,"OK", NULL, NULL, 1); } } diff --git a/src/shiftbuttons.c b/src/shiftbuttons.c index 99a3684..6a4cb12 100644 --- a/src/shiftbuttons.c +++ b/src/shiftbuttons.c @@ -24,6 +24,9 @@ help_text( " scrolls the display window left one tick worth of data." " The net action is that the data scrolls right a tick." +#ifdef WAVE_USE_GTK2 + " Ctrl + Scrollwheel Up also performs this function." +#endif ); return; } @@ -57,6 +60,9 @@ help_text( " scrolls the display window right one tick worth of data." " The net action is that the data scrolls left a tick." +#ifdef WAVE_USE_GTK2 + " Ctrl + Scrollwheel Down also performs this function." +#endif ); return; } diff --git a/src/signalwindow.c b/src/signalwindow.c index 9bfa11f..a1513be 100644 --- a/src/signalwindow.c +++ b/src/signalwindow.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -82,7 +82,10 @@ gdouble x,y; GdkModifierType state; int doloop; + +#ifdef WAVE_USE_GTK2 gint xi, yi; +#endif if(event->is_hint) { @@ -100,7 +103,7 @@ /********************* button 1 *********************/ -if((traces.total)&&(state&(GDK_BUTTON1_MASK|GDK_BUTTON3_MASK))&&(signalpixmap)&&(cachedwhich!=-1)) +if((traces.visible)&&(state&(GDK_BUTTON1_MASK|GDK_BUTTON3_MASK))&&(signalpixmap)&&(cachedwhich!=-1)) { num_traces_displayable=widget->allocation.height/(fontheight); num_traces_displayable--; /* for the time trace that is always there */ @@ -108,15 +111,15 @@ which=(int)(y); which=(which/fontheight)-1; - if(which>=traces.total) - { - which=traces.total-1; + if(which>=traces.visible) + { + which=traces.visible-1; } wadj=GTK_ADJUSTMENT(wave_vslider); - if(num_traces_displayable=num_traces_displayable) { @@ -125,7 +128,7 @@ target=((int)wadj->value)+1; which=num_traces_displayable-1; - if(target+which>=(traces.total-1)) target=traces.total-which-1; + if(target+which>=(traces.visible-1)) target=traces.visible-which-1; wadj->value=target; if(cachedwhich==which) cachedwhich=which-1; /* force update */ @@ -164,10 +167,10 @@ trwhich=0; while(t) { - if((trwhichnext)) + if((trwhichnext; + t=GiveNextTrace(t); } else { @@ -234,12 +237,12 @@ if(which>cachedwhich) { which--; - t=t->prev; + t=GivePrevTrace(t); } else if(whichnext; + t=GiveNextTrace(t); } } while((which!=cachedwhich)&&(t)); @@ -313,7 +316,7 @@ GtkAdjustment *wadj; Trptr t; -if((traces.total)&&(signalpixmap)) +if((traces.visible)&&(signalpixmap)) { gdk_pointer_grab(widget->window, FALSE, GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON1_MOTION_MASK | GDK_BUTTON3_MOTION_MASK | @@ -325,7 +328,7 @@ which=(int)(event->y); which=(which/fontheight)-1; - if((which>=traces.total)||(which>=num_traces_displayable)||(which<0)) + if((which>=traces.visible)||(which>=num_traces_displayable)||(which<0)) { if(dnd_state==0)cachedwhich=-1; goto check_button_3; /* off in no man's land, but check 3rd anyways.. */ @@ -339,10 +342,10 @@ trwhich=0; while(t) { - if((trwhichnext)) + if((trwhichnext; + t=GiveNextTrace(t); } else { @@ -351,6 +354,21 @@ } cachedtrace=t; + + /* frankel add */ + if((event->state&GDK_CONTROL_MASK)&&(dnd_state==0)&&(event->button==1)) + if(t) + { + if(CollapseTrace(t)) + { + signalwindow_width_dirty=1; + MaxSignalLength(); + signalarea_configure_event(signalarea, NULL); + wavearea_configure_event(wavearea, NULL); + return(TRUE); + } + } + if((dnd_state==0)&&(event->button==1)) if(t) { @@ -374,11 +392,11 @@ { t2->flags = (t2->flags & (~TR_HIGHLIGHT)) | f; if(t2==t) break; - t2=t2->prev; + t2=GivePrevTrace(t2); } goto resync_signalarea; } - t2=t2->prev; + t2=GivePrevTrace(t2); } t2=shift_click_trace; @@ -392,11 +410,11 @@ { t2->flags = (t2->flags & (~TR_HIGHLIGHT)) | f; if(t2==t) break; - t2=t2->next; + t2=GiveNextTrace(t2); } goto resync_signalarea; } - t2=t2->next; + t2=GiveNextTrace(t2); } goto normal_button1_press; /* couldn't find original so make this original... */ @@ -459,6 +477,8 @@ int num_traces_displayable; int width; +UpdateTracesVisible(); + num_traces_displayable=widget->allocation.height/(fontheight); num_traces_displayable--; /* for the time trace that is always there */ @@ -505,16 +525,16 @@ wadj->page_size=wadj->page_increment=(gfloat) num_traces_displayable; wadj->step_increment=(gfloat)1.0; wadj->lower=(gfloat)0.0; -wadj->upper=(gfloat)traces.total; - -if(num_traces_displayable>traces.total) +wadj->upper=(gfloat)traces.visible; + +if(num_traces_displayable>traces.visible) { wadj->value=(gfloat)(trtarget=0); } else - if (wadj->value + num_traces_displayable > traces.total) - { - wadj->value=(gfloat)(trtarget=traces.total-num_traces_displayable); + if (wadj->value + num_traces_displayable > traces.visible) + { + wadj->value=(gfloat)(trtarget=traces.visible-num_traces_displayable); } gtk_signal_emit_by_name (GTK_OBJECT (wadj), "changed"); /* force bar update */ diff --git a/src/simplereq.c b/src/simplereq.c index be984ac..30b4830 100644 --- a/src/simplereq.c +++ b/src/simplereq.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -10,6 +10,7 @@ #include "gtk12compat.h" #include #include "debug.h" +#include "pixmaps.h" static GtkWidget *window; static void (*cleanup)(GtkWidget *, gpointer); @@ -31,18 +32,19 @@ } void simplereqbox(char *title, int width, char *default_text, - char *oktext, char *canceltext, GtkSignalFunc func) + char *oktext, char *canceltext, GtkSignalFunc func, int is_alert) { GtkWidget *vbox, *hbox; GtkWidget *button1, *button2; GtkWidget *label, *separator; + GtkWidget *pixmapwid1; cleanup=WAVE_GTK_SFUNCAST(func); /* create a new modal window */ window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_grab_add(window); - gtk_widget_set_usize( GTK_WIDGET (window), width, 55); + gtk_widget_set_usize( GTK_WIDGET (window), width, 55 + 52); gtk_window_set_title(GTK_WINDOW (window), title); gtk_signal_connect(GTK_OBJECT (window), "delete_event", (GtkSignalFunc) destroy_callback, NULL); @@ -55,6 +57,17 @@ label=gtk_label_new(default_text); gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0); gtk_widget_show (label); + + if(is_alert) + { + pixmapwid1=gtk_pixmap_new(wave_alert_pixmap, wave_alert_mask); + } + else + { + pixmapwid1=gtk_pixmap_new(wave_info_pixmap, wave_info_mask); + } + gtk_widget_show(pixmapwid1); + gtk_container_add (GTK_CONTAINER (vbox), pixmapwid1); separator = gtk_hseparator_new (); gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, TRUE, 0); diff --git a/src/status.c b/src/status.c index 2a2085d..d184d9a 100644 --- a/src/status.c +++ b/src/status.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -17,12 +17,21 @@ realized with gtk_widget_realize, but it would have to be part of a hierarchy first */ -static GtkWidget *text; +static GtkWidget *text=NULL; static GtkWidget *vscrollbar; void status_text(char *str) { -gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL, str, -1); +if(text) + { + gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL, str, -1); + } + else + { + int len = strlen(str); + char ch = len ? str[len-1] : 0; + fprintf(stderr, "GTKWAVE | %s%s", str, (ch=='\n') ? "" : "\n"); + } } void @@ -42,7 +51,12 @@ else if(is_lx2) { - status_text("LXT2 loaded successfully.\n"); + switch(is_lx2) + { + case LXT2_IS_LXT2: status_text("LXT2 loaded successfully.\n"); break; + case LXT2_IS_AET2: status_text("AET2 loaded successfully.\n"); break; + case LXT2_IS_VZT: status_text("VZT loaded successfully.\n"); break; + } } sprintf(buf,"[%d] facilities found.\n",numfacs); diff --git a/src/strace.c b/src/strace.c index f52ad2b..94639e3 100644 --- a/src/strace.c +++ b/src/strace.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2003. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -7,12 +7,14 @@ * of the License, or (at your option) any later version. */ +#include "gtk12compat.h" #include "strace.h" +#include "currenttime.h" TimeType *timearray=NULL; int timearray_size=0; -static GtkWidget *ptr_mark_count_label=NULL; /* pointer to mark count label on pattern search dialog */ +static GtkWidget *ptr_mark_count_label=NULL; /* pointer to mark count label on pattern search dialog */ struct strace *straces=NULL; /* when active, disables certain ops! */ struct strace *shadow_straces=NULL; @@ -35,6 +37,78 @@ char shadow_type = 0; char *shadow_string = NULL; +signed char mark_idx_start = 0; /* which start mark conditons were selected */ +signed char mark_idx_end = 0; /* which end mark conditons were selected */ +signed char shadow_mark_idx_start = 0; +signed char shadow_mark_idx_end = 0; + +struct item_mark_string { + char *str; + unsigned char idx; +}; + +static struct item_mark_string item_mark_start_strings[]= + { + { "Start of Time" }, + { "Named Marker A" }, + { "Named Marker B" }, + { "Named Marker C" }, + { "Named Marker D" }, + { "Named Marker E" }, + { "Named Marker F" }, + { "Named Marker G" }, + { "Named Marker H" }, + { "Named Marker I" }, + { "Named Marker J" }, + { "Named Marker K" }, + { "Named Marker L" }, + { "Named Marker M" }, + { "Named Marker N" }, + { "Named Marker O" }, + { "Named Marker P" }, + { "Named Marker Q" }, + { "Named Marker R" }, + { "Named Marker S" }, + { "Named Marker T" }, + { "Named Marker U" }, + { "Named Marker V" }, + { "Named Marker W" }, + { "Named Marker X" }, + { "Named Marker Y" }, + { "Named Marker Z" } + }; + +static struct item_mark_string item_mark_end_strings[]= + { + { "End of Time" }, + { "Named Marker A" }, + { "Named Marker B" }, + { "Named Marker C" }, + { "Named Marker D" }, + { "Named Marker E" }, + { "Named Marker F" }, + { "Named Marker G" }, + { "Named Marker H" }, + { "Named Marker I" }, + { "Named Marker J" }, + { "Named Marker K" }, + { "Named Marker L" }, + { "Named Marker M" }, + { "Named Marker N" }, + { "Named Marker O" }, + { "Named Marker P" }, + { "Named Marker Q" }, + { "Named Marker R" }, + { "Named Marker S" }, + { "Named Marker T" }, + { "Named Marker U" }, + { "Named Marker V" }, + { "Named Marker W" }, + { "Named Marker X" }, + { "Named Marker Y" }, + { "Named Marker Z" } + }; + /* * trap timescale overflows @@ -89,7 +163,6 @@ strace_defer_free_head = NULL; } - /* * button/menu/entry activations.. */ @@ -118,10 +191,31 @@ DEBUG(printf("Trace %s Search Type: %s\n", s->trace->name, stype[(int)s->value])); } +static void start_clicked(GtkWidget *widget, gpointer which) +{ +mark_idx_start=((struct item_mark_string*)which)->idx; +if (mark_idx_start<0 || mark_idx_start>=(sizeof(item_mark_start_strings)/sizeof(struct item_mark_string))) + { + fprintf(stderr, "Internal error: mark_idx_start out of range %d\n",mark_idx_start); + exit(255); + } +DEBUG(printf("start: %s\n", ((struct item_mark_string*)which)->str)); +} + +static void end_clicked(GtkWidget *widget, gpointer which) +{ +mark_idx_end=((struct item_mark_string*)which)->idx; +if (mark_idx_end<0 || mark_idx_end>=(sizeof(item_mark_end_strings)/sizeof(struct item_mark_string))) + { + fprintf(stderr, "Internal error: mark_idx_end out of range %d\n",mark_idx_end); + exit(255); + } +DEBUG(printf("end: %s\n", ((struct item_mark_string*)which)->str)); +} static void enter_callback(GtkWidget *widget, gpointer strace_tmp) { -gchar *entry_text; +G_CONST_RETURN gchar *entry_text; struct strace *s; int i, len; @@ -203,10 +297,7 @@ if(ptr_mark_count_label) { char mark_count_buf[64]; - if (timearray_size < 1) - mark_count_buf[0] = 0; - else - sprintf (mark_count_buf, "Mark Count: %d", timearray_size>=1 ? timearray_size-1 : 0); + sprintf (mark_count_buf, "Mark Count: %d", timearray_size); gtk_label_set_text (GTK_LABEL(ptr_mark_count_label), mark_count_buf); } } @@ -216,7 +307,7 @@ GtkWidget *menu, *menuitem, *optionmenu; GSList *group; GtkWidget *entry; - GtkWidget *vbox, *hbox, *small_hbox, *count_hbox, *vbox_g, *label; + GtkWidget *vbox, *hbox, *small_hbox, *vbox_g, *label; GtkWidget *button1, *button1a, *button1b, *button1c, *button2, *scrolled_win, *frame, *separator; Trptr t; int i; @@ -290,7 +381,7 @@ gtk_container_add (GTK_CONTAINER (frame), scrolled_win); gtk_container_add (GTK_CONTAINER (vbox), frame); - for(t=traces.first;t;t=t->next) + for(t=traces.first;t;t=t->t_next) { struct strace *s; @@ -359,15 +450,85 @@ gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_win), vbox_g); - do /* add a horizontal box to display the mark count */ - { - count_hbox = gtk_hbox_new (TRUE, 0); + do /* add GUI elements for displaying mark count and mark count start/end */ + { + int idx; + GtkWidget *ptr_mark_start_label, *ptr_mark_end_label; + GtkWidget *mark_count_hbox_start, *mark_count_hbox_end; + GtkWidget *count_vbox_left, *count_vbox_right, *count_vbox, *count_hbox; + GtkWidget *ptr_mark_count_start, *ptr_mark_count_end; + + count_hbox=gtk_hbox_new (TRUE, 0); gtk_widget_show (count_hbox); - gtk_box_pack_start (GTK_BOX (vbox), count_hbox, FALSE, FALSE, 0); - - ptr_mark_count_label = gtk_label_new (""); + gtk_box_pack_start (GTK_BOX(vbox),count_hbox,FALSE,FALSE,0); + + /* add a vertical box to display the mark count GUI elements */ + count_vbox_left=gtk_vbox_new (TRUE, 0); + gtk_widget_show (count_vbox_left); + gtk_box_pack_start (GTK_BOX(count_hbox),count_vbox_left,FALSE,FALSE,0); + count_vbox=gtk_vbox_new (TRUE, 0); + gtk_widget_show (count_vbox); + gtk_box_pack_start (GTK_BOX(count_hbox),count_vbox,FALSE,FALSE,0); + count_vbox_right=gtk_vbox_new (TRUE, 0); + gtk_widget_show (count_vbox_right); + gtk_box_pack_start (GTK_BOX(count_hbox),count_vbox_right,FALSE,FALSE,0); + + /* add mark start GUI element */ + mark_count_hbox_start=gtk_hbox_new (TRUE, 0); + gtk_widget_show (mark_count_hbox_start); + gtk_box_pack_start (GTK_BOX(count_vbox),mark_count_hbox_start,FALSE,FALSE,0); + ptr_mark_start_label=gtk_label_new ("Marking Begins at:"); + gtk_widget_show (ptr_mark_start_label); + gtk_box_pack_start (GTK_BOX (mark_count_hbox_start),ptr_mark_start_label,TRUE,FALSE,0); + ptr_mark_count_start = gtk_menu_new (); + group=NULL; + for(idx=0; idxvalue); - exit(0); + fprintf(stderr, "Internal error: st_type of %d\n",s->value); + exit(255); } @@ -770,8 +931,8 @@ break; default: - printf("Internal error: st_type of %d\n",s->value); - exit(0); + fprintf(stderr, "Internal error: st_type of %d\n",s->value); + exit(255); } free_2(chval); @@ -985,8 +1146,8 @@ break; default: - printf("Internal error: st_type of %d\n",s->value); - exit(0); + fprintf(stderr, "Internal error: st_type of %d\n",s->value); + exit(255); } @@ -1123,8 +1284,8 @@ break; default: - printf("Internal error: st_type of %d\n",s->value); - exit(0); + fprintf(stderr, "Internal error: st_type of %d\n",s->value); + exit(255); } free_2(chval); @@ -1188,6 +1349,7 @@ void strace_maketimetrace(int mode) { TimeType basetime=tims.first; +TimeType endtime =MAX_HISTENT_TIME; int i, notfirst=0; struct timechain *tchead=NULL, *tc=NULL; TimeType *t; @@ -1207,11 +1369,51 @@ return; /* merely free stuff up */ } -do +if(mark_idx_start>0) + { + if(named_markers[mark_idx_start-1]>=0) + basetime=named_markers[mark_idx_start-1]; + else + { + status_text(item_mark_start_strings[mark_idx_start].str); + status_text(" not in use.\n"); + } + } + +if(mark_idx_end>0) + { + if(named_markers[mark_idx_end-1]>=0) + endtime=named_markers[mark_idx_end-1]; + else + { + status_text(item_mark_end_strings[mark_idx_end].str); + status_text(" not in use.\n"); + } + } + +if(basetime>endtime) + { + TimeType tmp=basetime; + basetime =endtime; + endtime =tmp; + } + +while(1) { basetime=strace_timetrace(basetime, notfirst); notfirst=1; + if(endtime==MAX_HISTENT_TIME) + { + if(basetime==MAX_HISTENT_TIME) break; + } + else + { + if(basetime>=endtime) break; + } + + timearray_size++; + if(!tc) { tchead=tc=wave_alloca(sizeof(struct timechain)); @@ -1224,14 +1426,20 @@ tc->t=basetime; tc->next=NULL; - timearray_size++; - } while(basetime!=MAX_HISTENT_TIME); - -timearray=t=malloc_2(sizeof(TimeType)*timearray_size); -for(i=0;it; - tchead=tchead->next; + } + +if(timearray_size) + { + timearray=t=malloc_2(sizeof(TimeType)*timearray_size); + for(i=0;it; + tchead=tchead->next; + } + } + else + { + timearray = NULL; } if(!shadow_active) update_mark_count_label(); @@ -1245,6 +1453,7 @@ { struct strace *stemp; char logical_mutex_temp[6]; +char mark_idx_start_temp, mark_idx_end_temp; stemp = straces; straces = shadow_straces; @@ -1253,6 +1462,14 @@ memcpy(logical_mutex_temp, logical_mutex, 6); memcpy(logical_mutex, shadow_logical_mutex, 6); memcpy(shadow_logical_mutex, logical_mutex_temp, 6); + +mark_idx_start_temp = mark_idx_start; +mark_idx_start = shadow_mark_idx_start; +shadow_mark_idx_start = mark_idx_start_temp; + +mark_idx_end_temp = mark_idx_end; +mark_idx_end = shadow_mark_idx_end; +shadow_mark_idx_end = mark_idx_end_temp; } @@ -1269,6 +1486,9 @@ { shadow_logical_mutex[i] = 0; } + +shadow_mark_idx_start = 0; +shadow_mark_idx_end = 0; strace_cache = straces; /* so the trace actually deletes */ straces=NULL; @@ -1356,7 +1576,6 @@ void cache_actual_pattern_mark_traces(void) { Trptr t; -int i; unsigned int def=0; TimeType prevshift=LLDescriptor(0); struct strace *st; @@ -1365,7 +1584,7 @@ if(timearray) { - mprintf("!%d%d%d%d%d%d\n", logical_mutex[0], logical_mutex[1], logical_mutex[2], logical_mutex[3], logical_mutex[4], logical_mutex[5]); + mprintf("!%d%d%d%d%d%d%c%c\n", logical_mutex[0], logical_mutex[1], logical_mutex[2], logical_mutex[3], logical_mutex[4], logical_mutex[5], '@'+mark_idx_start, '@'+mark_idx_end); st=straces; while(st) diff --git a/src/strace.h b/src/strace.h index 593aec8..832056e 100644 --- a/src/strace.h +++ b/src/strace.h @@ -76,6 +76,8 @@ extern char logical_mutex[6], shadow_logical_mutex[6]; extern char shadow_active, shadow_type; extern char *shadow_string; +extern signed char mark_idx_start, mark_idx_end; +extern signed char shadow_mark_idx_start, shadow_mark_idx_end; extern struct mprintf_buff_t *mprintf_buff_head, *mprintf_buff_current; void strace_search(int direction); diff --git a/src/timeentry.c b/src/timeentry.c index 3327f65..faad7d8 100644 --- a/src/timeentry.c +++ b/src/timeentry.c @@ -8,6 +8,7 @@ */ #include +#include "gtk12compat.h" #include "aet.h" #include "debug.h" @@ -28,7 +29,7 @@ static void callback(GtkWidget *widget, GtkWidget *entry) { -gchar *entry_text; +G_CONST_RETURN gchar *entry_text; TimeType newlo; char fromstr[40]; @@ -64,7 +65,7 @@ static void callback2(GtkWidget *widget, GtkWidget *entry) { -gchar *entry_text; +G_CONST_RETURN gchar *entry_text; TimeType newhi; char tostr[40]; diff --git a/src/tree.c b/src/tree.c index 9f64ded..063adae 100644 --- a/src/tree.c +++ b/src/tree.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2001. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -96,7 +96,7 @@ t2=(struct tree *)calloc_2(1,sizeof(struct tree)); t->child=t2; - t2->parent=t; + /* t2->parent=t; */ t=t2; continue; @@ -123,7 +123,7 @@ t3=(struct tree *)calloc_2(1,sizeof(struct tree)); t->child=t3; - t3->parent=t; + /* t3->parent=t; */ t=t3; continue; @@ -179,7 +179,9 @@ { treedebug(t->child, s2); } - else + + if(t->which>=0) /* for when valid netnames like A.B.C, A.B.C.D exist (not legal excluding texsim) */ + /* otherwise this would be an 'else' */ { printf("%d) %s\n", t->which, s2); } @@ -192,8 +194,6 @@ static GtkCTreeNode *maketree_nodes(GtkCTreeNode *subtree, struct tree *t2, GtkCTreeNode *sibling, int mode) { -GtkWidget *titem; -GtkWidget *added; char *tmp, *tmp2, *tmp3; gchar *text [1]; @@ -327,7 +327,7 @@ if(nam) { t=nam; - while(ch=*(t++)) + while((ch=*(t++))) { if(ch==hier_delimeter) pnt=t; } @@ -335,3 +335,122 @@ return(pnt?pnt:nam); } + +/**********************************/ +/* Experimental treesorting code */ +/* (won't directly work with lxt2 */ +/* because alias hier is after */ +/* fac hier so fix with partial */ +/* mergesort...) */ +/**********************************/ + +/* + * sort the hier tree..should be faster than + * moving numfacs longer strings around + */ +int fast_tree_sort = 1; + +static int tree_qsort_cmp(const void *v1, const void *v2) +{ +struct tree *t1 = *(struct tree **)v1; +struct tree *t2 = *(struct tree **)v2; + +return(sigcmp(t2->name, t1->name)); /* because list must be in rvs */ +} + +void treesort(struct tree *t, struct tree *p) +{ +struct tree *it; +struct tree **srt; +int cnt; +int i; + +if(t->next) + { + it = t; + cnt = 0; + do { + cnt++; + it=it->next; + } while(it); + + srt = wave_alloca(cnt * sizeof(struct tree *)); + for(i=0;inext; + } + + qsort((void *)srt, cnt, sizeof(struct tree *), tree_qsort_cmp); + + if(p) + { + p->child = srt[0]; + } + else + { + treeroot = srt[0]; + } + + for(i=0;i<(cnt-1);i++) + { + srt[i]->next = srt[i+1]; + if(srt[i]->child) + { + treesort(srt[i]->child, srt[i]); + } + } + srt[i]->next = NULL; + if(srt[i]->child) + { + treesort(srt[i]->child, srt[i]); + } + } +else if (t->child) + { + treesort(t->child, t); + } +} + +static struct symbol **facs2; +static int facs2_pos; + +void order_facs_from_treesort_2(struct tree *t) +{ +while(t) + { + if(t->child) + { + order_facs_from_treesort_2(t->child); + } + + if(t->which>=0) /* for when valid netnames like A.B.C, A.B.C.D exist (not legal excluding texsim) */ + /* otherwise this would be an 'else' */ + { + facs2[facs2_pos--] = facs[t->which]; + } + + t=t->next; + } +} + + +void order_facs_from_treesort(struct tree *t, void *v) +{ +struct symbol ***f = (struct symbol ***)v; /* eliminate compiler warning in tree.h as aet.h refs tree.h */ + +facs2=(struct symbol **)malloc_2(numfacs*sizeof(struct symbol *)); +facs2_pos = numfacs-1; +order_facs_from_treesort_2(t); + +if(facs2_pos>=0) + { + fprintf(stderr, "Internal Error: facs2_pos = %d\n", facs2_pos); + fprintf(stderr, "[This is usually the result of multiply defined facilities.]\n"); + exit(255); + } + +free_2(*f); +*f = facs2; +facs2 = NULL; +} diff --git a/src/tree.h b/src/tree.h index c9884e3..058425e 100644 --- a/src/tree.h +++ b/src/tree.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -23,11 +23,13 @@ extern char hier_delimeter, hier_was_explicitly_set, alt_hier_delimeter; extern char hier_grouping; -extern struct tree *selectedtree; struct tree { +#if 0 struct tree *parent; /* null if toplevel */ +#endif + struct tree *next; struct tree *child; char *name; @@ -43,6 +45,8 @@ extern struct tree *treeroot; +extern int fast_tree_sort; /* won't work with lxt2 because of how aliasing stacks */ + /* names at the end of the main hierarchy 010104ajb */ void init_tree(void); void build_tree_from_name(char *s, int which); @@ -51,5 +55,7 @@ void maketree(GtkCTreeNode *subtree, struct tree *t); char *leastsig_hiername(char *nam); +void treesort(struct tree *t, struct tree *p); +void order_facs_from_treesort(struct tree *t, void *v); + #endif - diff --git a/src/treesearch.c b/src/treesearch.c index 6dd877d..37dd7e6 100644 --- a/src/treesearch.c +++ b/src/treesearch.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2004. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -8,6 +8,7 @@ */ #include +#include "gtk12compat.h" #include "analyzer.h" #include "tree.h" #include "aet.h" @@ -57,7 +58,7 @@ static void enter_callback_e(GtkWidget *widget, GtkWidget *nothing) { - gchar *entry_text; + G_CONST_RETURN gchar *entry_text; int len; entry_text = gtk_entry_get_text(GTK_ENTRY(entry_a)); DEBUG(printf("Entry contents: %s\n", entry_text)); @@ -139,7 +140,6 @@ /***************************************************************************/ static GtkWidget *window; -static GtkWidget *entry; static GtkWidget *tree; static char bundle_direction=0; static GtkSignalFunc cleanup; @@ -189,18 +189,18 @@ void fetchvex(struct tree *t, char direction) { if(t) -if(t->child) { - fetchvex2(t, direction, 0); + if(t->child) + { + fetchvex2(t, direction, 0); + } + else + { + add_vector_range(NULL, fetchlow(t)->which, + fetchhigh(t)->which, direction); + } } - else - { - add_vector_range(NULL, fetchlow(t)->which, - fetchhigh(t)->which, direction); - } -} - - +} /* call cleanup() on ok/insert functions */ @@ -255,7 +255,7 @@ { if(!autoname_bundles) { - entrybox_local("Enter Bundle Name",300,"",128,bundle_cleanup); + entrybox_local("Enter Bundle Name",300,"",128,GTK_SIGNAL_FUNC(bundle_cleanup)); } else { @@ -497,7 +497,7 @@ { tfirst->flags |= TR_HIGHLIGHT; if(tfirst==tlast) break; - tfirst=tfirst->next; + tfirst=tfirst->t_next; } MaxSignalLength(); diff --git a/src/vcd.c b/src/vcd.c index 62f3ca0..9db6de1 100644 --- a/src/vcd.c +++ b/src/vcd.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2001. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -33,6 +33,7 @@ char convert_to_reals=0; char atomic_vectors=1; char make_vcd_save_file=0; +char vcd_preserve_glitches=0; FILE *vcd_save_handle=NULL; static FILE *vcd_handle=NULL; @@ -52,7 +53,6 @@ static TimeType start_time=-1; static TimeType end_time=-1; static TimeType current_time=-1; -static TimeType time_scale=1; /* multiplier is 1, 10, 100 */ static int num_glitches=0; static int num_glitch_regions=0; @@ -272,7 +272,6 @@ struct vcdsymbol *v; struct vcdsymbol **pnt; unsigned int vcd_distance; -int i; if(sorted) { @@ -1617,7 +1616,7 @@ if((ch=='x')||(ch=='X')) heval=1; else heval=2; - if((n->curr->v.val!=heval)||(time==start_time)) /* same region == go skip */ + if((n->curr->v.val!=heval)||(time==start_time)||(vcd_preserve_glitches)) /* same region == go skip */ { if(n->curr->time==time) { @@ -1717,6 +1716,7 @@ (n->curr->v.vector&&vector&&(*(double *)n->curr->v.vector!=*(double *)vector)) ||(time==start_time) ||(!n->curr->v.vector) + ||(vcd_preserve_glitches) ) /* same region == go skip */ { if(n->curr->time==time) @@ -1773,6 +1773,7 @@ (n->curr->v.vector&&vector&&(strcmp(n->curr->v.vector,vector))) ||(time==start_time) ||(!n->curr->v.vector) + ||(vcd_preserve_glitches) ) /* same region == go skip */ { if(n->curr->time==time) @@ -1815,7 +1816,7 @@ static void add_tail_histents(void) { -int i,j; +int j; struct vcdsymbol *v; /* dump out any pending events 1st */ @@ -1890,12 +1891,13 @@ static void vcd_build_symbols(void) { -int i,j; +int j; int max_slen=-1; struct sym_chain *sym_chain=NULL, *sym_curr=NULL; int duphier=0; char hashdirty; struct vcdsymbol *v, *vprime; +char *str = NULL; v=vcdsymroot; while(v) @@ -1904,7 +1906,6 @@ int delta; { - char *str; int slen; int substnode; @@ -1936,7 +1937,7 @@ if(((v->size==1)||(!atomic_vectors))&&(v->vartype!=V_REAL)) { - struct symbol *s; + struct symbol *s = NULL; for(j=0;jsize;j++) { @@ -2169,7 +2170,6 @@ static void vcd_cleanup(void) { -int i; struct slist *s, *s2; struct vcdsymbol *v, *vt; @@ -2290,8 +2290,8 @@ if(vcd_save_handle) fclose(vcd_save_handle); -printf("["TTFormat"] start time.\n["TTFormat"] end time.\n", start_time*time_scale, end_time*time_scale); -if(num_glitches) printf("Warning: encountered %d glitch%s across %d glitch region%s.\n", +fprintf(stderr, "["TTFormat"] start time.\n["TTFormat"] end time.\n", start_time*time_scale, end_time*time_scale); +if(num_glitches) fprintf(stderr, "Warning: encountered %d glitch%s across %d glitch region%s.\n", num_glitches, (num_glitches!=1)?"es":"", num_glitch_regions, (num_glitch_regions!=1)?"s":""); diff --git a/src/vcd.h b/src/vcd.h index a613a6f..cf65116 100644 --- a/src/vcd.h +++ b/src/vcd.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -24,6 +24,7 @@ #include "aet.h" #include "alloca.h" #include "debug.h" +#include "tree.h" #define VCD_BSIZ 32768 /* size of getch() emulation buffer--this val should be ok */ #define VCD_INDEXSIZ (2 * 1024 * 1024) @@ -73,6 +74,7 @@ extern char autocoalesce; extern char autocoalesce_reversal; extern int vcd_explicit_zero_subscripts; /* 0=yes, -1=no */ +extern char vcd_preserve_glitches; extern char convert_to_reals; extern char atomic_vectors; extern char make_vcd_save_file; diff --git a/src/vzt.c b/src/vzt.c new file mode 100644 index 0000000..10fd981 --- /dev/null +++ b/src/vzt.c @@ -0,0 +1,694 @@ +/* + * Copyright (c) Tony Bybell 2003-2005. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + */ + +#include +#include "vzt.h" +#include "lx2.h" + +#ifndef _MSC_VER +#include +#endif + +#include +#include +#include +#include "aet.h" +#include "vcd.h" +#include "lxt.h" +#include "lxt2_read.h" +#include "vzt_read.h" +#include "debug.h" + + +/* + * globals + */ +static struct vzt_rd_trace *vzt=NULL; +static TimeType first_cycle, last_cycle, total_cycles; + +static struct lx2_entry *vzt_table = NULL; +static struct fac *mvlfacs=NULL; + + +/* + * mainline + */ +TimeType vzt_main(char *fname, char *skip_start, char *skip_end) +{ +int i; +struct Node *n; +struct symbol *s, *prevsymroot=NULL, *prevsym=NULL; +signed char scale; +unsigned int numalias = 0; + +vzt = vzt_rd_init_smp(fname, num_cpus); +if(!vzt) + { + fprintf(stderr, "Could not initialize '%s', exiting.\n", fname); + exit(0); + } + +vzt_rd_process_blocks_linearly(vzt, 1); +/* vzt_rd_set_max_block_mem_usage(vzt, 0); */ + +scale=(signed char)vzt_rd_get_timescale(vzt); +exponent_to_time_scale(scale); + +numfacs=vzt_rd_get_num_facs(vzt); +mvlfacs=(struct fac *)calloc_2(numfacs,sizeof(struct fac)); +vzt_table=(struct lx2_entry *)calloc_2(numfacs, sizeof(struct lx2_entry)); + +for(i=0;i1) + { + free_2(mvlfacs[i-2].name); + mvlfacs[i-2].name = NULL; + } + + if(mvlfacs[i].flags&VZT_RD_SYM_F_ALIAS) + { + int alias = mvlfacs[i].array_height; + f=mvlfacs+alias; + + while(f->flags&VZT_RD_SYM_F_ALIAS) + { + f=mvlfacs+f->array_height; + } + + numalias++; + } + else + { + f=mvlfacs+i; + } + + if((f->len>1)&& (!(f->flags&(VZT_RD_SYM_F_INTEGER|VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) ) + { + sprintf(buf, "%s[%d:%d]", mvlfacs[i].name,mvlfacs[i].msb, mvlfacs[i].lsb); + str=malloc_2(strlen(buf)+1); + if(!alt_hier_delimeter) + { + strcpy(str, buf); + } + else + { + strcpy_vcdalt(str, buf, alt_hier_delimeter); + } + s=symadd_name_exists(str,hash(str)); + prevsymroot = prevsym = NULL; + } + else if ( + ((f->len==1)&&(!(f->flags&(VZT_RD_SYM_F_INTEGER|VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING)))&& + ((i!=numfacs-1)&&(!strcmp(mvlfacs[i].name, mvlfacs[i+1].name)))) + || + (((i!=0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) && + (mvlfacs[i].msb!=-1)&&(mvlfacs[i].lsb!=-1)) + ) + { + sprintf(buf, "%s[%d]", mvlfacs[i].name,mvlfacs[i].msb); + str=malloc_2(strlen(buf)+1); + if(!alt_hier_delimeter) + { + strcpy(str, buf); + } + else + { + strcpy_vcdalt(str, buf, alt_hier_delimeter); + } + s=symadd_name_exists(str,hash(str)); + if((prevsym)&&(i>0)&&(!strcmp(mvlfacs[i].name, mvlfacs[i-1].name))) /* allow chaining for search functions.. */ + { + prevsym->vec_root = prevsymroot; + prevsym->vec_chain = s; + s->vec_root = prevsymroot; + prevsym = s; + } + else + { + prevsymroot = prevsym = s; + } + } + else + { + str=malloc_2(strlen(mvlfacs[i].name)+1); + if(!alt_hier_delimeter) + { + strcpy(str, mvlfacs[i].name); + } + else + { + strcpy_vcdalt(str, mvlfacs[i].name, alt_hier_delimeter); + } + s=symadd_name_exists(str,hash(str)); + prevsymroot = prevsym = NULL; + + if(f->flags&VZT_RD_SYM_F_INTEGER) + { + mvlfacs[i].msb=31; + mvlfacs[i].lsb=0; + mvlfacs[i].len=32; + } + } + + if(!firstnode) + { + firstnode=curnode=s; + } + else + { + curnode->nextinaet=s; + curnode=s; + } + + n=(struct Node *)calloc_2(1,sizeof(struct Node)); + n->nname=s->name; + n->mvlfac = mvlfacs+i; + mvlfacs[i].working_node = n; + + if((f->len>1)||(f->flags&&(VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) + { + ExtNode *ext = (ExtNode *)calloc_2(1,sizeof(struct ExtNode)); + ext->msi = mvlfacs[i].msb; + ext->lsi = mvlfacs[i].lsb; + n->ext = ext; + } + + n->head.time=-1; /* mark 1st node as negative time */ + n->head.v.val=1; + s->n=n; + } + +for(i=0;((i<2)&&(iname))>longestname) longestname=len; + curnode=curnode->nextinaet; + } + + if(numalias) + { + unsigned int idx_lft = 0; + unsigned int idx_lftmax = numfacs - numalias; + unsigned int idx_rgh = numfacs - numalias; + struct symbol **facs_merge=(struct symbol **)malloc_2(numfacs*sizeof(struct symbol *)); + + fprintf(stderr, VZT_RDLOAD"Merging in %d aliases.\n", numalias); + + for(i=0;iname, facs[idx_rgh]->name) <= 0) + { + facs_merge[i] = facs[idx_lft++]; + + if(idx_lft == idx_lftmax) + { + for(i++;iname, i); + } + treeprune(treeroot); + + fprintf(stderr, VZT_RDLOAD"Sorting facility hierarchy tree.\n"); + treesort(treeroot, NULL); + order_facs_from_treesort(treeroot, &facs); + + facs_are_sorted=1; + } + else + { + curnode=firstnode; + for(i=0;iname))>longestname) longestname=len; + curnode=curnode->nextinaet; + while((ch=(*subst))) + { + if(ch==hier_delimeter) { *subst=0x01; } /* forces sort at hier boundaries */ + subst++; + } + } + + fprintf(stderr, VZT_RDLOAD"Sorting facilities at hierarchy boundaries.\n"); + wave_heapsort(facs,numfacs); + + for(i=0;iname; + while((ch=(*subst))) + { + if(ch==0x01) { *subst=hier_delimeter; } /* restore back to normal */ + subst++; + } + } + + facs_are_sorted=1; + + fprintf(stderr, VZT_RDLOAD"Building facility hierarchy tree.\n"); + + init_tree(); + for(i=0;iname, i); + } + treeprune(treeroot); + } + +min_time = first_cycle; max_time=last_cycle; +is_lx2 = LXT2_IS_VZT; + +if(skip_start || skip_end) + { + TimeType b_start, b_end; + + if(!skip_start) b_start = min_time; else b_start = unformat_time(skip_start, time_dimension); + if(!skip_end) b_end = max_time; else b_end = unformat_time(skip_end, time_dimension); + + if(b_startmax_time) b_start = max_time; + + if(b_endmax_time) b_end = max_time; + + if(b_start > b_end) + { + TimeType tmp_time = b_start; + b_start = b_end; + b_end = tmp_time; + } + + if(!vzt_rd_limit_time_range(vzt, b_start, b_end)) + { + fprintf(stderr, VZT_RDLOAD"--begin/--end options yield zero blocks, ignoring.\n"); + vzt_rd_unlimit_time_range(vzt); + } + else + { + min_time = b_start; + max_time = b_end; + } + } + +return(max_time); +} + + +/* + * vzt callback (only does bits for now) + */ +static void vzt_callback(struct vzt_rd_trace **lt, lxtint64_t *time, lxtint32_t *facidx, char **value) +{ +struct HistEnt *htemp = histent_calloc(); +struct lx2_entry *l2e = vzt_table+(*facidx); +struct fac *f = mvlfacs+(*facidx); + +/* fprintf(stderr, "%Ld %d %s\n", *time, *facidx, *value); */ + +if(!(f->flags&(VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) + { + if(f->len>1) + { + htemp->v.vector = (char *)malloc_2(f->len); + memcpy(htemp->v.vector, *value, f->len); + } + else + { + switch(**value) + { + case '0': htemp->v.val = 0; break; + case '1': htemp->v.val = 3; break; + case 'Z': + case 'z': htemp->v.val = 2; break; + default: htemp->v.val = 1; break; + } + } + } +else if(f->flags&VZT_RD_SYM_F_DOUBLE) + { + double *d = malloc_2(sizeof(double)); + sscanf(*value, "%lg", d); + htemp->v.vector = (char *)d; + htemp->flags = HIST_REAL; + } +else /* string */ + { + char *s = malloc_2(strlen(*value)+1); + strcpy(s, *value); + htemp->v.vector = s; + htemp->flags = HIST_REAL|HIST_STRING; + } + + +htemp->time = (*time) * (time_scale); + +if(l2e->histent_head) + { + l2e->histent_curr->next = htemp; + l2e->histent_curr = htemp; + } + else + { + l2e->histent_head = l2e->histent_curr = htemp; + } + +l2e->numtrans++; +} + + +/* + * this is the black magic that handles aliased signals... + */ +static void vzt_resolver(nptr np, nptr resolve) +{ +np->ext = resolve->ext; +memcpy(&np->head, &resolve->head, sizeof(struct HistEnt)); +np->curr = resolve->curr; +np->harray = resolve->harray; +np->numhist = resolve->numhist; +np->mvlfac=NULL; +} + + + +/* + * actually import a vzt trace but don't do it if it's already been imported + */ +void import_vzt_trace(nptr np) +{ +struct HistEnt *htemp, *histent_tail; +int len, i; +struct fac *f; +int txidx; +nptr nold = np; + +if(!(f=np->mvlfac)) return; /* already imported */ + +txidx = f - mvlfacs; +if(np->mvlfac->flags&VZT_RD_SYM_F_ALIAS) + { + txidx = vzt_rd_get_alias_root(vzt, txidx); + np = mvlfacs[txidx].working_node; + + if(!(f=np->mvlfac)) + { + vzt_resolver(nold, np); + return; /* already imported */ + } + } + +fprintf(stderr, "Import: %s\n", np->nname); + +/* new stuff */ +len = np->mvlfac->len; + +if(f->array_height <= 1) /* sorry, arrays not supported, but vzt doesn't support them yet either */ + { + vzt_rd_set_fac_process_mask(vzt, txidx); + vzt_rd_iter_blocks(vzt, vzt_callback, NULL); + vzt_rd_clr_fac_process_mask(vzt, txidx); + } + +histent_tail = htemp = histent_calloc(); +if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 2; + } + else + { + htemp->v.val = 2; /* z */ + } +htemp->time = MAX_HISTENT_TIME; + +htemp = histent_calloc(); +if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 1; + } + else + { + htemp->v.val = 1; /* x */ + } +htemp->time = MAX_HISTENT_TIME-1; +htemp->next = histent_tail; + +if(vzt_table[txidx].histent_curr) + { + vzt_table[txidx].histent_curr->next = htemp; + htemp = vzt_table[txidx].histent_head; + } + +if(!(f->flags&(VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) + { + if(len>1) + { + np->head.v.vector = (char *)malloc_2(len); + for(i=0;ihead.v.vector[i] = 1; + } + else + { + np->head.v.val = 1; /* x */ + } + } + else + { + np->head.flags = HIST_REAL; + if(f->flags&VZT_RD_SYM_F_STRING) np->head.flags |= HIST_STRING; + } + +np->head.time = -2; +np->head.next = htemp; +np->numhist=vzt_table[txidx].numtrans +2 /*endcap*/ +1 /*frontcap*/; + +memset(vzt_table+txidx, 0, sizeof(struct lx2_entry)); /* zero it out */ + +np->curr = histent_tail; +np->mvlfac = NULL; /* it's imported and cached so we can forget it's an mvlfac now */ + +if(nold!=np) + { + vzt_resolver(nold, np); + } +} + + +/* + * pre-import many traces at once so function above doesn't have to iterate... + */ +void vzt_set_fac_process_mask(nptr np) +{ +struct fac *f; +int txidx; + +if(!(f=np->mvlfac)) return; /* already imported */ + +txidx = f-mvlfacs; + +if(np->mvlfac->flags&VZT_RD_SYM_F_ALIAS) + { + txidx = vzt_rd_get_alias_root(vzt, txidx); + np = mvlfacs[txidx].working_node; + + if(!(np->mvlfac)) return; /* already imported */ + } + +if(np->mvlfac->array_height <= 1) /* sorry, arrays not supported, but vzt doesn't support them yet either */ + { + vzt_rd_set_fac_process_mask(vzt, txidx); + vzt_table[txidx].np = np; + } +} + + +void vzt_import_masked(void) +{ +int txidx, i, cnt; + +cnt = 0; +for(txidx=0;txidx100) + { + fprintf(stderr, VZT_RDLOAD"Extracting %d traces\n", cnt); + } + + +vzt_rd_iter_blocks(vzt, vzt_callback, NULL); + +for(txidx=0;txidxlen; + nptr np = vzt_table[txidx].np; + + histent_tail = htemp = histent_calloc(); + if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 2; + } + else + { + htemp->v.val = 2; /* z */ + } + htemp->time = MAX_HISTENT_TIME; + + htemp = histent_calloc(); + if(len>1) + { + htemp->v.vector = (char *)malloc_2(len); + for(i=0;iv.vector[i] = 1; + } + else + { + htemp->v.val = 1; /* x */ + } + htemp->time = MAX_HISTENT_TIME-1; + htemp->next = histent_tail; + + if(vzt_table[txidx].histent_curr) + { + vzt_table[txidx].histent_curr->next = htemp; + htemp = vzt_table[txidx].histent_head; + } + + if(!(f->flags&(VZT_RD_SYM_F_DOUBLE|VZT_RD_SYM_F_STRING))) + { + if(len>1) + { + np->head.v.vector = (char *)malloc_2(len); + for(i=0;ihead.v.vector[i] = 1; + } + else + { + np->head.v.val = 1; /* x */ + } + } + else + { + np->head.flags = HIST_REAL; + if(f->flags&VZT_RD_SYM_F_STRING) np->head.flags |= HIST_STRING; + } + + np->head.time = -2; + np->head.next = htemp; + np->numhist=vzt_table[txidx].numtrans +2 /*endcap*/ +1 /*frontcap*/; + + memset(vzt_table+txidx, 0, sizeof(struct lx2_entry)); /* zero it out */ + + np->curr = histent_tail; + np->mvlfac = NULL; /* it's imported and cached so we can forget it's an mvlfac now */ + vzt_rd_clr_fac_process_mask(vzt, txidx); + } + } +} diff --git a/src/vzt.h b/src/vzt.h new file mode 100644 index 0000000..9a773d1 --- /dev/null +++ b/src/vzt.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) Tony Bybell 2003-2004. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + */ + +#ifndef WAVE_VZTRDR_H +#define WAVE_VZTRDR_H + +#ifndef _MSC_VER +#include +#endif + +#include "vcd.h" + +extern unsigned char is_lx2; + +TimeType vzt_main(char *fname, char *skip_start, char *skip_end); +void import_vzt_trace(nptr np); +void vzt_set_fac_process_mask(nptr np); +void vzt_import_masked(void); + +#endif diff --git a/src/vzt_read.c b/src/vzt_read.c new file mode 120000 index 0000000..a1c7c58 --- /dev/null +++ b/src/vzt_read.c @@ -0,0 +1 @@ +helpers/vzt_read.c \ No newline at end of file diff --git a/src/vzt_read.h b/src/vzt_read.h new file mode 120000 index 0000000..ac29110 --- /dev/null +++ b/src/vzt_read.h @@ -0,0 +1 @@ +helpers/vzt_read.h \ No newline at end of file diff --git a/src/wavewindow.c b/src/wavewindow.c index 67e4d72..ace2ef3 100644 --- a/src/wavewindow.c +++ b/src/wavewindow.c @@ -1,5 +1,5 @@ /* - * Copyright (c) Tony Bybell 1999-2001. + * Copyright (c) Tony Bybell 1999-2005. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License @@ -67,6 +67,7 @@ static char made_gc_contexts=0; static GdkGC *gc_back =NULL; +static GdkGC *gc_baseline=NULL; static GdkGC *gc_grid =NULL; static GdkGC *gc_time =NULL; static GdkGC *gc_timeb =NULL; @@ -85,6 +86,80 @@ static const GdkModifierType bmask[4]= {0, GDK_BUTTON1_MASK, 0, GDK_BUTTON3_MASK }; /* button 1, 3 press/rel encodings */ static const GdkModifierType m_bmask[4]= {0, GDK_BUTTON1_MOTION_MASK, 0, GDK_BUTTON3_MOTION_MASK }; /* button 1, 3 motion encodings */ +/******************************************************************/ + +/* + * gtk_draw_line() acceleration for win32 by doing draw combining + */ +#if defined __MINGW32__ || defined _MSC_VER + +#define WAVE_SEG_BUF_CNT 1024 + +static int seg_trans_cnt=0, seg_low_cnt=0, seg_high_cnt=0, seg_mid_cnt=0; +static GdkSegment seg_trans[WAVE_SEG_BUF_CNT], seg_low[WAVE_SEG_BUF_CNT], seg_high[WAVE_SEG_BUF_CNT], seg_mid[WAVE_SEG_BUF_CNT]; + + +static void wave_gdk_draw_line(GdkDrawable *drawable, GdkGC *gc, gint x1, gint y1, gint x2, gint y2) +{ +GdkSegment *seg; +int *seg_cnt; + +if(gc==gc_trans) { seg = seg_trans; seg_cnt = &seg_trans_cnt; } +else if(gc==gc_low) { seg = seg_low; seg_cnt = &seg_low_cnt; } +else if(gc==gc_high) { seg = seg_high; seg_cnt = &seg_high_cnt; } +else if(gc==gc_mid) { seg = seg_mid; seg_cnt = &seg_mid_cnt; } +else { gdk_draw_line(drawable, gc, x1, y1, x2, y2); return; } + +seg[*seg_cnt].x1 = x1; +seg[*seg_cnt].y1 = y1; +seg[*seg_cnt].x2 = x2; +seg[*seg_cnt].y2 = y2; +(*seg_cnt)++; +if(*seg_cnt == WAVE_SEG_BUF_CNT) + { + gdk_draw_segments(drawable, gc, seg, *seg_cnt); + *seg_cnt = 0; + } +} + +static void wave_gdk_draw_line_flush(GdkDrawable *drawable) +{ +if(seg_mid) + { + gdk_draw_segments(drawable, gc_mid, seg_mid, seg_mid_cnt); + seg_mid_cnt = 0; + } + +if(seg_high) + { + gdk_draw_segments(drawable, gc_high, seg_high, seg_high_cnt); + seg_high_cnt = 0; + } + +if(seg_low) + { + gdk_draw_segments(drawable, gc_low, seg_low, seg_low_cnt); + seg_low_cnt = 0; + } + +if(seg_trans) + { + gdk_draw_segments(drawable, gc_trans, seg_trans, seg_trans_cnt); + seg_trans_cnt = 0; + } +} + +#else + +/* completely unnecessary for linux */ + +#define wave_gdk_draw_line(a,b,c,d,e,f) gdk_draw_line(a,b,c,d,e,f) +#define wave_gdk_draw_line_flush(x) + +#endif + +/******************************************************************/ + /* * aldec-like "snap" feature... @@ -112,7 +187,7 @@ for(i=0;inext; + t=GiveNextTrace(t); } if((!t)||(t->flags&(TR_BLANK|TR_EXCLUDE))) return(marker); @@ -223,7 +298,25 @@ gdouble pixstep; gint xl; +if(!wavearea->window) return; + m1x=m2x=-1; + +if(tims.baseline>=0) + { + if((tims.baseline>=tims.start)&&(tims.baseline<=tims.last) + &&(tims.baseline<=tims.end)) + { + pixstep=((gdouble)nsperframe)/((gdouble)pixelsperframe); + xl=((gdouble)(tims.baseline-tims.start))/pixstep; /* snap to integer */ + if((xl>=0)&&(xlwindow, + gc_baseline, + xl, fontheight-1, xl, waveheight-1); + } + } + } if(tims.marker>=0) { @@ -333,6 +426,12 @@ gdk_draw_pixmap(wavearea->window, wavearea->style->fg_gc[GTK_WIDGET_STATE(wavearea)], wavepixmap, m2x+1, 0, m2x+1, 0, wavewidth-m2x-1, waveheight); } + } + +/* keep baseline from getting obliterated */ +if(tims.baseline>=0) + { + draw_marker(); } } @@ -455,7 +554,7 @@ signalarea->allocation.width, signalarea->allocation.height); } -static void button_motion_common(gint xin, gint yin, int pressrel) +static void button_motion_common(gint xin, gint yin, int pressrel, int is_button_2) { gdouble x,offset,pixstep; TimeType newcurr; @@ -485,14 +584,24 @@ newcurr=tims.start; } -update_markertime(tims.marker=cook_markertime(time_trunc(newcurr), xin, yin)); -if(tims.lmbcache<0) tims.lmbcache=time_trunc(newcurr); - -draw_marker_partitions(); - -if((pressrel)||(constant_marker_update)) - { - button_press_release_common(); +if(!is_button_2) + { + update_markertime(tims.marker=cook_markertime(time_trunc(newcurr), xin, yin)); + if(tims.lmbcache<0) tims.lmbcache=time_trunc(newcurr); + + draw_marker_partitions(); + + if((pressrel)||(constant_marker_update)) + { + button_press_release_common(); + } + } + else + { + tims.baseline = ((tims.baseline<0)||(is_button_2<0)) ? cook_markertime(time_trunc(newcurr), xin, yin) : -1; + update_basetime(tims.baseline); + update_markertime(tims.marker); + wavearea_configure_event(wavearea, NULL); } } @@ -502,7 +611,10 @@ GdkModifierType state; TimeType newcurr; int scrolled; + +#ifdef WAVE_USE_GTK2 gint xi, yi; +#endif if(event->is_hint) { @@ -520,63 +632,69 @@ { scrolled=0; if(state&bmask[in_button_press]) /* needed for retargeting in AIX/X11 */ - if(x<0) - { - if(wave_scrolling) - if(tims.start>tims.first) - { - if(nsperframe<10) - { - tims.start-=nsperframe; + { + if(x<0) + { + if(wave_scrolling) + if(tims.start>tims.first) + { + if(nsperframe<10) + { + tims.start-=nsperframe; + } + else + { + tims.start-=(nsperframe/10); + } + if(tims.startvalue= + tims.marker=time_trunc(tims.timecache=tims.start); + + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); + scrolled=1; + } + x=0; + } + else + if(x>wavewidth) + { + if(wave_scrolling) + if(tims.start!=tims.last) + { + gfloat pageinc; + + pageinc=(gfloat)(((gdouble)wavewidth)*nspx); + + if(nsperframe<10) + { + tims.start+=nsperframe; + } + else + { + tims.start+=(nsperframe/10); + } + + if(tims.start>tims.last-pageinc+1) tims.start=time_trunc(tims.last-pageinc+1); + if(tims.starttims.last) tims.marker=tims.last; + + GTK_ADJUSTMENT(wave_hslider)->value=tims.timecache=tims.start; + + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); + scrolled=1; } - else - { - tims.start-=(nsperframe/10); - } - if(tims.startvalue= - tims.marker=time_trunc(tims.timecache=tims.start); - - gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); - gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); - scrolled=1; - } - x=0; - } - else - if(x>wavewidth) - { - if(wave_scrolling) - if(tims.start!=tims.last) - { - gfloat pageinc; - - pageinc=(gfloat)(((gdouble)wavewidth)*nspx); - - if(nsperframe<10) - { - tims.start+=nsperframe; - } - else - { - tims.start+=(nsperframe/10); - } - - if(tims.start>tims.last-pageinc+1) tims.start=time_trunc(tims.last-pageinc+1); - if(tims.starttims.last) tims.marker=tims.last; - - GTK_ADJUSTMENT(wave_hslider)->value=tims.timecache=tims.start; - - gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); - gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); - scrolled=1; - } - x=wavewidth-1; - } - + x=wavewidth-1; + } + } + else if((state&GDK_BUTTON2_MASK)&&(tims.baseline>=0)) + { + button_motion_common(x,y,0,-1); /* neg one says don't clear tims.baseline */ + } + pixstep=((gdouble)nsperframe)/((gdouble)pixelsperframe); newcurr=tims.start+(offset=x*pixstep); if((offset-((int)offset))>0.5) /* round to nearest integer ns */ @@ -594,7 +712,7 @@ if(state&bmask[in_button_press]) { - button_motion_common(x,y,0); + button_motion_common(x,y,0,0); } if(scrolled) /* make sure counters up top update.. */ @@ -612,6 +730,34 @@ return(TRUE); } + +#ifdef WAVE_USE_GTK2 +static gint +scroll_event( GtkWidget * widget, GdkEventScroll * event ) +{ + DEBUG(printf("Mouse Scroll Event\n")); + switch ( event->direction ) + { + case GDK_SCROLL_UP: + if ( event->state & GDK_CONTROL_MASK ) + service_left_shift(NULL, 0); + else if ( event->state & GDK_MOD1_MASK ) + service_zoom_out(NULL, 0); + else + service_left_page(NULL, 0); + break; + case GDK_SCROLL_DOWN: + if ( event->state & GDK_CONTROL_MASK ) + service_right_shift(NULL, 0); + else if ( event->state & GDK_MOD1_MASK ) + service_zoom_in(NULL, 0); + else + service_right_page(NULL, 0); + break; + } + return(TRUE); +} +#endif static gint button_press_event(GtkWidget *widget, GdkEventButton *event) { @@ -620,7 +766,7 @@ in_button_press=event->button; DEBUG(printf("Button Press Event\n")); - button_motion_common(event->x,event->y,1); + button_motion_common(event->x,event->y,1,0); tims.timecache=tims.start; gdk_pointer_grab(widget->window, FALSE, @@ -629,6 +775,11 @@ GDK_BUTTON_RELEASE_MASK, NULL, NULL, event->time); } +else +if(event->button==2) + { + button_motion_common(event->x,event->y,1,1); + } return(TRUE); } @@ -640,7 +791,7 @@ in_button_press=0; DEBUG(printf("Button Release Event\n")); - button_motion_common(event->x,event->y,1); + button_motion_common(event->x,event->y,1,0); tims.timecache=tims.start; gdk_pointer_ungrab(event->time); @@ -682,6 +833,7 @@ if(!made_gc_contexts) { gc_back = alloc_color(wavearea, color_back, wavearea->style->white_gc); + gc_baseline = alloc_color(wavearea, color_baseline, wavearea->style->bg_gc[GTK_STATE_SELECTED]); gc_grid = alloc_color(wavearea, color_grid, wavearea->style->bg_gc[GTK_STATE_PRELIGHT]); gc_time = alloc_color(wavearea, color_time, wavearea->style->black_gc); gc_timeb = alloc_color(wavearea, color_timeb, wavearea->style->bg_gc[GTK_STATE_ACTIVE]); @@ -701,18 +853,20 @@ } if(wavewidth>1) -if(!do_initial_zoom_fit) - { - calczoom(tims.zoom); - fix_wavehadj(); - gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); /* force zoom update */ - gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); /* force zoom update */ - } - else - { - do_initial_zoom_fit=0; - service_zoom_fit(NULL,NULL); - } + { + if(!do_initial_zoom_fit) + { + calczoom(tims.zoom); + fix_wavehadj(); + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); /* force zoom update */ + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); /* force zoom update */ + } + else + { + do_initial_zoom_fit=0; + service_zoom_fit(NULL,NULL); + } + } /* tims.timecache=tims.laststart; */ return(TRUE); @@ -742,6 +896,9 @@ gtk_widget_show(wavearea); gtk_widget_set_events(wavearea, +#ifdef WAVE_USE_GTK2 + GDK_SCROLL_MASK | +#endif GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK @@ -758,6 +915,12 @@ gtk_signal_connect(GTK_OBJECT(wavearea), "button_release_event", GTK_SIGNAL_FUNC(button_release_event), NULL); +#ifdef WAVE_USE_GTK2 +gtk_signal_connect(GTK_OBJECT(wavearea), "scroll_event", + GTK_SIGNAL_FUNC(scroll_event), NULL); +GTK_WIDGET_SET_FLAGS( wavearea, GTK_CAN_FOCUS ); +#endif + gtk_table_attach (GTK_TABLE (table), wavearea, 0, 9, 0, 9, GTK_FILL | GTK_EXPAND, GTK_FILL | GTK_EXPAND | GTK_SHRINK, 3, 3); @@ -821,10 +984,10 @@ trwhich=0; while(t) { - if((trwhichnext)) + if((trwhichnext; + t=GiveNextTrace(t); } else { @@ -838,7 +1001,7 @@ for(i=0;(inext; + t=GiveNextTrace(t); } } @@ -949,6 +1112,8 @@ { if(t->name) { + int comment_color = (t->flags&TR_COLLAPSED) ? GTK_STATE_INSENSITIVE : GTK_STATE_SELECTED; + if(bufxlen) { int baselen=gdk_string_measure(signalfont, t->name); @@ -956,14 +1121,14 @@ gdk_draw_string(signalpixmap, signalfont, - signalarea->style->bg_gc[GTK_STATE_SELECTED], + signalarea->style->bg_gc[comment_color], left_justify_sigs?3:3+max_signal_name_pixel_width- combined, texty, t->name); gdk_draw_string(signalpixmap, signalfont, - signalarea->style->bg_gc[GTK_STATE_SELECTED], + signalarea->style->bg_gc[comment_color], left_justify_sigs?3+baselen:3+max_signal_name_pixel_width- bufxlen, texty, @@ -973,7 +1138,7 @@ { gdk_draw_string(signalpixmap, signalfont, - signalarea->style->bg_gc[GTK_STATE_SELECTED], + signalarea->style->bg_gc[comment_color], left_justify_sigs?3:3+max_signal_name_pixel_width- gdk_string_measure(signalfont, t->name), texty, @@ -1078,7 +1243,7 @@ len=gdk_string_measure(signalfont, t->name); if(len>maxlen) maxlen=len; } - t=t->next; + t=GiveNextTrace(t); } else if(t->name) @@ -1199,11 +1364,11 @@ } } - t=t->next; + t=GiveNextTrace(t); } else { - t=t->next; + t=GiveNextTrace(t); } } @@ -1217,26 +1382,28 @@ if(signal_pixmap_width<60) signal_pixmap_width=60; if(!in_button_press) -if(!do_resize_signals) - { - int os; - os=30; - gtk_widget_set_usize(GTK_WIDGET(signalwindow), - os+30, -1); - } -else -if((do_resize_signals)&&(signalwindow)) - { - int oldusize; - - oldusize=signalwindow->allocation.width; - if(oldusize!=max_signal_name_pixel_width) + { + if(!do_resize_signals) { int os; - os=max_signal_name_pixel_width; - os=(os<30)?30:os; + os=48; gtk_widget_set_usize(GTK_WIDGET(signalwindow), os+30, -1); + } + else + if((do_resize_signals)&&(signalwindow)) + { + int oldusize; + + oldusize=signalwindow->allocation.width; + if(oldusize!=max_signal_name_pixel_width) + { + int os; + os=max_signal_name_pixel_width; + os=(os<48)?48:os; + gtk_widget_set_usize(GTK_WIDGET(signalwindow), + os+30, -1); + } } } } @@ -1576,7 +1743,7 @@ { draw_hptr_trace(NULL,NULL,i,0); } - t=t->next; + t=GiveNextTrace(t); } } @@ -1597,7 +1764,6 @@ TimeType tim, h2tim; hptr h2, h3; char hval, h2val, invert; -int last=-1; GdkGC *c; tims.start-=shift_timebase; @@ -1675,7 +1841,7 @@ switch(hval) { case 0: /* 0 */ - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_low, x0, y0, x1, y0); @@ -1683,8 +1849,8 @@ if(h2tim<=tims.end) switch(h2val) { - case 2: gdk_draw_line(wavepixmap, c, x1, y0, x1, yu); break; - default: gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); break; + case 2: wave_gdk_draw_line(wavepixmap, c, x1, y0, x1, yu); break; + default: wave_gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); break; } break; @@ -1701,42 +1867,42 @@ gc_xfill, TRUE, x0+1, y1, x1-x0, y0-y1+1); } - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_x, x0, y0, x1, y0); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_x, x0, y1, x1, y1); - if(h2tim<=tims.end) gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); + if(h2tim<=tims.end) wave_gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); break; case 2: /* Z */ - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_mid, x0, yu, x1, yu); if(h2tim<=tims.end) switch(h2val) { - case 0: gdk_draw_line(wavepixmap, c, x1, yu, x1, y0); break; - case 3: gdk_draw_line(wavepixmap, c, x1, yu, x1, y1); break; - default: gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); break; + case 0: wave_gdk_draw_line(wavepixmap, c, x1, yu, x1, y0); break; + case 3: wave_gdk_draw_line(wavepixmap, c, x1, yu, x1, y1); break; + default: wave_gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); break; } break; case 3: /* 1 */ - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_high, x0, y1, x1, y1); if(h2tim<=tims.end) switch(h2val) { - case 0: gdk_draw_line(wavepixmap, c, x1, y1, x1, y0); break; - case 2: gdk_draw_line(wavepixmap, c, x1, y1, x1, yu); break; - default: gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); break; + case 0: wave_gdk_draw_line(wavepixmap, c, x1, y1, x1, y0); break; + case 2: wave_gdk_draw_line(wavepixmap, c, x1, y1, x1, yu); break; + default: wave_gdk_draw_line(wavepixmap, c, x1, y0, x1, y1); break; } /* fallthrough on break */ default: @@ -1745,7 +1911,7 @@ } else { - gdk_draw_line(wavepixmap, gc_trans, x1, y0, x1, y1); + wave_gdk_draw_line(wavepixmap, gc_trans, x1, y0, x1, y1); newtime=(((gdouble)(x1+WAVE_OPT_SKIP))*nspx)+tims.start+shift_timebase; /* skip to next pixel */ h3=bsearch_node(t->n.nd,newtime); if(h3->time>h->time) @@ -1757,6 +1923,8 @@ h=h->next; } + +wave_gdk_draw_line_flush(wavepixmap); /* clear out state */ tims.start+=shift_timebase; tims.end+=shift_timebase; @@ -1835,49 +2003,49 @@ { if (type == 2) { if (lasttype != -1) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0-1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0, yu, x0-1, y1); } } else if (lasttype==2) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0+1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0, yu, x0+1, y1); } else { if (lasttype != type) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0-1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0, yu, x0-1, y1); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0+1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0, yu, x0+1, y1); } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0-2, y0, x0+2, y1); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0+2, y0, x0-2, y1); @@ -1886,7 +2054,7 @@ } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0, y0, x0, y1); @@ -1899,14 +2067,14 @@ { if(use_roundcaps) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_mid, x0+1, yu, x1-1, yu); } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_mid, x0, yu, x1, yu); @@ -1925,22 +2093,22 @@ if(use_roundcaps) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0+2, y0, x1-2, y0); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0+2, y1, x1-2, y1); } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0, y0, x1, y0); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0, y1, x1, y1); @@ -2011,6 +2179,8 @@ h=h->next; lasttype=type; } + +wave_gdk_draw_line_flush(wavepixmap); tims.start+=shift_timebase; tims.end+=shift_timebase; @@ -2093,11 +2263,11 @@ { if (lasttype != -1) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0-1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0, yu, x0-1, y1); @@ -2106,11 +2276,11 @@ else if (lasttype==2) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0+1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0, yu, x0+1, y1); @@ -2119,30 +2289,30 @@ { if (lasttype != type) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0-1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (lasttype==1? gc_x:gc_vtrans), x0, yu, x0-1, y1); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0+1, y0, x0, yu); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0, yu, x0+1, y1); } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0-2, y0, x0+2, y1); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0+2, y0, x0-2, y1); @@ -2151,7 +2321,7 @@ } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, (type==1? gc_x:gc_vtrans), x0, y0, x0, y1); @@ -2163,14 +2333,14 @@ { if(use_roundcaps) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_mid, x0+1, yu, x1-1, yu); } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, gc_mid, x0, yu, x1, yu); @@ -2189,22 +2359,22 @@ if(use_roundcaps) { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0+2, y0, x1-2, y0); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0+2, y1, x1-2, y1); } else { - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0, y0, x1, y0); - gdk_draw_line(wavepixmap, + wave_gdk_draw_line(wavepixmap, c, x0, y1, x1, y1); @@ -2262,621 +2432,8 @@ h=h->next; } +wave_gdk_draw_line_flush(wavepixmap); + tims.start+=shift_timebase; tims.end+=shift_timebase; } - -/********************************************************************************************************/ - -/* - * convert trptr+vptr into an ascii string - */ -char *convert_ascii(Trptr t, vptr v) -{ -Ulong flags; -int nbits; -unsigned char *bits; -char *os, *pnt, *newbuff; -int i, j, len; -char xtab[4]; - -static char xfwd[4]={0,1,2,3}; -static char xrev[4]={3,1,2,0}; - -flags=t->flags; -nbits=t->n.vec->nbits; -bits=v->v; - -if(flags&TR_INVERT) - { - memcpy(xtab,xrev,4); - } - else - { - memcpy(xtab,xfwd,4); - } - -newbuff=(char *)malloc_2(nbits+6); /* for justify */ -if(flags&TR_REVERSE) - { - char *fwdpnt, *revpnt; - - fwdpnt=bits; - revpnt=newbuff+nbits+6; - for(i=0;i<3;i++) *(--revpnt)=xtab[0]; - for(i=0;i 0x7f || !isprint(val)) *pnt++ = '.'; else *pnt++ = val; - found=1; - } - - parse+=8; - } - if (!found && !show_base) { - *(pnt++)='"'; - *(pnt++)='"'; - } - - if(show_base) { *(pnt++)='"'; } - *(pnt++)=0x00; - } -else if((flags&TR_HEX)||((flags&(TR_DEC|TR_SIGNED))&&(nbits>64))) - { - char *parse; - - len=(nbits/4)+2+1; /* $xxxxx */ - os=pnt=(char *)calloc_2(1,len); - if(show_base) { *(pnt++)='$'; } - - parse=(flags&TR_RJUSTIFY)?(newbuff+((nbits+3)&3)):(newbuff+3); - - for(i=0;in.nd->ext->msi-t->n.nd->ext->lsi; - if(nbits<0)nbits=-nbits; - nbits++; - res = 3; - for (i = 0; i < nbits; i++) - switch (*vec) { - case 1: - case 'x': - case 'X': - return(1); - case 2: - case 'z': - case 'Z': - if (res == 0) return(1); vec++; res = 2; break; - default: if (res == 2) return(1); vec++; res = 0; break; - } - - return(res); -} - -int vtype2(Trptr t, vptr v) -{ - int i, nbits, res; - char *vec=v->v; - - if (vec == NULL) - return(1); - nbits=t->n.vec->nbits; - res = 3; - for (i = 0; i < nbits; i++) - { - switch (*vec) - { - case 1: - case 'x': - case 'X': - return(1); - case 2: - case 'z': - case 'Z': - if (res == 0) return(1); vec++; res = 2; break; - default: if (res == 2) return(1); vec++; res = 0; break; - } - } - - return(res); -} - -/* - * convert trptr+hptr vectorstring into an ascii string - */ -char *convert_ascii_vec(Trptr t, char *vec) -{ -Ulong flags; -int nbits; -char *bits; -char *os, *pnt, *newbuff; -int i, j, len; -char xtab[4]; - -static char xfwd[4]={0,1,2,3}; -static char xrev[4]={3,1,2,0}; - -flags=t->flags; - -nbits=t->n.nd->ext->msi-t->n.nd->ext->lsi; -if(nbits<0)nbits=-nbits; -nbits++; - -if(vec) - { - bits=vec; - if(*vec>3) /* convert as needed */ - for(i=0;i 0x7f || !isprint(val)) *pnt++ = '.'; else *pnt++ = val; - found=1; - } - - parse+=8; - } - if (!found && !show_base) { - *(pnt++)='"'; - *(pnt++)='"'; - } - - if(show_base) { *(pnt++)='"'; } - *(pnt++)=0x00; - } -else if((flags&TR_HEX)||((flags&(TR_DEC|TR_SIGNED))&&(nbits>64))) - { - char *parse; - - len=(nbits/4)+2+1; /* $xxxxx */ - os=pnt=(char *)calloc_2(1,len); - if(show_base) { *(pnt++)='$'; } - - parse=(flags&TR_RJUSTIFY)?(newbuff+((nbits+3)&3)):(newbuff+3); - - for(i=0;i=0)&&(tims.marker>=0)) + { + service_dragzoom(tims.baseline, tims.marker); /* new semantics added to zoom between the two */ + } + else + { + if(wavewidth>4) { fixedwidth=wavewidth-4; } else { fixedwidth=wavewidth; } + estimated=-log(((gdouble)(tims.last-tims.first+1))/((gdouble)fixedwidth)*((gdouble)200.0))/log(zoombase); + if(estimated>((gdouble)(0.0))) estimated=((gdouble)(0.0)); + + tims.prevzoom=tims.zoom; + tims.timecache=0; + + calczoom(estimated); + tims.zoom=estimated; + + fix_wavehadj(); + + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); /* force zoom update */ + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); /* force zoom update */ + } + +DEBUG(printf("Zoombuttons Fit\n")); +} + +void service_zoom_full(GtkWidget *text, gpointer data) +{ +gdouble estimated; +int fixedwidth; + +if(helpbox_is_active) + { + help_text_bold("\n\nZoom Full"); + help_text( + " attempts a \"best fit\" to get the whole trace onscreen." + " Note that the trace may be more or less than a whole screen since" " this isn't a \"perfect fit.\"" ); return; @@ -235,19 +285,19 @@ if(wavewidth>4) { fixedwidth=wavewidth-4; } else { fixedwidth=wavewidth; } estimated=-log(((gdouble)(tims.last-tims.first+1))/((gdouble)fixedwidth)*((gdouble)200.0))/log(zoombase); if(estimated>((gdouble)(0.0))) estimated=((gdouble)(0.0)); - + tims.prevzoom=tims.zoom; tims.timecache=0; - + calczoom(estimated); tims.zoom=estimated; fix_wavehadj(); - + gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "changed"); /* force zoom update */ gtk_signal_emit_by_name (GTK_OBJECT (GTK_ADJUSTMENT(wave_hslider)), "value_changed"); /* force zoom update */ - -DEBUG(printf("Zoombuttons Fit\n")); + +DEBUG(printf("Zoombuttons Full\n")); } @@ -275,17 +325,20 @@ tims.prevzoom=tims.zoom; tims.timecache=tims.laststart=tims.start=time_trunc(time1); - for(t=traces.first;t;t=t->next) /* have to nuke string refs so printout is ok! */ + for(t=traces.first;t;t=t->t_next) /* have to nuke string refs so printout is ok! */ { if(t->asciivalue) { free_2(t->asciivalue); t->asciivalue=NULL; } } - for(t=traces.buffer;t;t=t->next) + for(t=traces.buffer;t;t=t->t_next) { if(t->asciivalue) { free_2(t->asciivalue); t->asciivalue=NULL; } } - update_markertime(tims.marker=-1); + if(!((tims.baseline>=0)&&(tims.marker>=0))) + { + update_markertime(tims.marker=-1); + } signalwindow_width_dirty=1; MaxSignalLength();