Compare commits

...

7 Commits

Author SHA1 Message Date
Mark Adler
e0ff940e1a zlib 1.2.3.8 2011-09-09 23:27:17 -07:00
Mark Adler
7df877eccd zlib 1.2.3.7 2011-09-09 23:27:08 -07:00
Mark Adler
dc5a43ebfa zlib 1.2.3.6 2011-09-09 23:26:58 -07:00
Mark Adler
d004b04783 zlib 1.2.3.5 2011-09-09 23:26:49 -07:00
Mark Adler
f6194ef39a zlib 1.2.3.4 2011-09-09 23:26:40 -07:00
Mark Adler
639be99788 zlib 1.2.3.3 2011-09-09 23:26:29 -07:00
Mark Adler
d6231142d2 zlib 1.2.3.2 2011-09-09 23:25:38 -07:00
133 changed files with 15055 additions and 4411 deletions

180
CMakeLists.txt Normal file
View File

@@ -0,0 +1,180 @@
cmake_minimum_required(VERSION 2.4.4)
set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS ON)
project(zlib C)
if(NOT DEFINED BUILD_SHARED_LIBS)
option(BUILD_SHARED_LIBS "Build a shared library form of zlib" ON)
endif()
include(CheckTypeSize)
include(CheckFunctionExists)
include(CheckIncludeFile)
include(CheckCSourceCompiles)
enable_testing()
check_include_file(sys/types.h HAVE_SYS_TYPES_H)
check_include_file(stdint.h HAVE_STDINT_H)
check_include_file(stddef.h HAVE_STDDEF_H)
#
# Check to see if we have large file support
#
set(CMAKE_REQUIRED_DEFINITIONS -D_LARGEFILE64_SOURCE)
# We add these other definitions here because CheckTypeSize.cmake
# in CMake 2.4.x does not automatically do so and we want
# compatibility with CMake 2.4.x.
if(HAVE_SYS_TYPES_H)
list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_SYS_TYPES_H)
endif()
if(HAVE_STDINT_H)
list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDINT_H)
endif()
if(HAVE_STDDEF_H)
list(APPEND CMAKE_REQUIRED_DEFINITIONS -DHAVE_STDDEF_H)
endif()
check_type_size(off64_t OFF64_T)
if(HAVE_OFF64_T)
add_definitions(-D_LARGEFILE64_SOURCE)
endif()
set(CMAKE_REQUIRED_DEFINITIONS) # clear variable
#
# Check for fseeko
#
check_function_exists(fseeko HAVE_FSEEKO)
if(NOT HAVE_FSEEKO)
add_definitions(-DNO_FSEEKO)
endif()
#
# Check for unistd.h
#
check_include_file(unistd.h HAVE_UNISTD_H)
#
# Check for errno.h
check_include_file(errno.h HAVE_ERRNO_H)
if(NOT HAVE_ERRNO_H)
add_definitions(-DNO_ERRNO_H)
endif()
if(MSVC)
set(CMAKE_DEBUG_POSTFIX "d")
add_definitions(-D_CRT_SECURE_NO_DEPRECATE)
add_definitions(-D_CRT_NONSTDC_NO_DEPRECATE)
endif()
#============================================================================
# zlib
#============================================================================
set(ZLIB_PUBLIC_HDRS
zconf.h
zlib.h
)
set(ZLIB_PRIVATE_HDRS
crc32.h
deflate.h
gzguts.h
inffast.h
inffixed.h
inflate.h
inftrees.h
trees.h
zutil.h
)
set(ZLIB_SRCS
adler32.c
compress.c
crc32.c
deflate.c
gzclose.c
gzio.c
gzlib.c
gzread.c
gzwrite.c
inflate.c
infback.c
inftrees.c
inffast.c
trees.c
uncompr.c
zutil.c
win32/zlib1.rc
)
# parse the full version number from zlib.h and include in ZLIB_FULL_VERSION
file(READ ${CMAKE_CURRENT_SOURCE_DIR}/zlib.h _zlib_h_contents)
string(REGEX REPLACE ".*#define[ \t]+ZLIB_VERSION[ \t]+\"([0-9A-Za-z.]+)\".*"
"\\1" ZLIB_FULL_VERSION ${_zlib_h_contents})
if(MINGW)
# This gets us DLL resource information when compiling on MinGW.
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj
COMMAND windres.exe
-D GCC_WINDRES
-I ${CMAKE_CURRENT_SOURCE_DIR}
-o ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj
-i ${CMAKE_CURRENT_SOURCE_DIR}/win32/zlib1.rc)
set(ZLIB_SRCS ${ZLIB_SRCS} ${CMAKE_CURRENT_BINARY_DIR}/zlib1rc.obj)
endif(MINGW)
add_library(zlib ${ZLIB_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS})
set_target_properties(zlib PROPERTIES DEFINE_SYMBOL ZLIB_DLL)
set_target_properties(zlib PROPERTIES SOVERSION 1)
if(NOT CYGWIN)
# This property causes shared libraries on Linux to have the full version
# encoded into their final filename. We disable this on Cygwin because
# it causes cygz-${ZLIB_FULL_VERSION}.dll to be created when cygz.dll
# seems to be the default.
#
# This has no effect with MSVC, on that platform the version info for
# the DLL comes from the resource file win32/zlib1.rc
set_target_properties(zlib PROPERTIES VERSION ${ZLIB_FULL_VERSION})
endif()
if(UNIX)
# On unix-like platforms the library is almost always called libz
set_target_properties(zlib PROPERTIES OUTPUT_NAME z)
elseif(BUILD_SHARED_LIBS AND WIN32)
# Creates zlib1.dll when building shared library version
set_target_properties(zlib PROPERTIES SUFFIX "1.dll")
endif()
if(NOT SKIP_INSTALL_LIBRARIES AND NOT SKIP_INSTALL_ALL )
install(TARGETS zlib
RUNTIME DESTINATION bin
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib )
endif()
if(NOT SKIP_INSTALL_HEADERS AND NOT SKIP_INSTALL_ALL )
install(FILES ${ZLIB_PUBLIC_HDRS} DESTINATION include)
endif()
if(NOT SKIP_INSTALL_FILES AND NOT SKIP_INSTALL_ALL )
install(FILES zlib.3 DESTINATION share/man/man3)
endif()
#============================================================================
# Example binaries
#============================================================================
add_executable(example example.c)
target_link_libraries(example zlib)
add_test(example example)
add_executable(minigzip minigzip.c)
target_link_libraries(minigzip zlib)
if(HAVE_OFF64_T)
add_executable(example64 example.c)
target_link_libraries(example64 zlib)
set_target_properties(example64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64")
add_test(example64 example64)
add_executable(minigzip64 minigzip.c)
target_link_libraries(minigzip64 zlib)
set_target_properties(minigzip64 PROPERTIES COMPILE_FLAGS "-D_FILE_OFFSET_BITS=64")
endif()

166
ChangeLog
View File

@@ -1,6 +1,170 @@
ChangeLog file for zlib ChangeLog file for zlib
Changes in 1.2.3.8 (13 Feb 2010)
- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer]
- Use z_off64_t in gz_zero() and gz_skip() to match state->skip
- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t)
- Revert to Makefile.in from 1.2.3.6 (live with the clutter)
- Fix missing error return in gzflush(), add zlib.h note
- Add *64 functions to zlib.map [Levin]
- Fix signed/unsigned comparison in gz_comp()
- Use SFLAGS when testing shared linking in configure
- Add --64 option to ./configure to use -m64 with gcc
- Fix ./configure --help to correctly name options
- Have make fail if a test fails [Levin]
- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson]
- Remove assembler object files from contrib
Changes in 1.2.3.7 (24 Jan 2010)
- Always gzopen() with O_LARGEFILE if available
- Fix gzdirect() to work immediately after gzopen() or gzdopen()
- Make gzdirect() more precise when the state changes while reading
- Improve zlib.h documentation in many places
- Catch memory allocation failure in gz_open()
- Complete close operation if seek forward in gzclose_w() fails
- Return Z_ERRNO from gzclose_r() if close() fails
- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL
- Return zero for gzwrite() errors to match zlib.h description
- Return -1 on gzputs() error to match zlib.h description
- Add zconf.in.h to allow recovery from configure modification [Weigelt]
- Fix static library permissions in Makefile.in [Weigelt]
- Avoid warnings in configure tests that hide functionality [Weigelt]
- Add *BSD and DragonFly to Linux case in configure [gentoo 123571]
- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212]
- Avoid access of uninitialized data for first inflateReset2 call [Gomes]
- Keep object files in subdirectories to reduce the clutter somewhat
- Remove default Makefile and zlibdefs.h, add dummy Makefile
- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_
- Remove zlibdefs.h completely -- modify zconf.h instead
Changes in 1.2.3.6 (17 Jan 2010)
- Avoid void * arithmetic in gzread.c and gzwrite.c
- Make compilers happier with const char * for gz_error message
- Avoid unused parameter warning in inflate.c
- Avoid signed-unsigned comparison warning in inflate.c
- Indent #pragma's for traditional C
- Fix usage of strwinerror() in glib.c, change to gz_strwinerror()
- Correct email address in configure for system options
- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser]
- Update zlib.map [Brown]
- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [T<>r<EFBFBD>k]
- Apply various fixes to CMakeLists.txt [Lowman]
- Add checks on len in gzread() and gzwrite()
- Add error message for no more room for gzungetc()
- Remove zlib version check in gzwrite()
- Defer compression of gzprintf() result until need to
- Use snprintf() in gzdopen() if available
- Remove USE_MMAP configuration determination (only used by minigzip)
- Remove examples/pigz.c (available separately)
- Update examples/gun.c to 1.6
Changes in 1.2.3.5 (8 Jan 2010)
- Add space after #if in zutil.h for some compilers
- Fix relatively harmless bug in deflate_fast() [Exarevsky]
- Fix same problem in deflate_slow()
- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown]
- Add deflate_rle() for faster Z_RLE strategy run-length encoding
- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding
- Change name of "write" variable in inffast.c to avoid library collisions
- Fix premature EOF from gzread() in gzio.c [Brown]
- Use zlib header window size if windowBits is 0 in inflateInit2()
- Remove compressBound() call in deflate.c to avoid linking compress.o
- Replace use of errno in gz* with functions, support WinCE [Alves]
- Provide alternative to perror() in minigzip.c for WinCE [Alves]
- Don't use _vsnprintf on later versions of MSVC [Lowman]
- Add CMake build script and input file [Lowman]
- Update contrib/minizip to 1.1 [Svensson, Vollant]
- Moved nintendods directory from contrib to .
- Replace gzio.c with a new set of routines with the same functionality
- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above
- Update contrib/minizip to 1.1b
- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h
Changes in 1.2.3.4 (21 Dec 2009)
- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility
- Update comments in configure and Makefile.in for default --shared
- Fix test -z's in configure [Marquess]
- Build examplesh and minigzipsh when not testing
- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h
- Import LDFLAGS from the environment in configure
- Fix configure to populate SFLAGS with discovered CFLAGS options
- Adapt make_vms.com to the new Makefile.in [Zinser]
- Add zlib2ansi script for C++ compilation [Marquess]
- Add _FILE_OFFSET_BITS=64 test to make test (when applicable)
- Add AMD64 assembler code for longest match to contrib [Teterin]
- Include options from $SFLAGS when doing $LDSHARED
- Simplify 64-bit file support by introducing z_off64_t type
- Make shared object files in objs directory to work around old Sun cc
- Use only three-part version number for Darwin shared compiles
- Add rc option to ar in Makefile.in for when ./configure not run
- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4*
- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile
- Protect against _FILE_OFFSET_BITS being defined when compiling zlib
- Rename Makefile.in targets allstatic to static and allshared to shared
- Fix static and shared Makefile.in targets to be independent
- Correct error return bug in gz_open() by setting state [Brown]
- Put spaces before ;;'s in configure for better sh compatibility
- Add pigz.c (parallel implementation of gzip) to examples/
- Correct constant in crc32.c to UL [Leventhal]
- Reject negative lengths in crc32_combine()
- Add inflateReset2() function to work like inflateEnd()/inflateInit2()
- Include sys/types.h for _LARGEFILE64_SOURCE [Brown]
- Correct typo in doc/algorithm.txt [Janik]
- Fix bug in adler32_combine() [Zhu]
- Catch missing-end-of-block-code error in all inflates and in puff
Assures that random input to inflate eventually results in an error
- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/
- Update ENOUGH and its usage to reflect discovered bounds
- Fix gzerror() error report on empty input file [Brown]
- Add ush casts in trees.c to avoid pedantic runtime errors
- Fix typo in zlib.h uncompress() description [Reiss]
- Correct inflate() comments with regard to automatic header detection
- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays)
- Put new version of gzlog (2.0) in examples with interruption recovery
- Add puff compile option to permit invalid distance-too-far streams
- Add puff TEST command options, ability to read piped input
- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but
_LARGEFILE64_SOURCE not defined
- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart
- Fix deflateSetDictionary() to use all 32K for output consistency
- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h)
- Clear bytes after deflate lookahead to avoid use of uninitialized data
- Change a limit in inftrees.c to be more transparent to Coverity Prevent
- Update win32/zlib.def with exported symbols from zlib.h
- Correct spelling error in zlib.h [Willem]
- Allow Z_BLOCK for deflate() to force a new block
- Allow negative bits in inflatePrime() to delete existing bit buffer
- Add Z_TREES flush option to inflate() to return at end of trees
- Add inflateMark() to return current state information for random access
- Add Makefile for NintendoDS to contrib [Costa]
- Add -w in configure compile tests to avoid spurious warnings [Beucler]
- Fix typos in zlib.h comments for deflateSetDictionary()
- Fix EOF detection in transparent gzread() [Maier]
Changes in 1.2.3.3 (2 October 2006)
- Make --shared the default for configure, add a --static option
- Add compile option to permit invalid distance-too-far streams
- Add inflateUndermine() function which is required to enable above
- Remove use of "this" variable name for C++ compatibility [Marquess]
- Add testing of shared library in make test, if shared library built
- Use ftello() and fseeko() if available instead of ftell() and fseek()
- Provide two versions of all functions that use the z_off_t type for
binary compatibility -- a normal version and a 64-bit offset version,
per the Large File Support Extension when _LARGEFILE64_SOURCE is
defined; use the 64-bit versions by default when _FILE_OFFSET_BITS
is defined to be 64
- Add a --uname= option to configure to perhaps help with cross-compiling
Changes in 1.2.3.2 (3 September 2006)
- Turn off silly Borland warnings [Hay]
- Use off64_t and define _LARGEFILE64_SOURCE when present
- Fix missing dependency on inffixed.h in Makefile.in
- Rig configure --shared to build both shared and static [Teredesai, Truta]
- Remove zconf.in.h and instead create a new zlibdefs.h file
- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant]
- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt]
Changes in 1.2.3.1 (16 August 2006) Changes in 1.2.3.1 (16 August 2006)
- Add watcom directory with OpenWatcom make files [Daniel] - Add watcom directory with OpenWatcom make files [Daniel]
- Remove #undef of FAR in zconf.in.h for MVS [Fedtke] - Remove #undef of FAR in zconf.in.h for MVS [Fedtke]
@@ -42,7 +206,7 @@ Changes in 1.2.3.1 (16 August 2006)
- Synchronize FAQ with website - Synchronize FAQ with website
- Fix compressBound(), was low for some pathological cases [Fearnley] - Fix compressBound(), was low for some pathological cases [Fearnley]
- Take into account wrapper variations in deflateBound() - Take into account wrapper variations in deflateBound()
- Set examples/zpipe.c input and output to binary mode for Windows - Set examples/zpipe.c input and output to binary mode for Windows
- Update examples/zlib_how.html with new zpipe.c (also web site) - Update examples/zlib_how.html with new zpipe.c (also web site)
- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems - Fix some warnings in examples/gzlog.c and examples/zran.c (it seems
that gcc became pickier in 4.0) that gcc became pickier in 4.0)

29
INDEX
View File

@@ -1,26 +1,30 @@
CMakeLists.txt cmake build file
ChangeLog history of changes ChangeLog history of changes
FAQ Frequently Asked Questions about zlib FAQ Frequently Asked Questions about zlib
INDEX this file INDEX this file
Makefile makefile for Unix (generated by configure) Makefile.in template for Unix Makefile
Makefile.in makefile for Unix (template for configure)
README guess what README guess what
configure configure script for Unix configure configure script for Unix
make_vms.com makefile for VMS make_vms.com makefile for VMS
zconf.in.h template for zconf.h (used by configure) treebuild.xml XML description of source file dependencies
zlib.3 Man page for zlib zconf.in.h zconf.h template for configure
zlib.map Linux symbol information zlib.3 Man page for zlib
zlib.pc.in ?? zlib.map Linux symbol information
zlib.pc.in Template for pkg-config descriptor
zlib2ansi perl script to convert source files for C++ compilation
amiga/ makefiles for Amiga SAS C amiga/ makefiles for Amiga SAS C
as400/ makefiles for IBM AS/400 as400/ makefiles for IBM AS/400
doc/ documentation for formats and algorithms doc/ documentation for formats and algorithms
msdos/ makefiles for MSDOS msdos/ makefiles for MSDOS
nintendods/ makefile for Nintendo DS
objs/ destination for object files
old/ makefiles for various architectures and zlib documentation old/ makefiles for various architectures and zlib documentation
files that have not yet been updated for zlib 1.2.x files that have not yet been updated for zlib 1.2.x
pics/ destination for position-independent-code object files
projects/ projects for various Integrated Development Environments projects/ projects for various Integrated Development Environments
qnx/ makefiles for QNX qnx/ makefiles for QNX
todo/ works in progress watcom/ makefiles for OpenWatcom
watcom/ makefiles for OpenWatcom
win32/ makefiles for Windows win32/ makefiles for Windows
zlib public header files (required for library use): zlib public header files (required for library use):
@@ -34,7 +38,12 @@ crc32.c
crc32.h crc32.h
deflate.c deflate.c
deflate.h deflate.h
gzclose.c
gzguts.h
gzio.c gzio.c
gzlib.c
gzread.c
gzwrite.c
infback.c infback.c
inffast.c inffast.c
inffast.h inffast.h

161
Makefile
View File

@@ -1,159 +1,2 @@
# Makefile for zlib all:
# Copyright (C) 1995-2006 Jean-loup Gailly. -@echo "Use ./configure first. Thank you."
# For conditions of distribution and use, see copyright notice in zlib.h
# To compile and test, type:
# ./configure; make test
# The call of configure is optional if you don't have special requirements
# If you wish to build zlib as a shared library, use: ./configure -s
# To use the asm code, type:
# cp contrib/asm?86/match.S ./match.S
# make LOC=-DASMV OBJA=match.o
# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
# make install
# To install in $HOME instead of /usr/local, use:
# make install prefix=$HOME
CC=cc
CFLAGS=-O
#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
#CFLAGS=-g -DDEBUG
#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
# -Wstrict-prototypes -Wmissing-prototypes
LDFLAGS=libz.a
LDSHARED=$(CC)
CPP=$(CC) -E
LIBS=libz.a
SHAREDLIB=libz.so
SHAREDLIBV=libz.so.1.2.3.1
SHAREDLIBM=libz.so.1
AR=ar
RANLIB=ranlib
TAR=tar
SHELL=/bin/sh
EXE=
prefix = /usr/local
exec_prefix = ${prefix}
libdir = ${exec_prefix}/lib
includedir = ${prefix}/include
mandir = ${prefix}/share/man
man3dir = ${mandir}/man3
pkgconfigdir = ${libdir}/pkgconfig
OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
zutil.o inflate.o infback.o inftrees.o inffast.o
OBJA =
# to use the asm code: make OBJA=match.o
TEST_OBJS = example.o minigzip.o
all: example$(EXE) minigzip$(EXE)
check: test
test: all
@LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
echo hello world | ./minigzip | ./minigzip -d || \
echo ' *** minigzip test FAILED ***' ; \
if ./example; then \
echo ' *** zlib test OK ***'; \
else \
echo ' *** zlib test FAILED ***'; \
fi
libz.a: $(OBJS) $(OBJA)
$(AR) $@ $(OBJS) $(OBJA)
-@ ($(RANLIB) $@ || true) >/dev/null 2>&1
match.o: match.S
$(CPP) match.S > _match.s
$(CC) -c _match.s
mv _match.o match.o
rm -f _match.s
$(SHAREDLIBV): $(OBJS)
$(LDSHARED) -o $@ $(OBJS)
rm -f $(SHAREDLIB) $(SHAREDLIBM)
ln -s $@ $(SHAREDLIB)
ln -s $@ $(SHAREDLIBM)
example$(EXE): example.o $(LIBS)
$(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
minigzip$(EXE): minigzip.o $(LIBS)
$(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
install: $(LIBS)
-@if [ ! -d $(DESTDIR)$(exec_prefix) ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi
-@if [ ! -d $(DESTDIR)$(includedir) ]; then mkdir -p $(DESTDIR)$(includedir); fi
-@if [ ! -d $(DESTDIR)$(libdir) ]; then mkdir -p $(DESTDIR)$(libdir); fi
-@if [ ! -d $(DESTDIR)$(man3dir) ]; then mkdir -p $(DESTDIR)$(man3dir); fi
-@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi
cp zlib.h zconf.h $(DESTDIR)$(includedir)
chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
cp $(LIBS) $(DESTDIR)$(libdir)
cd $(DESTDIR)$(libdir); chmod 755 $(LIBS)
-@(cd $(DESTDIR)$(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
cd $(DESTDIR)$(libdir); if test -f $(SHAREDLIBV); then \
rm -f $(SHAREDLIB) $(SHAREDLIBM); \
ln -s $(SHAREDLIBV) $(SHAREDLIB); \
ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
(ldconfig || true) >/dev/null 2>&1; \
fi
cp zlib.3 $(DESTDIR)$(man3dir)
chmod 644 $(DESTDIR)$(man3dir)/zlib.3
cp zlib.pc $(DESTDIR)$(pkgconfigdir)
chmod 644 $(DESTDIR)$(pkgconfigdir)/zlib.pc
# The ranlib in install is needed on NeXTSTEP which checks file times
# ldconfig is for Linux
uninstall:
cd $(DESTDIR)$(includedir); rm -f zlib.h zconf.h
cd $(DESTDIR)$(libdir); rm -f libz.a; \
if test -f $(SHAREDLIBV); then \
rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
fi
cd $(DESTDIR)$(man3dir); rm -f zlib.3
cd $(DESTDIR)$(pkgconfigdir); rm -f zlib.pc
mostlyclean: clean
clean:
rm -f *.o *~ example$(EXE) minigzip$(EXE) \
libz.* foo.gz so_locations \
_match.s maketree contrib/infback9/*.o
maintainer-clean: distclean
distclean: clean
cp -p Makefile.in Makefile
cp -p zconf.in.h zconf.h
rm -f zlib.pc .DS_Store
tags:
etags *.[ch]
depend:
makedepend -- $(CFLAGS) -- *.[ch]
# DO NOT DELETE THIS LINE -- make depend depends on it.
adler32.o: zlib.h zconf.h
compress.o: zlib.h zconf.h
crc32.o: crc32.h zlib.h zconf.h
deflate.o: deflate.h zutil.h zlib.h zconf.h
example.o: zlib.h zconf.h
gzio.o: zutil.h zlib.h zconf.h
inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
inftrees.o: zutil.h zlib.h zconf.h inftrees.h
minigzip.o: zlib.h zconf.h
trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
uncompr.o: zlib.h zconf.h
zutil.o: zutil.h zlib.h zconf.h

View File

@@ -1,11 +1,11 @@
# Makefile for zlib # Makefile for zlib
# Copyright (C) 1995-2006 Jean-loup Gailly. # Copyright (C) 1995-2010 Jean-loup Gailly.
# For conditions of distribution and use, see copyright notice in zlib.h # For conditions of distribution and use, see copyright notice in zlib.h
# To compile and test, type: # To compile and test, type:
# ./configure; make test # ./configure; make test
# The call of configure is optional if you don't have special requirements # Normally configure builds both a static and a shared library.
# If you wish to build zlib as a shared library, use: ./configure -s # If you want to build just a static library, use: ./configure --static
# To use the asm code, type: # To use the asm code, type:
# cp contrib/asm?86/match.S ./match.S # cp contrib/asm?86/match.S ./match.S
@@ -24,16 +24,19 @@ CFLAGS=-O
#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ #CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
# -Wstrict-prototypes -Wmissing-prototypes # -Wstrict-prototypes -Wmissing-prototypes
LDFLAGS=libz.a SFLAGS=-O
LDFLAGS=-L. libz.a
LDSHARED=$(CC) LDSHARED=$(CC)
CPP=$(CC) -E CPP=$(CC) -E
LIBS=libz.a STATICLIB=libz.a
SHAREDLIB=libz.so SHAREDLIB=libz.so
SHAREDLIBV=libz.so.1.2.3.1 SHAREDLIBV=libz.so.1.2.3.8
SHAREDLIBM=libz.so.1 SHAREDLIBM=libz.so.1
LIBS=$(STATICLIB) $(SHAREDLIB) $(SHAREDLIBV)
AR=ar AR=ar rc
RANLIB=ranlib RANLIB=ranlib
TAR=tar TAR=tar
SHELL=/bin/sh SHELL=/bin/sh
@@ -47,29 +50,62 @@ mandir = ${prefix}/share/man
man3dir = ${mandir}/man3 man3dir = ${mandir}/man3
pkgconfigdir = ${libdir}/pkgconfig pkgconfigdir = ${libdir}/pkgconfig
OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ OBJC = adler32.o compress.o crc32.o deflate.o gzclose.o gzio.o gzlib.o gzread.o \
zutil.o inflate.o infback.o inftrees.o inffast.o gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o
PIC_OBJC = adler32.lo compress.lo crc32.lo deflate.lo gzclose.lo gzio.lo gzlib.lo gzread.lo \
gzwrite.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo uncompr.lo zutil.lo
# to use the asm code: make OBJA=match.o, PIC_OBJA=match.lo
OBJA = OBJA =
# to use the asm code: make OBJA=match.o PIC_OBJA =
TEST_OBJS = example.o minigzip.o OBJS = $(OBJC) $(OBJA)
all: example$(EXE) minigzip$(EXE) PIC_OBJS = $(PIC_OBJC) $(PIC_OBJA)
all: static shared
static: example$(EXE) minigzip$(EXE)
shared: examplesh$(EXE) minigzipsh$(EXE)
all64: example64$(EXE) minigzip64$(EXE)
check: test check: test
test: all
@LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ test: all teststatic testshared
echo hello world | ./minigzip | ./minigzip -d || \
echo ' *** minigzip test FAILED ***' ; \ teststatic: static
if ./example; then \ @if echo hello world | ./minigzip | ./minigzip -d && ./example; then \
echo ' *** zlib test OK ***'; \ echo ' *** zlib test OK ***'; \
else \ else \
echo ' *** zlib test FAILED ***'; \ echo ' *** zlib test FAILED ***'; false; \
fi fi
-@rm -f foo.gz
libz.a: $(OBJS) $(OBJA) testshared: shared
$(AR) $@ $(OBJS) $(OBJA) @LD_LIBRARY_PATH=`pwd`:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
LD_LIBRARYN32_PATH=`pwd`:$(LD_LIBRARYN32_PATH) ; export LD_LIBRARYN32_PATH; \
DYLD_LIBRARY_PATH=`pwd`:$(DYLD_LIBRARY_PATH) ; export DYLD_LIBRARY_PATH; \
SHLIB_PATH=`pwd`:$(SHLIB_PATH) ; export SHLIB_PATH; \
if echo hello world | ./minigzipsh | ./minigzipsh -d && ./examplesh; then \
echo ' *** zlib shared test OK ***'; \
else \
echo ' *** zlib shared test FAILED ***'; false; \
fi
-@rm -f foo.gz
test64: all64
@if echo hello world | ./minigzip64 | ./minigzip64 -d && ./example64; then \
echo ' *** zlib 64-bit test OK ***'; \
else \
echo ' *** zlib 64-bit test FAILED ***'; false; \
fi
-@rm -f foo.gz
libz.a: $(OBJS)
$(AR) $@ $(OBJS)
-@ ($(RANLIB) $@ || true) >/dev/null 2>&1 -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
match.o: match.S match.o: match.S
@@ -78,28 +114,57 @@ match.o: match.S
mv _match.o match.o mv _match.o match.o
rm -f _match.s rm -f _match.s
$(SHAREDLIBV): $(OBJS) match.lo: match.S
$(LDSHARED) -o $@ $(OBJS) $(CPP) match.S > _match.s
$(CC) -c -fPIC _match.s
mv _match.o match.lo
rm -f _match.s
example64.o: example.c zlib.h zconf.h
$(CC) $(CFLAGS) -D_FILE_OFFSET_BITS=64 -c -o $@ example.c
minigzip64.o: minigzip.c zlib.h zconf.h
$(CC) $(CFLAGS) -D_FILE_OFFSET_BITS=64 -c -o $@ minigzip.c
.SUFFIXES: .lo
.c.lo:
-@if [ ! -d objs ]; then mkdir objs; fi
$(CC) $(SFLAGS) -DPIC -c -o objs/$*.o $<
-@mv objs/$*.o $@
$(SHAREDLIBV): $(PIC_OBJS)
$(LDSHARED) $(SFLAGS) -o $@ $(PIC_OBJS) -lc
rm -f $(SHAREDLIB) $(SHAREDLIBM) rm -f $(SHAREDLIB) $(SHAREDLIBM)
ln -s $@ $(SHAREDLIB) ln -s $@ $(SHAREDLIB)
ln -s $@ $(SHAREDLIBM) ln -s $@ $(SHAREDLIBM)
-@rmdir objs
example$(EXE): example.o $(LIBS) example$(EXE): example.o $(STATICLIB)
$(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS) $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
minigzip$(EXE): minigzip.o $(LIBS) minigzip$(EXE): minigzip.o $(STATICLIB)
$(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS) $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
install: $(LIBS) examplesh$(EXE): example.o $(SHAREDLIBV)
$(CC) $(CFLAGS) -o $@ example.o -L. $(SHAREDLIBV)
minigzipsh$(EXE): minigzip.o $(SHAREDLIBV)
$(CC) $(CFLAGS) -o $@ minigzip.o -L. $(SHAREDLIBV)
example64$(EXE): example64.o $(STATICLIB)
$(CC) $(CFLAGS) -o $@ example64.o $(LDFLAGS)
minigzip64$(EXE): minigzip64.o $(STATICLIB)
$(CC) $(CFLAGS) -o $@ minigzip64.o $(LDFLAGS)
install-libs: $(LIBS)
-@if [ ! -d $(DESTDIR)$(exec_prefix) ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi -@if [ ! -d $(DESTDIR)$(exec_prefix) ]; then mkdir -p $(DESTDIR)$(exec_prefix); fi
-@if [ ! -d $(DESTDIR)$(includedir) ]; then mkdir -p $(DESTDIR)$(includedir); fi
-@if [ ! -d $(DESTDIR)$(libdir) ]; then mkdir -p $(DESTDIR)$(libdir); fi -@if [ ! -d $(DESTDIR)$(libdir) ]; then mkdir -p $(DESTDIR)$(libdir); fi
-@if [ ! -d $(DESTDIR)$(man3dir) ]; then mkdir -p $(DESTDIR)$(man3dir); fi -@if [ ! -d $(DESTDIR)$(man3dir) ]; then mkdir -p $(DESTDIR)$(man3dir); fi
-@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi -@if [ ! -d $(DESTDIR)$(pkgconfigdir) ]; then mkdir -p $(DESTDIR)$(pkgconfigdir); fi
cp zlib.h zconf.h $(DESTDIR)$(includedir)
chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
cp $(LIBS) $(DESTDIR)$(libdir) cp $(LIBS) $(DESTDIR)$(libdir)
cd $(DESTDIR)$(libdir); chmod 755 $(LIBS) cd $(DESTDIR)$(libdir); chmod 755 $(SHAREDLIB) ; chmod u=rw,go=r $(STATICLIB)
-@(cd $(DESTDIR)$(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1 -@(cd $(DESTDIR)$(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
cd $(DESTDIR)$(libdir); if test -f $(SHAREDLIBV); then \ cd $(DESTDIR)$(libdir); if test -f $(SHAREDLIBV); then \
rm -f $(SHAREDLIB) $(SHAREDLIBM); \ rm -f $(SHAREDLIB) $(SHAREDLIBM); \
@@ -114,6 +179,11 @@ install: $(LIBS)
# The ranlib in install is needed on NeXTSTEP which checks file times # The ranlib in install is needed on NeXTSTEP which checks file times
# ldconfig is for Linux # ldconfig is for Linux
install: install-libs
-@if [ ! -d $(DESTDIR)$(includedir) ]; then mkdir -p $(DESTDIR)$(includedir); fi
cp zlib.h zconf.h $(DESTDIR)$(includedir)
chmod 644 $(DESTDIR)$(includedir)/zlib.h $(DESTDIR)$(includedir)/zconf.h
uninstall: uninstall:
cd $(DESTDIR)$(includedir); rm -f zlib.h zconf.h cd $(DESTDIR)$(includedir); rm -f zlib.h zconf.h
cd $(DESTDIR)$(libdir); rm -f libz.a; \ cd $(DESTDIR)$(libdir); rm -f libz.a; \
@@ -125,15 +195,19 @@ uninstall:
mostlyclean: clean mostlyclean: clean
clean: clean:
rm -f *.o *~ example$(EXE) minigzip$(EXE) \ rm -f *.o *.lo *~ \
example$(EXE) minigzip$(EXE) examplesh$(EXE) minigzipsh$(EXE) \
example64$(EXE) minigzip64$(EXE) \
libz.* foo.gz so_locations \ libz.* foo.gz so_locations \
_match.s maketree contrib/infback9/*.o _match.s maketree contrib/infback9/*.o
rm -rf objs
maintainer-clean: distclean maintainer-clean: distclean
distclean: clean distclean: clean
cp -p Makefile.in Makefile
cp -p zconf.in.h zconf.h cp -p zconf.in.h zconf.h
rm -f zlib.pc .DS_Store rm -f zlib.pc .DS_Store
-@printf 'all:\n\t-@echo "Use ./configure first. Thank you."\n' > Makefile
-@touch -r Makefile.in Makefile
tags: tags:
etags *.[ch] etags *.[ch]
@@ -143,17 +217,22 @@ depend:
# DO NOT DELETE THIS LINE -- make depend depends on it. # DO NOT DELETE THIS LINE -- make depend depends on it.
adler32.o: zlib.h zconf.h adler32.o gzio.o zutil.o: zutil.h zlib.h zconf.h
compress.o: zlib.h zconf.h gzclose.o gzlib.o gzread.o gzwrite.o: zlib.h zconf.h gzguts.h
crc32.o: crc32.h zlib.h zconf.h compress.o example.o minigzip.o uncompr.o: zlib.h zconf.h
crc32.o: zutil.h zlib.h zconf.h crc32.h
deflate.o: deflate.h zutil.h zlib.h zconf.h deflate.o: deflate.h zutil.h zlib.h zconf.h
example.o: zlib.h zconf.h infback.o inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
gzio.o: zutil.h zlib.h zconf.h
inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
inftrees.o: zutil.h zlib.h zconf.h inftrees.h inftrees.o: zutil.h zlib.h zconf.h inftrees.h
minigzip.o: zlib.h zconf.h
trees.o: deflate.h zutil.h zlib.h zconf.h trees.h trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
uncompr.o: zlib.h zconf.h
zutil.o: zutil.h zlib.h zconf.h adler32.lo gzio.lo zutil.lo: zutil.h zlib.h zconf.h
gzclose.lo gzlib.lo gzread.lo gzwrite.lo: zlib.h zconf.h gzguts.h
compress.lo example.lo minigzip.lo uncompr.lo: zlib.h zconf.h
crc32.lo: zutil.h zlib.h zconf.h crc32.h
deflate.lo: deflate.h zutil.h zlib.h zconf.h
infback.lo inflate.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffixed.h
inffast.lo: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
inftrees.lo: zutil.h zlib.h zconf.h inftrees.h
trees.lo: deflate.h zutil.h zlib.h zconf.h trees.h

4
README
View File

@@ -1,6 +1,6 @@
ZLIB DATA COMPRESSION LIBRARY ZLIB DATA COMPRESSION LIBRARY
zlib 1.2.3.1 is a general purpose data compression library. All the code is zlib 1.2.3.8 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 thread safe. The data format used by the zlib library is described by RFCs
(Request for Comments) 1950 to 1952 in the files (Request for Comments) 1950 to 1952 in the files
http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
@@ -33,7 +33,7 @@ Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997
issue of Dr. Dobb's Journal; a copy of the article is available in issue of Dr. Dobb's Journal; a copy of the article is available in
http://dogma.net/markn/articles/zlibtool/zlibtool.htm http://dogma.net/markn/articles/zlibtool/zlibtool.htm
The changes made in version 1.2.3.1 are documented in the file ChangeLog. The changes made in version 1.2.3.8 are documented in the file ChangeLog.
Unsupported third party contributions are provided in directory "contrib". Unsupported third party contributions are provided in directory "contrib".

View File

@@ -1,12 +1,15 @@
/* adler32.c -- compute the Adler-32 checksum of a data stream /* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2004 Mark Adler * Copyright (C) 1995-2007 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* @(#) $Id$ */ /* @(#) $Id$ */
#define ZLIB_INTERNAL #include "zutil.h"
#include "zlib.h"
#define local static
local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2);
#define BASE 65521UL /* largest prime smaller than 65536 */ #define BASE 65521UL /* largest prime smaller than 65536 */
#define NMAX 5552 #define NMAX 5552
@@ -125,10 +128,10 @@ uLong ZEXPORT adler32(adler, buf, len)
} }
/* ========================================================================= */ /* ========================================================================= */
uLong ZEXPORT adler32_combine(adler1, adler2, len2) local uLong adler32_combine_(adler1, adler2, len2)
uLong adler1; uLong adler1;
uLong adler2; uLong adler2;
z_off_t len2; z_off64_t len2;
{ {
unsigned long sum1; unsigned long sum1;
unsigned long sum2; unsigned long sum2;
@@ -141,9 +144,26 @@ uLong ZEXPORT adler32_combine(adler1, adler2, len2)
MOD(sum2); MOD(sum2);
sum1 += (adler2 & 0xffff) + BASE - 1; sum1 += (adler2 & 0xffff) + BASE - 1;
sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
if (sum1 > BASE) sum1 -= BASE; if (sum1 >= BASE) sum1 -= BASE;
if (sum1 > BASE) sum1 -= BASE; if (sum1 >= BASE) sum1 -= BASE;
if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 > BASE) sum2 -= BASE; if (sum2 >= BASE) sum2 -= BASE;
return sum1 | (sum2 << 16); return sum1 | (sum2 << 16);
} }
/* ========================================================================= */
uLong ZEXPORT adler32_combine(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off_t len2;
{
return adler32_combine_(adler1, adler2, len2);
}
uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off64_t len2;
{
return adler32_combine_(adler1, adler2, len2);
}

View File

@@ -14,8 +14,8 @@ LDFLAGS = -o
LDLIBS = LIB:scppc.a LIB:end.o LDLIBS = LIB:scppc.a LIB:end.o
RM = delete quiet RM = delete quiet
OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ OBJS = adler32.o compress.o crc32.o gzclose.o gzio.o gzlib.o gzread.o gzwrite.o \
zutil.o inflate.o infback.o inftrees.o inffast.o uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
TEST_OBJS = example.o minigzip.o TEST_OBJS = example.o minigzip.o
@@ -55,7 +55,11 @@ compress.o: zlib.h zconf.h
crc32.o: crc32.h zlib.h zconf.h crc32.o: crc32.h zlib.h zconf.h
deflate.o: deflate.h zutil.h zlib.h zconf.h deflate.o: deflate.h zutil.h zlib.h zconf.h
example.o: zlib.h zconf.h example.o: zlib.h zconf.h
gzclose.o: zlib.h zconf.h gzguts.h
gzio.o: zutil.h zlib.h zconf.h gzio.o: zutil.h zlib.h zconf.h
gzlib.o: zlib.h zconf.h gzguts.h
gzread.o: zlib.h zconf.h gzguts.h
gzwrite.o: zlib.h zconf.h gzguts.h
inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h

View File

@@ -13,8 +13,8 @@ SCOPTIONS=OPTSCHED OPTINLINE OPTALIAS OPTTIME OPTINLOCAL STRMERGE \
NOICONS PARMS=BOTH NOSTACKCHECK UTILLIB NOVERSION ERRORREXX \ NOICONS PARMS=BOTH NOSTACKCHECK UTILLIB NOVERSION ERRORREXX \
DEF=POSTINC DEF=POSTINC
OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ OBJS = adler32.o compress.o crc32.o gzclose.o gzio.o gzlib.o gzread.o gzwrite.o \
zutil.o inflate.o infback.o inftrees.o inffast.o uncompr.o deflate.o trees.o zutil.o inflate.o infback.o inftrees.o inffast.o
TEST_OBJS = example.o minigzip.o TEST_OBJS = example.o minigzip.o
@@ -54,7 +54,11 @@ compress.o: zlib.h zconf.h
crc32.o: crc32.h zlib.h zconf.h crc32.o: crc32.h zlib.h zconf.h
deflate.o: deflate.h zutil.h zlib.h zconf.h deflate.o: deflate.h zutil.h zlib.h zconf.h
example.o: zlib.h zconf.h example.o: zlib.h zconf.h
gzclose.o: zlib.h zconf.h gzguts.h
gzio.o: zutil.h zlib.h zconf.h gzio.o: zutil.h zlib.h zconf.h
gzlib.o: zlib.h zconf.h gzguts.h
gzread.o: zlib.h zconf.h gzguts.h
gzwrite.o: zlib.h zconf.h gzguts.h
inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h

View File

@@ -1,7 +1,7 @@
* ZLIB.INC - Interface to the general purpose compression library * ZLIB.INC - Interface to the general purpose compression library
* *
* ILE RPG400 version by Patrick Monnerat, DATASPHERE. * ILE RPG400 version by Patrick Monnerat, DATASPHERE.
* Version 1.2.3.1 * Version 1.2.3.8
* *
* *
* WARNING: * WARNING:
@@ -22,8 +22,8 @@
* *
* Versioning information. * Versioning information.
* *
D ZLIB_VERSION C '1.2.3.1' D ZLIB_VERSION C '1.2.3.8'
D ZLIB_VERNUM C X'1231' D ZLIB_VERNUM C X'1238'
* *
* Other equates. * Other equates.
* *

229
configure vendored
View File

@@ -1,26 +1,22 @@
#!/bin/sh #!/bin/sh
# configure script for zlib. This script is needed only if # configure script for zlib.
# you wish to build a shared library and your system supports them,
# of if you need special compiler, flags or install directory.
# Otherwise, you can just use directly "make test; make install"
# #
# To create a shared library, use "configure --shared"; by default a static # Normally configure builds both a static and a shared library.
# library is created. If the primitive shared library support provided here # If you want to build just a static library, use: ./configure --static
# does not work, use ftp://prep.ai.mit.edu/pub/gnu/libtool-*.tar.gz
# #
# To impose specific compiler or flags or install directory, use for example: # To impose specific compiler or flags or install directory, use for example:
# prefix=$HOME CC=cc CFLAGS="-O4" ./configure # prefix=$HOME CC=cc CFLAGS="-O4" ./configure
# or for csh/tcsh users: # or for csh/tcsh users:
# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure) # (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure)
# LDSHARED is the command to be used to create a shared library
# Incorrect settings of CC or CFLAGS may prevent creating a shared library. # Incorrect settings of CC or CFLAGS may prevent creating a shared library.
# If you have problems, try without defining CC and CFLAGS before reporting # If you have problems, try without defining CC and CFLAGS before reporting
# an error. # an error.
LIBS=libz.a STATICLIB=libz.a
LDFLAGS="-L. ${LIBS}" LDFLAGS="${LDFLAGS} -L. ${STATICLIB}"
VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h` VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`
VER3=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h`
VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h` VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h`
VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h` VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h`
AR=${AR-"ar"} AR=${AR-"ar"}
@@ -32,8 +28,9 @@ libdir=${libdir-'${exec_prefix}/lib'}
includedir=${includedir-'${prefix}/include'} includedir=${includedir-'${prefix}/include'}
mandir=${mandir-'${prefix}/share/man'} mandir=${mandir-'${prefix}/share/man'}
shared_ext='.so' shared_ext='.so'
shared=0 shared=1
zprefix=0 zprefix=0
build64=0
gcc=0 gcc=0
old_cc="$CC" old_cc="$CC"
old_cflags="$CFLAGS" old_cflags="$CFLAGS"
@@ -43,22 +40,25 @@ do
case "$1" in case "$1" in
-h* | --help) -h* | --help)
echo 'usage:' echo 'usage:'
echo ' configure [--shared] [--prefix=PREFIX] [--exec_prefix=EXPREFIX]' echo ' configure [--zprefix] [--prefix=PREFIX] [--eprefix=EXPREFIX]'
echo ' [--libdir=LIBDIR] [--includedir=INCLUDEDIR] [--zprefix]' echo ' [--static] [--64] [--libdir=LIBDIR] [--includedir=INCLUDEDIR]'
exit 0;; exit 0 ;;
-p*=* | --prefix=*) prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;; -p*=* | --prefix=*) prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift ;;
-e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;; -e*=* | --eprefix=*) exec_prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift ;;
-l*=* | --libdir=*) libdir=`echo $1 | sed 's/[-a-z_]*=//'`; shift;; -l*=* | --libdir=*) libdir=`echo $1 | sed 's/[-a-z_]*=//'`; shift ;;
-i*=* | --includedir=*) includedir=`echo $1 | sed 's/[-a-z_]*=//'`;shift;; -i*=* | --includedir=*) includedir=`echo $1 | sed 's/[-a-z_]*=//'`;shift ;;
-p* | --prefix) prefix="$2"; shift; shift;; -u*=* | --uname=*) uname=`echo $1 | sed 's/[-a-z_]*=//'`;shift ;;
-e* | --eprefix) exec_prefix="$2"; shift; shift;; -p* | --prefix) prefix="$2"; shift; shift ;;
-l* | --libdir) libdir="$2"; shift; shift;; -e* | --eprefix) exec_prefix="$2"; shift; shift ;;
-i* | --includedir) includedir="$2"; shift; shift;; -l* | --libdir) libdir="$2"; shift; shift ;;
-s* | --shared | --enable-shared) shared=1; shift;; -i* | --includedir) includedir="$2"; shift; shift ;;
-z* | --zprefix) zprefix=1; shift;; -s* | --shared | --enable-shared) shared=1; shift ;;
--sysconfdir=*) echo "ignored option: --sysconfdir"; shift;; -t | --static) shared=0; shift ;;
--localstatedir=*) echo "ignored option: --localstatedir"; shift;; -z* | --zprefix) zprefix=1; shift ;;
*) echo "unknown option: $1"; echo "$0 --help for help"; exit 1;; -6* | --64) build64=1; shift ;;
--sysconfdir=*) echo "ignored option: --sysconfdir"; shift ;;
--localstatedir=*) echo "ignored option: --localstatedir"; shift ;;
*) echo "unknown option: $1"; echo "$0 --help for help"; exit 1 ;;
esac esac
done done
@@ -73,41 +73,54 @@ cc=${CC-gcc}
cflags=${CFLAGS-"-O3"} cflags=${CFLAGS-"-O3"}
# to force the asm version use: CFLAGS="-O3 -DASMV" ./configure # to force the asm version use: CFLAGS="-O3 -DASMV" ./configure
case "$cc" in case "$cc" in
*gcc*) gcc=1;; *gcc*) gcc=1 ;;
esac esac
if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) 2>/dev/null; then if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) 2>/dev/null; then
CC="$cc" CC="$cc"
SFLAGS="${CFLAGS-"-O3"} -fPIC" SFLAGS="${CFLAGS-"-O3"} -fPIC"
CFLAGS="$cflags" CFLAGS="${CFLAGS-"-O3"}"
case `(uname -s || echo unknown) 2>/dev/null` in if test $build64 -eq 1; then
Linux | linux | GNU | GNU/*) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map"};; CFLAGS="${CFLAGS} -m64"
SFLAGS="${SFLAGS} -m64"
fi
if test "${ZLIBGCCWARN}" = "YES"; then
CFLAGS="${CFLAGS} -Wall -Wextra -pedantic"
fi
if test -z "$uname"; then
uname=`(uname -s || echo unknown) 2>/dev/null`
fi
case "$uname" in
Linux | linux | GNU | GNU/* | *BSD | DragonFly) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map"} ;;
CYGWIN* | Cygwin* | cygwin* | OS/2* ) CYGWIN* | Cygwin* | cygwin* | OS/2* )
EXE='.exe';; EXE='.exe' ;;
QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4 QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4
# (alain.bonnefoy@icbt.com) # (alain.bonnefoy@icbt.com)
LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"};; LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"} ;;
HP-UX*) HP-UX*)
LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"} LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"}
case `(uname -m || echo unknown) 2>/dev/null` in case `(uname -m || echo unknown) 2>/dev/null` in
ia64) ia64)
shared_ext='.so' shared_ext='.so'
SHAREDLIB='libz.so';; SHAREDLIB='libz.so' ;;
*) *)
shared_ext='.sl' shared_ext='.sl'
SHAREDLIB='libz.sl';; SHAREDLIB='libz.sl' ;;
esac;; esac ;;
Darwin*) shared_ext='.dylib' Darwin*) shared_ext='.dylib'
SHAREDLIB=libz$shared_ext SHAREDLIB=libz$shared_ext
SHAREDLIBV=libz.$VER$shared_ext SHAREDLIBV=libz.$VER$shared_ext
SHAREDLIBM=libz.$VER1$shared_ext SHAREDLIBM=libz.$VER1$shared_ext
LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER"};; LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER3"} ;;
*) LDSHARED=${LDSHARED-"$cc -shared"};; *) LDSHARED=${LDSHARED-"$cc -shared"} ;;
esac esac
else else
# find system name and corresponding cc options # find system name and corresponding cc options
CC=${CC-cc} CC=${CC-cc}
case `(uname -sr || echo unknown) 2>/dev/null` in if test -z "$uname"; then
uname=`(uname -sr || echo unknown) 2>/dev/null`
fi
case "$uname" in
HP-UX*) SFLAGS=${CFLAGS-"-O +z"} HP-UX*) SFLAGS=${CFLAGS-"-O +z"}
CFLAGS=${CFLAGS-"-O"} CFLAGS=${CFLAGS-"-O"}
# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"} # LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"}
@@ -115,63 +128,64 @@ else
case `(uname -m || echo unknown) 2>/dev/null` in case `(uname -m || echo unknown) 2>/dev/null` in
ia64) ia64)
shared_ext='.so' shared_ext='.so'
SHAREDLIB='libz.so';; SHAREDLIB='libz.so' ;;
*) *)
shared_ext='.sl' shared_ext='.sl'
SHAREDLIB='libz.sl';; SHAREDLIB='libz.sl' ;;
esac;; esac ;;
IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."} IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."}
CFLAGS=${CFLAGS-"-ansi -O2"} CFLAGS=${CFLAGS-"-ansi -O2"}
LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"};; LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"} OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"}
CFLAGS=${CFLAGS-"-O -std1"} CFLAGS=${CFLAGS-"-O -std1"}
LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"};; LDFLAGS="${LDFLAGS} -Wl,-rpath,."
LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"} ;;
OSF1*) SFLAGS=${CFLAGS-"-O -std1"} OSF1*) SFLAGS=${CFLAGS-"-O -std1"}
CFLAGS=${CFLAGS-"-O -std1"} CFLAGS=${CFLAGS-"-O -std1"}
LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"};; LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so.1"} ;;
QNX*) SFLAGS=${CFLAGS-"-4 -O"} QNX*) SFLAGS=${CFLAGS-"-4 -O"}
CFLAGS=${CFLAGS-"-4 -O"} CFLAGS=${CFLAGS-"-4 -O"}
LDSHARED=${LDSHARED-"cc"} LDSHARED=${LDSHARED-"cc"}
RANLIB=${RANLIB-"true"} RANLIB=${RANLIB-"true"}
AR_RC="cc -A";; AR_RC="cc -A" ;;
SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "} SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "}
CFLAGS=${CFLAGS-"-O3"} CFLAGS=${CFLAGS-"-O3"}
LDSHARED=${LDSHARED-"cc -dy -KPIC -G"};; LDSHARED=${LDSHARED-"cc -dy -KPIC -G"} ;;
SunOS\ 5*) LDSHARED=${LDSHARED-"cc -G"} SunOS\ 5*) LDSHARED=${LDSHARED-"cc -G"}
case `(uname -m || echo unknown) 2>/dev/null` in case `(uname -m || echo unknown) 2>/dev/null` in
i86*) i86*)
SFLAGS=${CFLAGS-"-xpentium -fast -KPIC -R."} SFLAGS=${CFLAGS-"-xpentium -fast -KPIC -R."}
CFLAGS=${CFLAGS-"-xpentium -fast"};; CFLAGS=${CFLAGS-"-xpentium -fast"} ;;
*) *)
SFLAGS=${CFLAGS-"-fast -xcg92 -KPIC -R."} SFLAGS=${CFLAGS-"-fast -xcg92 -KPIC -R."}
CFLAGS=${CFLAGS-"-fast -xcg92"};; CFLAGS=${CFLAGS-"-fast -xcg92"} ;;
esac;; esac ;;
SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"} SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"}
CFLAGS=${CFLAGS-"-O2"} CFLAGS=${CFLAGS-"-O2"}
LDSHARED=${LDSHARED-"ld"};; LDSHARED=${LDSHARED-"ld"} ;;
SunStudio\ 9*) SFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"} SunStudio\ 9*) SFLAGS=${CFLAGS-"-fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
CFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xtarget=ultra3 -xarch=v9b"} CFLAGS=${CFLAGS-"-fast -xtarget=ultra3 -xarch=v9b"}
LDSHARED=${LDSHARED-"cc -xarch=v9b"};; LDSHARED=${LDSHARED-"cc -xarch=v9b"} ;;
UNIX_System_V\ 4.2.0) UNIX_System_V\ 4.2.0)
SFLAGS=${CFLAGS-"-KPIC -O"} SFLAGS=${CFLAGS-"-KPIC -O"}
CFLAGS=${CFLAGS-"-O"} CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -G"};; LDSHARED=${LDSHARED-"cc -G"} ;;
UNIX_SV\ 4.2MP) UNIX_SV\ 4.2MP)
SFLAGS=${CFLAGS-"-Kconform_pic -O"} SFLAGS=${CFLAGS-"-Kconform_pic -O"}
CFLAGS=${CFLAGS-"-O"} CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -G"};; LDSHARED=${LDSHARED-"cc -G"} ;;
OpenUNIX\ 5) OpenUNIX\ 5)
SFLAGS=${CFLAGS-"-KPIC -O"} SFLAGS=${CFLAGS-"-KPIC -O"}
CFLAGS=${CFLAGS-"-O"} CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -G"};; LDSHARED=${LDSHARED-"cc -G"} ;;
AIX*) # Courtesy of dbakker@arrayasolutions.com AIX*) # Courtesy of dbakker@arrayasolutions.com
SFLAGS=${CFLAGS-"-O -qmaxmem=8192"} SFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
CFLAGS=${CFLAGS-"-O -qmaxmem=8192"} CFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
LDSHARED=${LDSHARED-"xlc -G"};; LDSHARED=${LDSHARED-"xlc -G"} ;;
# send working options for other systems to support@gzip.org # send working options for other systems to zlib@gzip.org
*) SFLAGS=${CFLAGS-"-O"} *) SFLAGS=${CFLAGS-"-O"}
CFLAGS=${CFLAGS-"-O"} CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -shared"};; LDSHARED=${LDSHARED-"cc -shared"} ;;
esac esac
fi fi
@@ -182,39 +196,71 @@ SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"}
if test $shared -eq 1; then if test $shared -eq 1; then
echo Checking for shared library support... echo Checking for shared library support...
# we must test in two steps (cc then ld), required at least on SunOS 4.x # we must test in two steps (cc then ld), required at least on SunOS 4.x
if test "`($CC -c $SFLAGS $test.c) 2>&1`" = "" && if test "`($CC -w -c $SFLAGS $test.c) 2>&1`" = "" &&
test "`($LDSHARED -o $test$shared_ext $test.o) 2>&1`" = ""; then test "`($LDSHARED $SFLAGS -o $test$shared_ext $test.o) 2>&1`" = ""; then
CFLAGS="$SFLAGS"
LIBS="$SHAREDLIBV"
echo Building shared library $SHAREDLIBV with $CC. echo Building shared library $SHAREDLIBV with $CC.
elif test -z "$old_cc" -a -z "$old_cflags"; then elif test -z "$old_cc" -a -z "$old_cflags"; then
echo No shared library support. echo No shared library support.
shared=0; shared=0;
else else
echo Tested $CC -c $SFLAGS $test.c echo Tested $CC -w -c $SFLAGS $test.c
$CC -c $SFLAGS $test.c $CC -w -c $SFLAGS $test.c
echo Tested $LDSHARED -o $test$shared_ext $test.o echo Tested $LDSHARED $SFLAGS -o $test$shared_ext $test.o
$LDSHARED -o $test$shared_ext $test.o $LDSHARED $SFLAGS -o $test$shared_ext $test.o
echo 'No shared library support; try without defining CC and CFLAGS' echo 'No shared library support; try without defining CC and CFLAGS'
shared=0; shared=0;
fi fi
fi fi
if test $shared -eq 0; then if test $shared -eq 0; then
LDSHARED="$CC" LDSHARED="$CC"
echo Building static library $LIBS version $VER with $CC. ALL="static"
TEST="all teststatic"
echo Building static library $STATICLIB version $VER with $CC.
else else
LDFLAGS="-L. ${SHAREDLIBV}" ALL="static shared"
TEST="all teststatic testshared"
fi fi
cat > $test.c <<EOF
#include <sys/types.h>
off64_t dummy = 0;
EOF
if test "`($CC -c $CFLAGS -D_LARGEFILE64_SOURCE=1 $test.c) 2>&1`" = ""; then
CFLAGS="${CFLAGS} -D_LARGEFILE64_SOURCE=1"
SFLAGS="${SFLAGS} -D_LARGEFILE64_SOURCE=1"
ALL="${ALL} all64"
TEST="${TEST} test64"
echo "Checking for off64_t... Yes."
echo "Checking for fseeko... Yes."
else
echo "Checking for off64_t... No."
cat > $test.c <<EOF
#include <stdio.h>
int main(void) {
fseeko(NULL, 0, 0);
return 0;
}
EOF
if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
echo "Checking for fseeko... Yes."
else
CFLAGS="${CFLAGS} -DNO_FSEEKO"
SFLAGS="${SFLAGS} -DNO_FSEEKO"
echo "Checking for fseeko... No."
fi
fi
cp -p zconf.in.h zconf.h
cat > $test.c <<EOF cat > $test.c <<EOF
#include <unistd.h> #include <unistd.h>
int main() { return 0; } int main() { return 0; }
EOF EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
sed < zconf.in.h "/HAVE_UNISTD_H/s%0%1%" > zconf.h sed < zconf.h "/#ifdef HAVE_UNISTD_H/s/def HAVE_UNISTD_H/ 1/" > zconf.temp.h
mv zconf.temp.h zconf.h
echo "Checking for unistd.h... Yes." echo "Checking for unistd.h... Yes."
else else
cp -p zconf.in.h zconf.h
echo "Checking for unistd.h... No." echo "Checking for unistd.h... No."
fi fi
@@ -246,7 +292,7 @@ if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
#include <stdio.h> #include <stdio.h>
#include <stdarg.h> #include <stdarg.h>
int mytest(char *fmt, ...) int mytest(const char *fmt, ...)
{ {
char buf[20]; char buf[20];
va_list ap; va_list ap;
@@ -292,6 +338,7 @@ EOF
echo "Checking for return value of vsnprintf()... Yes." echo "Checking for return value of vsnprintf()... Yes."
else else
CFLAGS="$CFLAGS -DHAS_vsnprintf_void" CFLAGS="$CFLAGS -DHAS_vsnprintf_void"
SFLAGS="$SFLAGS -DHAS_vsnprintf_void"
echo "Checking for return value of vsnprintf()... No." echo "Checking for return value of vsnprintf()... No."
echo " WARNING: apparently vsnprintf() does not return a value. zlib" echo " WARNING: apparently vsnprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security" echo " can build but will be open to possible string-format security"
@@ -299,6 +346,7 @@ EOF
fi fi
else else
CFLAGS="$CFLAGS -DNO_vsnprintf" CFLAGS="$CFLAGS -DNO_vsnprintf"
SFLAGS="$SFLAGS -DNO_vsnprintf"
echo "Checking for vsnprintf() in stdio.h... No." echo "Checking for vsnprintf() in stdio.h... No."
echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib" echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib"
echo " can build but will be open to possible buffer-overflow security" echo " can build but will be open to possible buffer-overflow security"
@@ -308,7 +356,7 @@ EOF
#include <stdio.h> #include <stdio.h>
#include <stdarg.h> #include <stdarg.h>
int mytest(char *fmt, ...) int mytest(const char *fmt, ...)
{ {
int n; int n;
char buf[20]; char buf[20];
@@ -330,6 +378,7 @@ EOF
echo "Checking for return value of vsprintf()... Yes." echo "Checking for return value of vsprintf()... Yes."
else else
CFLAGS="$CFLAGS -DHAS_vsprintf_void" CFLAGS="$CFLAGS -DHAS_vsprintf_void"
SFLAGS="$SFLAGS -DHAS_vsprintf_void"
echo "Checking for return value of vsprintf()... No." echo "Checking for return value of vsprintf()... No."
echo " WARNING: apparently vsprintf() does not return a value. zlib" echo " WARNING: apparently vsprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security" echo " can build but will be open to possible string-format security"
@@ -379,6 +428,7 @@ EOF
echo "Checking for return value of snprintf()... Yes." echo "Checking for return value of snprintf()... Yes."
else else
CFLAGS="$CFLAGS -DHAS_snprintf_void" CFLAGS="$CFLAGS -DHAS_snprintf_void"
SFLAGS="$SFLAGS -DHAS_snprintf_void"
echo "Checking for return value of snprintf()... No." echo "Checking for return value of snprintf()... No."
echo " WARNING: apparently snprintf() does not return a value. zlib" echo " WARNING: apparently snprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security" echo " can build but will be open to possible string-format security"
@@ -386,6 +436,7 @@ EOF
fi fi
else else
CFLAGS="$CFLAGS -DNO_snprintf" CFLAGS="$CFLAGS -DNO_snprintf"
SFLAGS="$SFLAGS -DNO_snprintf"
echo "Checking for snprintf() in stdio.h... No." echo "Checking for snprintf() in stdio.h... No."
echo " WARNING: snprintf() not found, falling back to sprintf(). zlib" echo " WARNING: snprintf() not found, falling back to sprintf(). zlib"
echo " can build but will be open to possible buffer-overflow security" echo " can build but will be open to possible buffer-overflow security"
@@ -411,6 +462,7 @@ EOF
echo "Checking for return value of sprintf()... Yes." echo "Checking for return value of sprintf()... Yes."
else else
CFLAGS="$CFLAGS -DHAS_sprintf_void" CFLAGS="$CFLAGS -DHAS_sprintf_void"
SFLAGS="$SFLAGS -DHAS_sprintf_void"
echo "Checking for return value of sprintf()... No." echo "Checking for return value of sprintf()... No."
echo " WARNING: apparently sprintf() does not return a value. zlib" echo " WARNING: apparently sprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security" echo " can build but will be open to possible string-format security"
@@ -428,21 +480,7 @@ if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
else else
echo "Checking for errno.h... No." echo "Checking for errno.h... No."
CFLAGS="$CFLAGS -DNO_ERRNO_H" CFLAGS="$CFLAGS -DNO_ERRNO_H"
fi SFLAGS="$SFLAGS -DNO_ERRNO_H"
cat > $test.c <<EOF
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
caddr_t hello() {
return mmap((caddr_t)0, (off_t)0, PROT_READ, MAP_SHARED, 0, (off_t)0);
}
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
CFLAGS="$CFLAGS -DUSE_MMAP"
echo Checking for mmap support... Yes.
else
echo Checking for mmap support... No.
fi fi
CPP=${CPP-"$CC -E"} CPP=${CPP-"$CC -E"}
@@ -453,7 +491,7 @@ case $CFLAGS in
echo Checking for underline in external names... No. echo Checking for underline in external names... No.
else else
echo Checking for underline in external names... Yes. echo Checking for underline in external names... Yes.
fi;; fi ;;
esac esac
rm -f $test.[co] $test $test$shared_ext rm -f $test.[co] $test $test$shared_ext
@@ -462,9 +500,11 @@ rm -f $test.[co] $test $test$shared_ext
sed < Makefile.in " sed < Makefile.in "
/^CC *=/s#=.*#=$CC# /^CC *=/s#=.*#=$CC#
/^CFLAGS *=/s#=.*#=$CFLAGS# /^CFLAGS *=/s#=.*#=$CFLAGS#
/^CPP *=/s#=.*#=$CPP# /^SFLAGS *=/s#=.*#=$SFLAGS#
/^LDFLAGS *=/s#=.*#=$LDFLAGS#
/^LDSHARED *=/s#=.*#=$LDSHARED# /^LDSHARED *=/s#=.*#=$LDSHARED#
/^LIBS *=/s#=.*#=$LIBS# /^CPP *=/s#=.*#=$CPP#
/^STATICLIB *=/s#=.*#=$STATICLIB#
/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# /^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# /^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# /^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
@@ -476,7 +516,8 @@ sed < Makefile.in "
/^libdir *=/s#=.*#=$libdir# /^libdir *=/s#=.*#=$libdir#
/^includedir *=/s#=.*#=$includedir# /^includedir *=/s#=.*#=$includedir#
/^mandir *=/s#=.*#=$mandir# /^mandir *=/s#=.*#=$mandir#
/^LDFLAGS *=/s#=.*#=$LDFLAGS# /^all: */s#:.*#: $ALL#
/^test: */s#:.*#: $TEST#
" > Makefile " > Makefile
sed < zlib.pc.in " sed < zlib.pc.in "
@@ -484,7 +525,7 @@ sed < zlib.pc.in "
/^CFLAGS *=/s#=.*#=$CFLAGS# /^CFLAGS *=/s#=.*#=$CFLAGS#
/^CPP *=/s#=.*#=$CPP# /^CPP *=/s#=.*#=$CPP#
/^LDSHARED *=/s#=.*#=$LDSHARED# /^LDSHARED *=/s#=.*#=$LDSHARED#
/^LIBS *=/s#=.*#=$LIBS# /^STATICLIB *=/s#=.*#=$STATICLIB#
/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# /^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# /^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# /^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#

View File

@@ -8,6 +8,10 @@ ada/ by Dmitriy Anisimkov <anisimkov@yahoo.com>
Support for Ada Support for Ada
See http://zlib-ada.sourceforge.net/ See http://zlib-ada.sourceforge.net/
amd64/ by Mikhail Teterin <mi@ALDAN.algebra.com>
asm code for AMD64
See patch at http://www.freebsd.org/cgi/query-pr.cgi?pr=bin/96393
asm586/ asm586/
asm686/ by Brian Raiter <breadbox@muppetlabs.com> asm686/ by Brian Raiter <breadbox@muppetlabs.com>
asm code for Pentium and PPro/PII, using the AT&T (GNU as) syntax asm code for Pentium and PPro/PII, using the AT&T (GNU as) syntax
@@ -52,6 +56,7 @@ masmx86/ by Gilles Vollant <info@winimage.com>
minizip/ by Gilles Vollant <info@winimage.com> minizip/ by Gilles Vollant <info@winimage.com>
Mini zip and unzip based on zlib Mini zip and unzip based on zlib
Includes Zip64 support by Mathias Svensson <mathias@result42.com>
See http://www.winimage.com/zLibDll/unzip.html See http://www.winimage.com/zLibDll/unzip.html
pascal/ by Bob Dellaca <bobdl@xtra.co.nz> et al. pascal/ by Bob Dellaca <bobdl@xtra.co.nz> et al.

357
contrib/amd64/amd64-match.S Normal file
View File

@@ -0,0 +1,357 @@
/*
* match.S -- optimized version of longest_match()
* based on the similar work by Gilles Vollant, and Brian Raiter, written 1998
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the BSD License. Use by owners of Che Guevarra
* parafernalia is prohibited, where possible, and highly discouraged
* elsewhere.
*/
#ifndef NO_UNDERLINE
# define match_init _match_init
# define longest_match _longest_match
#endif
#define scanend ebx
#define scanendw bx
#define chainlenwmask edx /* high word: current chain len low word: s->wmask */
#define curmatch rsi
#define curmatchd esi
#define windowbestlen r8
#define scanalign r9
#define scanalignd r9d
#define window r10
#define bestlen r11
#define bestlend r11d
#define scanstart r12d
#define scanstartw r12w
#define scan r13
#define nicematch r14d
#define limit r15
#define limitd r15d
#define prev rcx
/*
* The 258 is a "magic number, not a parameter -- changing it
* breaks the hell loose
*/
#define MAX_MATCH (258)
#define MIN_MATCH (3)
#define MIN_LOOKAHEAD (MAX_MATCH + MIN_MATCH + 1)
#define MAX_MATCH_8 ((MAX_MATCH + 7) & ~7)
/* stack frame offsets */
#define LocalVarsSize (112)
#define _chainlenwmask ( 8-LocalVarsSize)(%rsp)
#define _windowbestlen (16-LocalVarsSize)(%rsp)
#define save_r14 (24-LocalVarsSize)(%rsp)
#define save_rsi (32-LocalVarsSize)(%rsp)
#define save_rbx (40-LocalVarsSize)(%rsp)
#define save_r12 (56-LocalVarsSize)(%rsp)
#define save_r13 (64-LocalVarsSize)(%rsp)
#define save_r15 (80-LocalVarsSize)(%rsp)
/*
* On AMD64 the first argument of a function (in our case -- the pointer to
* deflate_state structure) is passed in %rdi, hence our offsets below are
* all off of that.
*/
#ifndef STRUCT_OFFSET
# define STRUCT_OFFSET (0)
#endif
#define dsWSize ( 56 + STRUCT_OFFSET)(%rdi)
#define dsWMask ( 64 + STRUCT_OFFSET)(%rdi)
#define dsWindow ( 72 + STRUCT_OFFSET)(%rdi)
#define dsPrev ( 88 + STRUCT_OFFSET)(%rdi)
#define dsMatchLen (136 + STRUCT_OFFSET)(%rdi)
#define dsPrevMatch (140 + STRUCT_OFFSET)(%rdi)
#define dsStrStart (148 + STRUCT_OFFSET)(%rdi)
#define dsMatchStart (152 + STRUCT_OFFSET)(%rdi)
#define dsLookahead (156 + STRUCT_OFFSET)(%rdi)
#define dsPrevLen (160 + STRUCT_OFFSET)(%rdi)
#define dsMaxChainLen (164 + STRUCT_OFFSET)(%rdi)
#define dsGoodMatch (180 + STRUCT_OFFSET)(%rdi)
#define dsNiceMatch (184 + STRUCT_OFFSET)(%rdi)
.globl match_init, longest_match
.text
/* uInt longest_match(deflate_state *deflatestate, IPos curmatch) */
longest_match:
/*
* Retrieve the function arguments. %curmatch will hold cur_match
* throughout the entire function (passed via rsi on amd64).
* rdi will hold the pointer to the deflate_state (first arg on amd64)
*/
mov %rsi, save_rsi
mov %rbx, save_rbx
mov %r12, save_r12
mov %r13, save_r13
mov %r14, save_r14
mov %r15, save_r15
/* uInt wmask = s->w_mask; */
/* unsigned chain_length = s->max_chain_length; */
/* if (s->prev_length >= s->good_match) { */
/* chain_length >>= 2; */
/* } */
movl dsPrevLen, %eax
movl dsGoodMatch, %ebx
cmpl %ebx, %eax
movl dsWMask, %eax
movl dsMaxChainLen, %chainlenwmask
jl LastMatchGood
shrl $2, %chainlenwmask
LastMatchGood:
/* chainlen is decremented once beforehand so that the function can */
/* use the sign flag instead of the zero flag for the exit test. */
/* It is then shifted into the high word, to make room for the wmask */
/* value, which it will always accompany. */
decl %chainlenwmask
shll $16, %chainlenwmask
orl %eax, %chainlenwmask
/* if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; */
movl dsNiceMatch, %eax
movl dsLookahead, %ebx
cmpl %eax, %ebx
jl LookaheadLess
movl %eax, %ebx
LookaheadLess: movl %ebx, %nicematch
/* register Bytef *scan = s->window + s->strstart; */
mov dsWindow, %window
movl dsStrStart, %limitd
lea (%limit, %window), %scan
/* Determine how many bytes the scan ptr is off from being */
/* dword-aligned. */
mov %scan, %scanalign
negl %scanalignd
andl $3, %scanalignd
/* IPos limit = s->strstart > (IPos)MAX_DIST(s) ? */
/* s->strstart - (IPos)MAX_DIST(s) : NIL; */
movl dsWSize, %eax
subl $MIN_LOOKAHEAD, %eax
xorl %ecx, %ecx
subl %eax, %limitd
cmovng %ecx, %limitd
/* int best_len = s->prev_length; */
movl dsPrevLen, %bestlend
/* Store the sum of s->window + best_len in %windowbestlen locally, and in memory. */
lea (%window, %bestlen), %windowbestlen
mov %windowbestlen, _windowbestlen
/* register ush scan_start = *(ushf*)scan; */
/* register ush scan_end = *(ushf*)(scan+best_len-1); */
/* Posf *prev = s->prev; */
movzwl (%scan), %scanstart
movzwl -1(%scan, %bestlen), %scanend
mov dsPrev, %prev
/* Jump into the main loop. */
movl %chainlenwmask, _chainlenwmask
jmp LoopEntry
.balign 16
/* do {
* match = s->window + cur_match;
* if (*(ushf*)(match+best_len-1) != scan_end ||
* *(ushf*)match != scan_start) continue;
* [...]
* } while ((cur_match = prev[cur_match & wmask]) > limit
* && --chain_length != 0);
*
* Here is the inner loop of the function. The function will spend the
* majority of its time in this loop, and majority of that time will
* be spent in the first ten instructions.
*/
LookupLoop:
andl %chainlenwmask, %curmatchd
movzwl (%prev, %curmatch, 2), %curmatchd
cmpl %limitd, %curmatchd
jbe LeaveNow
subl $0x00010000, %chainlenwmask
js LeaveNow
LoopEntry: cmpw -1(%windowbestlen, %curmatch), %scanendw
jne LookupLoop
cmpw %scanstartw, (%window, %curmatch)
jne LookupLoop
/* Store the current value of chainlen. */
movl %chainlenwmask, _chainlenwmask
/* %scan is the string under scrutiny, and %prev to the string we */
/* are hoping to match it up with. In actuality, %esi and %edi are */
/* both pointed (MAX_MATCH_8 - scanalign) bytes ahead, and %edx is */
/* initialized to -(MAX_MATCH_8 - scanalign). */
mov $(-MAX_MATCH_8), %rdx
lea (%curmatch, %window), %windowbestlen
lea MAX_MATCH_8(%windowbestlen, %scanalign), %windowbestlen
lea MAX_MATCH_8(%scan, %scanalign), %prev
/* the prefetching below makes very little difference... */
prefetcht1 (%windowbestlen, %rdx)
prefetcht1 (%prev, %rdx)
/*
* Test the strings for equality, 8 bytes at a time. At the end,
* adjust %rdx so that it is offset to the exact byte that mismatched.
*
* It should be confessed that this loop usually does not represent
* much of the total running time. Replacing it with a more
* straightforward "rep cmpsb" would not drastically degrade
* performance -- unrolling it, for example, makes no difference.
*/
#undef USE_SSE /* works, but is 6-7% slower, than non-SSE... */
LoopCmps:
#ifdef USE_SSE
/* Preload the SSE registers */
movdqu (%windowbestlen, %rdx), %xmm1
movdqu (%prev, %rdx), %xmm2
pcmpeqb %xmm2, %xmm1
movdqu 16(%windowbestlen, %rdx), %xmm3
movdqu 16(%prev, %rdx), %xmm4
pcmpeqb %xmm4, %xmm3
movdqu 32(%windowbestlen, %rdx), %xmm5
movdqu 32(%prev, %rdx), %xmm6
pcmpeqb %xmm6, %xmm5
movdqu 48(%windowbestlen, %rdx), %xmm7
movdqu 48(%prev, %rdx), %xmm8
pcmpeqb %xmm8, %xmm7
/* Check the comparisions' results */
pmovmskb %xmm1, %rax
notw %ax
bsfw %ax, %ax
jnz LeaveLoopCmps
add $16, %rdx
pmovmskb %xmm3, %rax
notw %ax
bsfw %ax, %ax
jnz LeaveLoopCmps
add $16, %rdx
pmovmskb %xmm5, %rax
notw %ax
bsfw %ax, %ax
jnz LeaveLoopCmps
add $16, %rdx
pmovmskb %xmm7, %rax
notw %ax
bsfw %ax, %ax
jnz LeaveLoopCmps
add $16, %rdx
jmp LoopCmps
LeaveLoopCmps: add %rax, %rdx
#else
mov (%windowbestlen, %rdx), %rax
xor (%prev, %rdx), %rax
jnz LeaveLoopCmps
add $8, %rdx
jnz LoopCmps
jmp LenMaximum
# if 0
/*
* This three-liner is tantalizingly simple, but bsf is a slow instruction,
* and the complicated alternative down below is quite a bit faster. Sad...
*/
LeaveLoopCmps: bsf %rax, %rax /* find the first non-zero bit */
shrl $3, %eax /* divide by 8 to get the byte */
add %rax, %rdx
# else
LeaveLoopCmps: testl $0xFFFFFFFF, %eax /* Check the first 4 bytes */
jnz Check16
add $4, %rdx
shr $32, %rax
Check16: testw $0xFFFF, %ax
jnz LenLower
add $2, %rdx
shrl $16, %eax
LenLower: subb $1, %al
adc $0, %rdx
# endif
#endif
/* Calculate the length of the match. If it is longer than MAX_MATCH, */
/* then automatically accept it as the best possible match and leave. */
lea (%prev, %rdx), %rax
sub %scan, %rax
cmpl $MAX_MATCH, %eax
jge LenMaximum
/* If the length of the match is not longer than the best match we */
/* have so far, then forget it and return to the lookup loop. */
cmpl %bestlend, %eax
jg LongerMatch
mov _windowbestlen, %windowbestlen
mov dsPrev, %prev
movl _chainlenwmask, %edx
jmp LookupLoop
/* s->match_start = cur_match; */
/* best_len = len; */
/* if (len >= nice_match) break; */
/* scan_end = *(ushf*)(scan+best_len-1); */
LongerMatch:
movl %eax, %bestlend
movl %curmatchd, dsMatchStart
cmpl %nicematch, %eax
jge LeaveNow
lea (%window, %bestlen), %windowbestlen
mov %windowbestlen, _windowbestlen
movzwl -1(%scan, %rax), %scanend
mov dsPrev, %prev
movl _chainlenwmask, %chainlenwmask
jmp LookupLoop
/* Accept the current string, with the maximum possible length. */
LenMaximum:
movl $MAX_MATCH, %bestlend
movl %curmatchd, dsMatchStart
/* if ((uInt)best_len <= s->lookahead) return (uInt)best_len; */
/* return s->lookahead; */
LeaveNow:
movl dsLookahead, %eax
cmpl %eax, %bestlend
cmovngl %bestlend, %eax
LookaheadRet:
/* Restore the registers and return from whence we came. */
mov save_rsi, %rsi
mov save_rbx, %rbx
mov save_r12, %r12
mov save_r13, %r13
mov save_r14, %r14
mov save_r15, %r15
ret
match_init: ret

View File

@@ -0,0 +1,196 @@
/* ioapi.h -- IO base function header for compress/uncompress .zip
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Changes
Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
More if/def section may be needed to support other platforms
Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
(but you should use iowin32.c for windows instead)
*/
#ifndef _ZLIBIOAPI64_H
#define _ZLIBIOAPI64_H
#include "zlib.h"
#ifndef _WIN32
// Linux needs this to support file operation on files larger then 4+GB
// But might need better if/def to select just the platforms that needs them.
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#ifdef _MSC_VER
#define fopen64 fopen
#if _MSC_VER >= 1400
#define ftello64 _ftelli64
#define fseeko64 _fseeki64
#else // old MSC
#define ftello64 ftell
#define fseeko64 fseek
#endif
#endif
/*
#ifndef ZPOS64_T
#ifdef _WIN32
#define ZPOS64_T fpos_t
#else
#include <stdint.h>
#define ZPOS64_T uint64_t
#endif
#endif
*/
#ifdef HAVE_MINIZIP64_CONF_H
#include "mz64conf.h"
#endif
/* a type choosen by DEFINE */
#ifdef HAVE_64BIT_INT_CUSTOM
typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T;
#else
#ifdef HAS_STDINT_H
#include "stdint.h"
typedef uint64_t ZPOS64_T;
#else
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 ZPOS64_T;
#else
typedef unsigned long long int ZPOS64_T;
#endif
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define ZLIB_FILEFUNC_SEEK_CUR (1)
#define ZLIB_FILEFUNC_SEEK_END (2)
#define ZLIB_FILEFUNC_SEEK_SET (0)
#define ZLIB_FILEFUNC_MODE_READ (1)
#define ZLIB_FILEFUNC_MODE_WRITE (2)
#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
#define ZLIB_FILEFUNC_MODE_EXISTING (4)
#define ZLIB_FILEFUNC_MODE_CREATE (8)
#ifndef ZCALLBACK
#if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
#define ZCALLBACK CALLBACK
#else
#define ZCALLBACK
#endif
#endif
typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
/* here is the "old" 32 bits structure structure */
typedef struct zlib_filefunc_def_s
{
open_file_func zopen_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell_file_func ztell_file;
seek_file_func zseek_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc_def;
typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode));
typedef struct zlib_filefunc64_def_s
{
open64_file_func zopen64_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell64_file_func ztell64_file;
seek64_file_func zseek64_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc64_def;
void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
/* now internal definition, only for zip.c and unzip.h */
typedef struct zlib_filefunc64_32_def_s
{
zlib_filefunc64_def zfile_func64;
open_file_func zopen32_file;
tell_file_func ztell32_file;
seek_file_func zseek32_file;
} zlib_filefunc64_32_def;
#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,389 @@
/* iowin32.c -- IO base function header for compress/uncompress .zip
Version 1.1, January 7th, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
*/
#include <stdlib.h>
#include "zlib.h"
#include "ioapi.h"
#include "iowin32.h"
#ifndef INVALID_HANDLE_VALUE
#define INVALID_HANDLE_VALUE (0xFFFFFFFF)
#endif
#ifndef INVALID_SET_FILE_POINTER
#define INVALID_SET_FILE_POINTER ((DWORD)-1)
#endif
voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode));
uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
uLong ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
ZPOS64_T ZCALLBACK win32_tell64_file_func OF((voidpf opaque, voidpf stream));
long ZCALLBACK win32_seek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
int ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream));
int ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream));
typedef struct
{
HANDLE hf;
int error;
} WIN32FILE_IOWIN;
static void win32_translate_open_mode(int mode,
DWORD* lpdwDesiredAccess,
DWORD* lpdwCreationDisposition,
DWORD* lpdwShareMode,
DWORD* lpdwFlagsAndAttributes)
{
*lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
{
*lpdwDesiredAccess = GENERIC_READ;
*lpdwCreationDisposition = OPEN_EXISTING;
*lpdwShareMode = FILE_SHARE_READ;
}
else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
{
*lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
*lpdwCreationDisposition = OPEN_EXISTING;
}
else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
{
*lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
*lpdwCreationDisposition = CREATE_ALWAYS;
}
}
static voidpf win32_build_iowin(HANDLE hFile)
{
voidpf ret=NULL;
if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
{
WIN32FILE_IOWIN w32fiow;
w32fiow.hf = hFile;
w32fiow.error = 0;
ret = malloc(sizeof(WIN32FILE_IOWIN));
if (ret==NULL)
CloseHandle(hFile);
else
*((WIN32FILE_IOWIN*)ret) = w32fiow;
}
return ret;
}
voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size)
{
uLong ret=0;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
if (!ReadFile(hFile, buf, size, &ret, NULL))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_HANDLE_EOF)
dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
}
}
return ret;
}
uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size)
{
uLong ret=0;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
if (!WriteFile(hFile, buf, size, &ret, NULL))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_HANDLE_EOF)
dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
}
}
return ret;
}
long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream)
{
long ret=-1;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
DWORD dwSet = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=(long)dwSet;
}
return ret;
}
ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream)
{
ZPOS64_T ret= (ZPOS64_T)-1;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream)->hf;
if (hFile)
{
LARGE_INTEGER li;
li.QuadPart = 0;
li.u.LowPart = SetFilePointer(hFile, li.u.LowPart, &li.u.HighPart, FILE_CURRENT);
if ( (li.LowPart == 0xFFFFFFFF) && (GetLastError() != NO_ERROR))
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = (ZPOS64_T)-1;
}
else
ret=li.QuadPart;
}
return ret;
}
long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin)
{
DWORD dwMoveMethod=0xFFFFFFFF;
HANDLE hFile = NULL;
long ret=-1;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
dwMoveMethod = FILE_CURRENT;
break;
case ZLIB_FILEFUNC_SEEK_END :
dwMoveMethod = FILE_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
dwMoveMethod = FILE_BEGIN;
break;
default: return -1;
}
if (hFile != NULL)
{
DWORD dwSet = SetFilePointer(hFile, offset, NULL, dwMoveMethod);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=0;
}
return ret;
}
long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin)
{
DWORD dwMoveMethod=0xFFFFFFFF;
HANDLE hFile = NULL;
long ret=-1;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream)->hf;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
dwMoveMethod = FILE_CURRENT;
break;
case ZLIB_FILEFUNC_SEEK_END :
dwMoveMethod = FILE_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
dwMoveMethod = FILE_BEGIN;
break;
default: return -1;
}
if (hFile)
{
LARGE_INTEGER* li = (LARGE_INTEGER*)&offset;
DWORD dwSet = SetFilePointer(hFile, li->u.LowPart, &li->u.HighPart, dwMoveMethod);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=0;
}
return ret;
}
int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream)
{
int ret=-1;
if (stream!=NULL)
{
HANDLE hFile;
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
CloseHandle(hFile);
ret=0;
}
free(stream);
}
return ret;
}
int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream)
{
int ret=-1;
if (stream!=NULL)
{
ret = ((WIN32FILE_IOWIN*)stream) -> error;
}
return ret;
}
extern void ZEXPORT fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen_file = win32_open_file_func;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell_file = win32_tell_file_func;
pzlib_filefunc_def->zseek_file = win32_seek_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
extern void ZEXPORT fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_func;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
extern void ZEXPORT fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
extern void ZEXPORT fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}

View File

@@ -0,0 +1,28 @@
/* iowin32.h -- IO base function header for compress/uncompress .zip
Version 1.1, January 7th, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
*/
#include <windows.h>
#ifdef __cplusplus
extern "C" {
#endif
extern void ZEXPORT fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
extern void ZEXPORT fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def));
extern void ZEXPORT fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def));
extern void ZEXPORT fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def));
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,649 @@
/*
miniunz.c
Version 1.1, January 7th, 2010
sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
*/
#include "unzip.h"
#ifndef _WIN32
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef unix
# include <unistd.h>
# include <utime.h>
#else
# include <direct.h>
# include <io.h>
#endif
#define CASESENSITIVITY (0)
#define WRITEBUFFERSIZE (8192)
#define MAXFILENAME (256)
#ifdef _WIN32
#define USEWIN32IOAPI
#include "iowin32.h"
#endif
/*
mini unzip, demo of unzip package
usage :
Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir]
list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT
if it exists
*/
/* change_file_date : change the date/time of a file
filename : the filename of the file where date/time must be modified
dosdate : the new date at the MSDos format (4 bytes)
tmu_date : the SAME new date at the tm_unz format */
void change_file_date(filename,dosdate,tmu_date)
const char *filename;
uLong dosdate;
tm_unz tmu_date;
{
#ifdef _WIN32
HANDLE hFile;
FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite;
hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE,
0,NULL,OPEN_EXISTING,0,NULL);
GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite);
DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal);
LocalFileTimeToFileTime(&ftLocal,&ftm);
SetFileTime(hFile,&ftm,&ftLastAcc,&ftm);
CloseHandle(hFile);
#else
#ifdef unix
struct utimbuf ut;
struct tm newdate;
newdate.tm_sec = tmu_date.tm_sec;
newdate.tm_min=tmu_date.tm_min;
newdate.tm_hour=tmu_date.tm_hour;
newdate.tm_mday=tmu_date.tm_mday;
newdate.tm_mon=tmu_date.tm_mon;
if (tmu_date.tm_year > 1900)
newdate.tm_year=tmu_date.tm_year - 1900;
else
newdate.tm_year=tmu_date.tm_year ;
newdate.tm_isdst=-1;
ut.actime=ut.modtime=mktime(&newdate);
utime(filename,&ut);
#endif
#endif
}
/* mymkdir and change_file_date are not 100 % portable
As I don't know well Unix, I wait feedback for the unix portion */
int mymkdir(dirname)
const char* dirname;
{
int ret=0;
#ifdef _WIN32
ret = _mkdir(dirname);
#else
#ifdef unix
ret = mkdir (dirname,0775);
#endif
#endif
return ret;
}
int makedir (newdir)
char *newdir;
{
char *buffer ;
char *p;
int len = (int)strlen(newdir);
if (len <= 0)
return 0;
buffer = (char*)malloc(len+1);
if (buffer==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
strcpy(buffer,newdir);
if (buffer[len-1] == '/') {
buffer[len-1] = '\0';
}
if (mymkdir(buffer) == 0)
{
free(buffer);
return 1;
}
p = buffer+1;
while (1)
{
char hold;
while(*p && *p != '\\' && *p != '/')
p++;
hold = *p;
*p = 0;
if ((mymkdir(buffer) == -1) && (errno == ENOENT))
{
printf("couldn't create directory %s\n",buffer);
free(buffer);
return 0;
}
if (hold == 0)
break;
*p++ = hold;
}
free(buffer);
return 1;
}
void do_banner()
{
printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n");
printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
}
void do_help()
{
printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \
" -e Extract without pathname (junk paths)\n" \
" -x Extract with pathname\n" \
" -v list files\n" \
" -l list files\n" \
" -d directory to extract into\n" \
" -o overwrite files without prompting\n" \
" -p extract crypted file using password\n\n");
}
void Display64BitsSize(ZPOS64_T n, int size_char)
{
/* to avoid compatibility problem , we do here the conversion */
char number[21];
int offset=19;
int pos_string = 19;
number[20]=0;
for (;;) {
number[offset]=(char)((n%10)+'0');
if (number[offset] != '0')
pos_string=offset;
n/=10;
if (offset==0)
break;
offset--;
}
{
int size_display_string = 19-pos_string;
while (size_char > size_display_string)
{
size_char--;
printf(" ");
}
}
printf("%s",&number[pos_string]);
}
int do_list(uf)
unzFile uf;
{
uLong i;
unz_global_info64 gi;
int err;
err = unzGetGlobalInfo64(uf,&gi);
if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err);
printf(" Length Method Size Ratio Date Time CRC-32 Name\n");
printf(" ------ ------ ---- ----- ---- ---- ------ ----\n");
for (i=0;i<gi.number_entry;i++)
{
char filename_inzip[256];
unz_file_info64 file_info;
uLong ratio=0;
const char *string_method;
char charCrypt=' ';
err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
break;
}
if (file_info.uncompressed_size>0)
ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size);
/* display a '*' if the file is crypted */
if ((file_info.flag & 1) != 0)
charCrypt='*';
if (file_info.compression_method==0)
string_method="Stored";
else
if (file_info.compression_method==Z_DEFLATED)
{
uInt iLevel=(uInt)((file_info.flag & 0x6)/2);
if (iLevel==0)
string_method="Defl:N";
else if (iLevel==1)
string_method="Defl:X";
else if ((iLevel==2) || (iLevel==3))
string_method="Defl:F"; /* 2:fast , 3 : extra fast*/
}
else
if (file_info.compression_method==Z_BZIP2ED)
{
string_method="BZip2 ";
}
else
string_method="Unkn. ";
Display64BitsSize(file_info.uncompressed_size,7);
printf(" %6s%c",string_method,charCrypt);
Display64BitsSize(file_info.compressed_size,7);
printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n",
ratio,
(uLong)file_info.tmu_date.tm_mon + 1,
(uLong)file_info.tmu_date.tm_mday,
(uLong)file_info.tmu_date.tm_year % 100,
(uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min,
(uLong)file_info.crc,filename_inzip);
if ((i+1)<gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGoToNextFile\n",err);
break;
}
}
}
return 0;
}
int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
unzFile uf;
const int* popt_extract_without_path;
int* popt_overwrite;
const char* password;
{
char filename_inzip[256];
char* filename_withoutpath;
char* p;
int err=UNZ_OK;
FILE *fout=NULL;
void* buf;
uInt size_buf;
unz_file_info64 file_info;
uLong ratio=0;
err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
return err;
}
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
if (buf==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
p = filename_withoutpath = filename_inzip;
while ((*p) != '\0')
{
if (((*p)=='/') || ((*p)=='\\'))
filename_withoutpath = p+1;
p++;
}
if ((*filename_withoutpath)=='\0')
{
if ((*popt_extract_without_path)==0)
{
printf("creating directory: %s\n",filename_inzip);
mymkdir(filename_inzip);
}
}
else
{
const char* write_filename;
int skip=0;
if ((*popt_extract_without_path)==0)
write_filename = filename_inzip;
else
write_filename = filename_withoutpath;
err = unzOpenCurrentFilePassword(uf,password);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
}
if (((*popt_overwrite)==0) && (err==UNZ_OK))
{
char rep=0;
FILE* ftestexist;
ftestexist = fopen64(write_filename,"rb");
if (ftestexist!=NULL)
{
fclose(ftestexist);
do
{
char answer[128];
int ret;
printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ;
if ((rep>='a') && (rep<='z'))
rep -= 0x20;
}
while ((rep!='Y') && (rep!='N') && (rep!='A'));
}
if (rep == 'N')
skip = 1;
if (rep == 'A')
*popt_overwrite=1;
}
if ((skip==0) && (err==UNZ_OK))
{
fout=fopen64(write_filename,"wb");
/* some zipfile don't contain directory alone before file */
if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
(filename_withoutpath!=(char*)filename_inzip))
{
char c=*(filename_withoutpath-1);
*(filename_withoutpath-1)='\0';
makedir(write_filename);
*(filename_withoutpath-1)=c;
fout=fopen64(write_filename,"wb");
}
if (fout==NULL)
{
printf("error opening %s\n",write_filename);
}
}
if (fout!=NULL)
{
printf(" extracting: %s\n",write_filename);
do
{
err = unzReadCurrentFile(uf,buf,size_buf);
if (err<0)
{
printf("error %d with zipfile in unzReadCurrentFile\n",err);
break;
}
if (err>0)
if (fwrite(buf,err,1,fout)!=1)
{
printf("error in writing extracted file\n");
err=UNZ_ERRNO;
break;
}
}
while (err>0);
if (fout)
fclose(fout);
if (err==0)
change_file_date(write_filename,file_info.dosDate,
file_info.tmu_date);
}
if (err==UNZ_OK)
{
err = unzCloseCurrentFile (uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzCloseCurrentFile\n",err);
}
}
else
unzCloseCurrentFile(uf); /* don't lose the error */
}
free(buf);
return err;
}
int do_extract(uf,opt_extract_without_path,opt_overwrite,password)
unzFile uf;
int opt_extract_without_path;
int opt_overwrite;
const char* password;
{
uLong i;
unz_global_info64 gi;
int err;
FILE* fout=NULL;
err = unzGetGlobalInfo64(uf,&gi);
if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err);
for (i=0;i<gi.number_entry;i++)
{
if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite,
password) != UNZ_OK)
break;
if ((i+1)<gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGoToNextFile\n",err);
break;
}
}
}
return 0;
}
int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password)
unzFile uf;
const char* filename;
int opt_extract_without_path;
int opt_overwrite;
const char* password;
{
int err = UNZ_OK;
if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK)
{
printf("file %s not found in the zipfile\n",filename);
return 2;
}
if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite,
password) == UNZ_OK)
return 0;
else
return 1;
}
int main(argc,argv)
int argc;
char *argv[];
{
const char *zipfilename=NULL;
const char *filename_to_extract=NULL;
const char *password=NULL;
char filename_try[MAXFILENAME+16] = "";
int i;
int ret_value=0;
int opt_do_list=0;
int opt_do_extract=1;
int opt_do_extract_withoutpath=0;
int opt_overwrite=0;
int opt_extractdir=0;
const char *dirname=NULL;
unzFile uf=NULL;
do_banner();
if (argc==1)
{
do_help();
return 0;
}
else
{
for (i=1;i<argc;i++)
{
if ((*argv[i])=='-')
{
const char *p=argv[i]+1;
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='l') || (c=='L'))
opt_do_list = 1;
if ((c=='v') || (c=='V'))
opt_do_list = 1;
if ((c=='x') || (c=='X'))
opt_do_extract = 1;
if ((c=='e') || (c=='E'))
opt_do_extract = opt_do_extract_withoutpath = 1;
if ((c=='o') || (c=='O'))
opt_overwrite=1;
if ((c=='d') || (c=='D'))
{
opt_extractdir=1;
dirname=argv[i+1];
}
if (((c=='p') || (c=='P')) && (i+1<argc))
{
password=argv[i+1];
i++;
}
}
}
else
{
if (zipfilename == NULL)
zipfilename = argv[i];
else if ((filename_to_extract==NULL) && (!opt_extractdir))
filename_to_extract = argv[i] ;
}
}
}
if (zipfilename!=NULL)
{
# ifdef USEWIN32IOAPI
zlib_filefunc64_def ffunc;
# endif
strncpy(filename_try, zipfilename,MAXFILENAME-1);
/* strncpy doesnt append the trailing NULL, of the string is too long. */
filename_try[ MAXFILENAME ] = '\0';
# ifdef USEWIN32IOAPI
fill_win32_filefunc64A(&ffunc);
uf = unzOpen2_64(zipfilename,&ffunc);
# else
uf = unzOpen64(zipfilename);
# endif
if (uf==NULL)
{
strcat(filename_try,".zip");
# ifdef USEWIN32IOAPI
uf = unzOpen2_64(filename_try,&ffunc);
# else
uf = unzOpen64(filename_try);
# endif
}
}
if (uf==NULL)
{
printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
return 1;
}
printf("%s opened\n",filename_try);
if (opt_do_list==1)
ret_value = do_list(uf);
else if (opt_do_extract==1)
{
#ifdef _WIN32
if (opt_extractdir && _chdir(dirname))
#else
if (opt_extractdir && chdir(dirname))
#endif
{
printf("Error changing into %s, aborting\n", dirname);
exit(-1);
}
if (filename_to_extract == NULL)
ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password);
else
ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password);
}
unzClose(uf);
return ret_value;
}

View File

@@ -0,0 +1,508 @@
/*
minizip.c
Version 1.1, January 7th, 2010
sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
*/
#include "zip.h"
#ifndef _WIN32
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef unix
# include <unistd.h>
# include <utime.h>
# include <sys/types.h>
# include <sys/stat.h>
#else
# include <direct.h>
# include <io.h>
#endif
#ifdef _WIN32
#define USEWIN32IOAPI
#include "iowin32.h"
#endif
#define WRITEBUFFERSIZE (16384)
#define MAXFILENAME (256)
#ifdef _WIN32
uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */
uLong *dt; /* dostime */
{
int ret = 0;
{
FILETIME ftLocal;
HANDLE hFind;
WIN32_FIND_DATAA ff32;
hFind = FindFirstFileA(f,&ff32);
if (hFind != INVALID_HANDLE_VALUE)
{
FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
FindClose(hFind);
ret = 1;
}
}
return ret;
}
#else
#ifdef unix
uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */
uLong *dt; /* dostime */
{
int ret=0;
struct stat s; /* results of stat() */
struct tm* filedate;
time_t tm_t=0;
if (strcmp(f,"-")!=0)
{
char name[MAXFILENAME+1];
int len = strlen(f);
if (len > MAXFILENAME)
len = MAXFILENAME;
strncpy(name, f,MAXFILENAME-1);
/* strncpy doesnt append the trailing NULL, of the string is too long. */
name[ MAXFILENAME ] = '\0';
if (name[len - 1] == '/')
name[len - 1] = '\0';
/* not all systems allow stat'ing a file with / appended */
if (stat(name,&s)==0)
{
tm_t = s.st_mtime;
ret = 1;
}
}
filedate = localtime(&tm_t);
tmzip->tm_sec = filedate->tm_sec;
tmzip->tm_min = filedate->tm_min;
tmzip->tm_hour = filedate->tm_hour;
tmzip->tm_mday = filedate->tm_mday;
tmzip->tm_mon = filedate->tm_mon ;
tmzip->tm_year = filedate->tm_year;
return ret;
}
#else
uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */
uLong *dt; /* dostime */
{
return 0;
}
#endif
#endif
int check_exist_file(filename)
const char* filename;
{
FILE* ftestexist;
int ret = 1;
ftestexist = fopen64(filename,"rb");
if (ftestexist==NULL)
ret = 0;
else
fclose(ftestexist);
return ret;
}
void do_banner()
{
printf("MiniZip64 1.0, demo of zLib + MiniZip64 package, written by Gilles Vollant\n");
printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n");
printf("more info on MiniZip64 at http://result42.com/projects/MiniZip64\n\n");
}
void do_help()
{
printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \
" -o Overwrite existing file.zip\n" \
" -a Append to existing file.zip\n" \
" -0 Store only\n" \
" -1 Compress faster\n" \
" -9 Compress better\n\n" \
" -j exclude path. store only the file name.\n\n");
}
/* calculate the CRC32 of a file,
because to encrypt a file, we need known the CRC32 of the file before */
int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc)
{
unsigned long calculate_crc=0;
int err=ZIP_OK;
FILE * fin = fopen64(filenameinzip,"rb");
unsigned long size_read = 0;
unsigned long total_read = 0;
if (fin==NULL)
{
err = ZIP_ERRNO;
}
if (err == ZIP_OK)
do
{
err = ZIP_OK;
size_read = (int)fread(buf,1,size_buf,fin);
if (size_read < size_buf)
if (feof(fin)==0)
{
printf("error in reading %s\n",filenameinzip);
err = ZIP_ERRNO;
}
if (size_read>0)
calculate_crc = crc32(calculate_crc,buf,size_read);
total_read += size_read;
} while ((err == ZIP_OK) && (size_read>0));
if (fin)
fclose(fin);
*result_crc=calculate_crc;
printf("file %s crc %lx\n", filenameinzip, calculate_crc);
return err;
}
int isLargeFile(const char* filename)
{
int largeFile = 0;
ZPOS64_T pos = 0;
FILE* pFile = fopen64(filename, "rb");
if(pFile != NULL)
{
int n = fseeko64(pFile, 0, SEEK_END);
pos = ftello64(pFile);
printf("File : %s is %lld bytes\n", filename, pos);
if(pos >= 0xffffffff)
largeFile = 1;
fclose(pFile);
}
return largeFile;
}
int main(argc,argv)
int argc;
char *argv[];
{
int i;
int opt_overwrite=0;
int opt_compress_level=Z_DEFAULT_COMPRESSION;
int opt_exclude_path=0;
int zipfilenamearg = 0;
char filename_try[MAXFILENAME+16];
int zipok;
int err=0;
int size_buf=0;
void* buf=NULL;
const char* password=NULL;
do_banner();
if (argc==1)
{
do_help();
return 0;
}
else
{
for (i=1;i<argc;i++)
{
if ((*argv[i])=='-')
{
const char *p=argv[i]+1;
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='o') || (c=='O'))
opt_overwrite = 1;
if ((c=='a') || (c=='A'))
opt_overwrite = 2;
if ((c>='0') && (c<='9'))
opt_compress_level = c-'0';
if ((c=='j') || (c=='J'))
opt_exclude_path = 1;
if (((c=='p') || (c=='P')) && (i+1<argc))
{
password=argv[i+1];
i++;
}
}
}
else
{
if (zipfilenamearg == 0)
{
zipfilenamearg = i ;
}
}
}
}
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
if (buf==NULL)
{
printf("Error allocating memory\n");
return ZIP_INTERNALERROR;
}
if (zipfilenamearg==0)
{
zipok=0;
}
else
{
int i,len;
int dot_found=0;
zipok = 1 ;
strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
/* strncpy doesnt append the trailing NULL, of the string is too long. */
filename_try[ MAXFILENAME ] = '\0';
len=(int)strlen(filename_try);
for (i=0;i<len;i++)
if (filename_try[i]=='.')
dot_found=1;
if (dot_found==0)
strcat(filename_try,".zip");
if (opt_overwrite==2)
{
/* if the file don't exist, we not append file */
if (check_exist_file(filename_try)==0)
opt_overwrite=1;
}
else
if (opt_overwrite==0)
if (check_exist_file(filename_try)!=0)
{
char rep=0;
do
{
char answer[128];
int ret;
printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ;
if ((rep>='a') && (rep<='z'))
rep -= 0x20;
}
while ((rep!='Y') && (rep!='N') && (rep!='A'));
if (rep=='N')
zipok = 0;
if (rep=='A')
opt_overwrite = 2;
}
}
if (zipok==1)
{
zipFile zf;
int errclose;
# ifdef USEWIN32IOAPI
zlib_filefunc64_def ffunc;
fill_win32_filefunc64A(&ffunc);
zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
# else
zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
# endif
if (zf == NULL)
{
printf("error opening %s\n",filename_try);
err= ZIP_ERRNO;
}
else
printf("creating %s\n",filename_try);
for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
{
if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
((argv[i][1]=='o') || (argv[i][1]=='O') ||
(argv[i][1]=='a') || (argv[i][1]=='A') ||
(argv[i][1]=='p') || (argv[i][1]=='P') ||
((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
(strlen(argv[i]) == 2)))
{
FILE * fin;
int size_read;
const char* filenameinzip = argv[i];
const char *savefilenameinzip;
zip_fileinfo zi;
unsigned long crcFile=0;
int zip64 = 0;
zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
zi.dosDate = 0;
zi.internal_fa = 0;
zi.external_fa = 0;
filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);
/*
err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
NULL,0,NULL,0,NULL / * comment * /,
(opt_compress_level != 0) ? Z_DEFLATED : 0,
opt_compress_level);
*/
if ((password != NULL) && (err==ZIP_OK))
err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
zip64 = isLargeFile(filenameinzip);
/* The path name saved, should not include a leading slash. */
/*if it did, windows/xp and dynazip couldn't read the zip file. */
savefilenameinzip = filenameinzip;
while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
{
savefilenameinzip++;
}
/*should the zip file contain any path at all?*/
if( opt_exclude_path )
{
const char *tmpptr;
const char *lastslash = 0;
for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
{
if( *tmpptr == '\\' || *tmpptr == '/')
{
lastslash = tmpptr;
}
}
if( lastslash != NULL )
{
savefilenameinzip = lastslash+1; // base filename follows last slash.
}
}
/**/
err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
NULL,0,NULL,0,NULL /* comment*/,
(opt_compress_level != 0) ? Z_DEFLATED : 0,
opt_compress_level,0,
/* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
password,crcFile, zip64);
if (err != ZIP_OK)
printf("error in opening %s in zipfile\n",filenameinzip);
else
{
fin = fopen64(filenameinzip,"rb");
if (fin==NULL)
{
err=ZIP_ERRNO;
printf("error in opening %s for reading\n",filenameinzip);
}
}
if (err == ZIP_OK)
do
{
err = ZIP_OK;
size_read = (int)fread(buf,1,size_buf,fin);
if (size_read < size_buf)
if (feof(fin)==0)
{
printf("error in reading %s\n",filenameinzip);
err = ZIP_ERRNO;
}
if (size_read>0)
{
err = zipWriteInFileInZip (zf,buf,size_read);
if (err<0)
{
printf("error in writing %s in the zipfile\n",
filenameinzip);
}
}
} while ((err == ZIP_OK) && (size_read>0));
if (fin)
fclose(fin);
if (err<0)
err=ZIP_ERRNO;
else
{
err = zipCloseFileInZip(zf);
if (err!=ZIP_OK)
printf("error in closing %s in the zipfile\n",
filenameinzip);
}
}
}
errclose = zipClose(zf,NULL);
if (errclose != ZIP_OK)
printf("error in closing %s\n",filename_try);
}
else
{
do_help();
}
free(buf);
return 0;
}

View File

@@ -0,0 +1,95 @@
VERSION 1.23
HEAPSIZE 1048576,8192
EXPORTS
adler32 @1
compress @2
crc32 @3
deflate @4
deflateCopy @5
deflateEnd @6
deflateInit2_ @7
deflateInit_ @8
deflateParams @9
deflateReset @10
deflateSetDictionary @11
gzclose @12
gzdopen @13
gzerror @14
gzflush @15
gzopen @16
gzread @17
gzwrite @18
inflate @19
inflateEnd @20
inflateInit2_ @21
inflateInit_ @22
inflateReset @23
inflateSetDictionary @24
inflateSync @25
uncompress @26
zlibVersion @27
gzprintf @28
gzputc @29
gzgetc @30
gzseek @31
gzrewind @32
gztell @33
gzeof @34
gzsetparams @35
zError @36
inflateSyncPoint @37
get_crc_table @38
compress2 @39
gzputs @40
gzgets @41
inflateCopy @42
inflateBackInit_ @43
inflateBack @44
inflateBackEnd @45
compressBound @46
deflateBound @47
gzclearerr @48
gzungetc @49
zlibCompileFlags @50
deflatePrime @51
unzOpen @61
unzClose @62
unzGetGlobalInfo @63
unzGetCurrentFileInfo @64
unzGoToFirstFile @65
unzGoToNextFile @66
unzOpenCurrentFile @67
unzReadCurrentFile @68
unzOpenCurrentFile3 @69
unztell @70
unzeof @71
unzCloseCurrentFile @72
unzGetGlobalComment @73
unzStringFileNameCompare @74
unzLocateFile @75
unzGetLocalExtrafield @76
unzOpen2 @77
unzOpenCurrentFile2 @78
unzOpenCurrentFilePassword @79
zipOpen @80
zipOpenNewFileInZip @81
zipWriteInFileInZip @82
zipCloseFileInZip @83
zipClose @84
zipOpenNewFileInZip2 @86
zipCloseFileInZipRaw @87
zipOpen2 @88
zipOpenNewFileInZip3 @89
unzGetFilePos @100
unzGoToFilePos @101
fill_win32_filefunc @110
fill_win32_filefunc64 @111
fill_win32_filefunc64A @112
fill_win32_filefunc64W @113

View File

@@ -0,0 +1,881 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8,00"
Name="zlibstat"
ProjectGUID="{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
<Platform
Name="Itanium"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="x86\ZlibStat$(ConfigurationName)"
IntermediateDirectory="x86\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="WIN32;ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE"
ExceptionHandling="0"
RuntimeLibrary="1"
BufferSecurityCheck="false"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:X86 /NODEFAULTLIB"
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="x64\ZlibStat$(ConfigurationName)"
IntermediateDirectory="x64\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;WIN64"
ExceptionHandling="0"
RuntimeLibrary="3"
BufferSecurityCheck="false"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:AMD64 /NODEFAULTLIB"
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|Itanium"
OutputDirectory="ia64\ZlibStat$(ConfigurationName)"
IntermediateDirectory="ia64\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="2"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;WIN64"
ExceptionHandling="0"
RuntimeLibrary="3"
BufferSecurityCheck="false"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:IA64 /NODEFAULTLIB"
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="x86\ZlibStat$(ConfigurationName)"
IntermediateDirectory="x86\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="WIN32;ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ASMV;ASMINF"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:X86 /NODEFAULTLIB"
AdditionalDependencies="..\..\masmx86\gvmat32.obj ..\..\masmx86\inffas32.obj "
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="x64\ZlibStat$(ConfigurationName)"
IntermediateDirectory="x64\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;ASMV;ASMINF;WIN64"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="2"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:AMD64 /NODEFAULTLIB"
AdditionalDependencies="..\..\masmx64\gvmat64.obj ..\..\masmx64\inffasx64.obj "
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Itanium"
OutputDirectory="ia64\ZlibStat$(ConfigurationName)"
IntermediateDirectory="ia64\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="2"
/>
<Tool
Name="VCCLCompilerTool"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;WIN64"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="2"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:IA64 /NODEFAULTLIB"
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="ReleaseWithoutAsm|Win32"
OutputDirectory="x86\ZlibStat$(ConfigurationName)"
IntermediateDirectory="x86\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="WIN32;ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:X86 /NODEFAULTLIB"
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="ReleaseWithoutAsm|x64"
OutputDirectory="x64\ZlibStat$(ConfigurationName)"
IntermediateDirectory="x64\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;WIN64"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="2"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:AMD64 /NODEFAULTLIB"
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="ReleaseWithoutAsm|Itanium"
OutputDirectory="ia64\ZlibStat$(ConfigurationName)"
IntermediateDirectory="ia64\ZlibStat$(ConfigurationName)\Tmp"
ConfigurationType="4"
InheritedPropertySheets="UpgradeFromVC70.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="2"
/>
<Tool
Name="VCCLCompilerTool"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\..;..\..\masmx86"
PreprocessorDefinitions="ZLIB_WINAPI;NO_snprintf;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_DEPRECATE;WIN64"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="2"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
PrecompiledHeaderFile="$(IntDir)/zlibstat.pch"
AssemblerListingLocation="$(IntDir)\"
ObjectFile="$(IntDir)\"
ProgramDataBaseFileName="$(OutDir)\"
WarningLevel="3"
SuppressStartupBanner="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
Culture="1036"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
AdditionalOptions="/MACHINE:IA64 /NODEFAULTLIB"
OutputFile="$(OutDir)\zlibstat.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
>
<File
RelativePath="..\..\..\adler32.c"
>
</File>
<File
RelativePath="..\..\..\compress.c"
>
</File>
<File
RelativePath="..\..\..\crc32.c"
>
</File>
<File
RelativePath="..\..\..\deflate.c"
>
</File>
<File
RelativePath="..\..\masmx86\gvmat32c.c"
>
<FileConfiguration
Name="Debug|x64"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Itanium"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|x64"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Itanium"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="ReleaseWithoutAsm|x64"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="ReleaseWithoutAsm|Itanium"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
</File>
<File
RelativePath="..\..\..\gzclose.c">
</File>
<File
RelativePath="..\..\..\gzio.c">
</File>
<File
RelativePath="..\..\..\gzlib.c">
</File>
<File
RelativePath="..\..\..\gzread.c">
</File>
<File
RelativePath="..\..\..\gzwrite.c">
</File>
<File
RelativePath="..\..\..\infback.c"
>
</File>
<File
RelativePath="..\..\masmx64\inffas8664.c"
>
<FileConfiguration
Name="Debug|Win32"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Itanium"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Itanium"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="ReleaseWithoutAsm|Win32"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
<FileConfiguration
Name="ReleaseWithoutAsm|Itanium"
ExcludedFromBuild="true"
>
<Tool
Name="VCCLCompilerTool"
/>
</FileConfiguration>
</File>
<File
RelativePath="..\..\..\inffast.c"
>
</File>
<File
RelativePath="..\..\..\inflate.c"
>
</File>
<File
RelativePath="..\..\..\inftrees.c"
>
</File>
<File
RelativePath="..\..\minizip\ioapi.c"
>
</File>
<File
RelativePath="..\..\..\trees.c"
>
</File>
<File
RelativePath="..\..\..\uncompr.c"
>
</File>
<File
RelativePath="..\..\minizip\unzip.c"
>
</File>
<File
RelativePath="..\..\minizip\zip.c"
>
</File>
<File
RelativePath=".\zlib.rc"
>
</File>
<File
RelativePath=".\zlibvc.def"
>
</File>
<File
RelativePath="..\..\..\zutil.c"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -0,0 +1,95 @@
VERSION 1.23
HEAPSIZE 1048576,8192
EXPORTS
adler32 @1
compress @2
crc32 @3
deflate @4
deflateCopy @5
deflateEnd @6
deflateInit2_ @7
deflateInit_ @8
deflateParams @9
deflateReset @10
deflateSetDictionary @11
gzclose @12
gzdopen @13
gzerror @14
gzflush @15
gzopen @16
gzread @17
gzwrite @18
inflate @19
inflateEnd @20
inflateInit2_ @21
inflateInit_ @22
inflateReset @23
inflateSetDictionary @24
inflateSync @25
uncompress @26
zlibVersion @27
gzprintf @28
gzputc @29
gzgetc @30
gzseek @31
gzrewind @32
gztell @33
gzeof @34
gzsetparams @35
zError @36
inflateSyncPoint @37
get_crc_table @38
compress2 @39
gzputs @40
gzgets @41
inflateCopy @42
inflateBackInit_ @43
inflateBack @44
inflateBackEnd @45
compressBound @46
deflateBound @47
gzclearerr @48
gzungetc @49
zlibCompileFlags @50
deflatePrime @51
unzOpen @61
unzClose @62
unzGetGlobalInfo @63
unzGetCurrentFileInfo @64
unzGoToFirstFile @65
unzGoToNextFile @66
unzOpenCurrentFile @67
unzReadCurrentFile @68
unzOpenCurrentFile3 @69
unztell @70
unzeof @71
unzCloseCurrentFile @72
unzGetGlobalComment @73
unzStringFileNameCompare @74
unzLocateFile @75
unzGetLocalExtrafield @76
unzOpen2 @77
unzOpenCurrentFile2 @78
unzOpenCurrentFilePassword @79
zipOpen @80
zipOpenNewFileInZip @81
zipWriteInFileInZip @82
zipCloseFileInZip @83
zipClose @84
zipOpenNewFileInZip2 @86
zipCloseFileInZipRaw @87
zipOpen2 @88
zipOpenNewFileInZip3 @89
unzGetFilePos @100
unzGoToFilePos @101
fill_win32_filefunc @110
fill_win32_filefunc64 @111
fill_win32_filefunc64A @112
fill_win32_filefunc64W @113

File diff suppressed because it is too large Load Diff

View File

@@ -18,10 +18,10 @@ LDFLAGS =
# variables # variables
ZLIB_LIB = zlib.lib ZLIB_LIB = zlib.lib
OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzio.obj infback.obj OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzio.obj gzlib.obj gzread.obj
OBJ2 = inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzio.obj+infback.obj OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzio.obj+gzlib.obj+gzread.obj
OBJP2 = +inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
# targets # targets
@@ -38,8 +38,16 @@ crc32.obj: crc32.c zlib.h zconf.h crc32.h
deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
gzio.obj: gzio.c zutil.h zlib.h zconf.h gzio.obj: gzio.c zutil.h zlib.h zconf.h
gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
gzread.obj: gzread.c zlib.h zconf.h gzguts.h
gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
inffast.h inffixed.h inffast.h inffixed.h

View File

@@ -4,7 +4,7 @@
<property name="nunit.location" value="c:/program files/NUnit V2.1/bin" /> <property name="nunit.location" value="c:/program files/NUnit V2.1/bin" />
<property name="build.root" value="bin" /> <property name="build.root" value="bin" />
<property name="debug" value="true" /> <property name="debug" value="true" />
<property name="nunit" value="true" /> <property name="nunit" value="true" />
@@ -16,7 +16,7 @@
</target> </target>
<target name="build" description="compiles the source code"> <target name="build" description="compiles the source code">
<mkdir dir="${build.folder}" /> <mkdir dir="${build.folder}" />
<csc target="library" output="${build.folder}DotZLib.dll" debug="${debug}"> <csc target="library" output="${build.folder}DotZLib.dll" debug="${debug}">
<references basedir="${nunit.location}"> <references basedir="${nunit.location}">

Binary file not shown.

View File

@@ -2,7 +2,7 @@ using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
// //
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
// //
@@ -13,42 +13,42 @@ using System.Runtime.CompilerServices;
[assembly: AssemblyProduct("")] [assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2004 by Henrik Ravn")] [assembly: AssemblyCopyright("(c) 2004 by Henrik Ravn")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// //
// Version information for an assembly consists of the following four values: // Version information for an assembly consists of the following four values:
// //
// Major Version // Major Version
// Minor Version // Minor Version
// Build Number // Build Number
// Revision // Revision
// //
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")]
// //
// In order to sign your assembly you must specify a key to use. Refer to the // In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing. // Microsoft .NET Framework documentation for more information on assembly signing.
// //
// Use the attributes below to control which key is used for signing. // Use the attributes below to control which key is used for signing.
// //
// Notes: // Notes:
// (*) If no key is specified, the assembly is not signed. // (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service // (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains // Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key. // a key.
// (*) If the KeyFile and the KeyName values are both specified, the // (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs: // following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used. // (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key // (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used. // in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be // When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is // relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile // located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this. // documentation for more information on this.

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -25,7 +25,7 @@ namespace DotZLib
protected uint _current; protected uint _current;
/// <summary> /// <summary>
/// Initializes a new instance of the checksum generator base - the current checksum is /// Initializes a new instance of the checksum generator base - the current checksum is
/// set to zero /// set to zero
/// </summary> /// </summary>
public ChecksumGeneratorBase() public ChecksumGeneratorBase()
@@ -61,7 +61,7 @@ namespace DotZLib
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception> /// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception> /// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception> /// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
/// <remarks>All the other <c>Update</c> methods are implmeneted in terms of this one. /// <remarks>All the other <c>Update</c> methods are implmeneted in terms of this one.
/// This is therefore the only method a derived class has to implement</remarks> /// This is therefore the only method a derived class has to implement</remarks>
public abstract void Update(byte[] data, int offset, int count); public abstract void Update(byte[] data, int offset, int count);
@@ -101,7 +101,7 @@ namespace DotZLib
/// <summary> /// <summary>
/// Implements a CRC32 checksum generator /// Implements a CRC32 checksum generator
/// </summary> /// </summary>
public sealed class CRC32Checksum : ChecksumGeneratorBase public sealed class CRC32Checksum : ChecksumGeneratorBase
{ {
#region DLL imports #region DLL imports
@@ -152,7 +152,7 @@ namespace DotZLib
/// <summary> /// <summary>
/// Implements a checksum generator that computes the Adler checksum on data /// Implements a checksum generator that computes the Adler checksum on data
/// </summary> /// </summary>
public sealed class AdlerChecksum : ChecksumGeneratorBase public sealed class AdlerChecksum : ChecksumGeneratorBase
{ {
#region DLL imports #region DLL imports

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -25,7 +25,7 @@ namespace DotZLib
#endregion #endregion
public CircularBuffer(int capacity) public CircularBuffer(int capacity)
{ {
Debug.Assert( capacity > 0 ); Debug.Assert( capacity > 0 );
_buffer = new byte[capacity]; _buffer = new byte[capacity];
_capacity = capacity; _capacity = capacity;

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -19,7 +19,7 @@ namespace DotZLib
#region Data members #region Data members
/// <summary> /// <summary>
/// Instance of the internal zlib buffer structure that is /// Instance of the internal zlib buffer structure that is
/// passed to all functions in the zlib dll /// passed to all functions in the zlib dll
/// </summary> /// </summary>
internal ZStream _ztream = new ZStream(); internal ZStream _ztream = new ZStream();
@@ -45,7 +45,7 @@ namespace DotZLib
#endregion #endregion
/// <summary> /// <summary>
/// Initializes a new instance of the <c>CodeBase</c> class. /// Initializes a new instance of the <c>CodeBase</c> class.
/// </summary> /// </summary>
public CodecBase() public CodecBase()
{ {
@@ -77,7 +77,7 @@ namespace DotZLib
if (_ztream.total_out > 0) if (_ztream.total_out > 0)
{ {
if (DataAvailable != null) if (DataAvailable != null)
DataAvailable( _outBuffer, 0, (int)_ztream.total_out); DataAvailable( _outBuffer, 0, (int)_ztream.total_out);
resetOutput(); resetOutput();
} }
} }

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -56,7 +56,7 @@ namespace DotZLib
if (data == null) throw new ArgumentNullException(); if (data == null) throw new ArgumentNullException();
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException(); if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > data.Length) throw new ArgumentException(); if ((offset+count) > data.Length) throw new ArgumentException();
int total = count; int total = count;
int inputIndex = offset; int inputIndex = offset;
int err = 0; int err = 0;
@@ -86,7 +86,7 @@ namespace DotZLib
public override void Finish() public override void Finish()
{ {
int err; int err;
do do
{ {
err = deflate(ref _ztream, (int)FlushTypes.Finish); err = deflate(ref _ztream, (int)FlushTypes.Finish);
OnDataAvailable(); OnDataAvailable();

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -19,7 +19,7 @@ namespace DotZLib
/// <summary> /// <summary>
/// Defines constants for the various flush types used with zlib /// Defines constants for the various flush types used with zlib
/// </summary> /// </summary>
internal enum FlushTypes internal enum FlushTypes
{ {
None, Partial, Sync, Full, Finish, Block None, Partial, Sync, Full, Finish, Block
} }
@@ -38,7 +38,7 @@ namespace DotZLib
public uint total_out; public uint total_out;
[MarshalAs(UnmanagedType.LPStr)] [MarshalAs(UnmanagedType.LPStr)]
string msg; string msg;
uint state; uint state;
uint zalloc; uint zalloc;
@@ -51,7 +51,7 @@ namespace DotZLib
} }
#endregion #endregion
#endregion #endregion
#region Public enums #region Public enums
@@ -63,7 +63,7 @@ namespace DotZLib
/// <summary> /// <summary>
/// The default compression level with a reasonable compromise between compression and speed /// The default compression level with a reasonable compromise between compression and speed
/// </summary> /// </summary>
Default = -1, Default = -1,
/// <summary> /// <summary>
/// No compression at all. The data are passed straight through. /// No compression at all. The data are passed straight through.
/// </summary> /// </summary>
@@ -71,7 +71,7 @@ namespace DotZLib
/// <summary> /// <summary>
/// The maximum compression rate available. /// The maximum compression rate available.
/// </summary> /// </summary>
Best = 9, Best = 9,
/// <summary> /// <summary>
/// The fastest available compression level. /// The fastest available compression level.
/// </summary> /// </summary>
@@ -86,7 +86,7 @@ namespace DotZLib
public class ZLibException : ApplicationException public class ZLibException : ApplicationException
{ {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ZLibException"/> class with a specified /// Initializes a new instance of the <see cref="ZLibException"/> class with a specified
/// error message and error code /// error message and error code
/// </summary> /// </summary>
/// <param name="errorCode">The zlib error code that caused the exception</param> /// <param name="errorCode">The zlib error code that caused the exception</param>
@@ -96,7 +96,7 @@ namespace DotZLib
} }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ZLibException"/> class with a specified /// Initializes a new instance of the <see cref="ZLibException"/> class with a specified
/// error code /// error code
/// </summary> /// </summary>
/// <param name="errorCode">The zlib error code that caused the exception</param> /// <param name="errorCode">The zlib error code that caused the exception</param>
@@ -109,7 +109,7 @@ namespace DotZLib
#region Interfaces #region Interfaces
/// <summary> /// <summary>
/// Declares methods and properties that enables a running checksum to be calculated /// Declares methods and properties that enables a running checksum to be calculated
/// </summary> /// </summary>
public interface ChecksumGenerator public interface ChecksumGenerator
{ {
@@ -163,7 +163,7 @@ namespace DotZLib
/// <paramref name="data">The byte array containing the processed data</paramref> /// <paramref name="data">The byte array containing the processed data</paramref>
/// <paramref name="startIndex">The index of the first processed byte in <c>data</c></paramref> /// <paramref name="startIndex">The index of the first processed byte in <c>data</c></paramref>
/// <paramref name="count">The number of processed bytes available</paramref> /// <paramref name="count">The number of processed bytes available</paramref>
/// <remarks>On return from this method, the data may be overwritten, so grab it while you can. /// <remarks>On return from this method, the data may be overwritten, so grab it while you can.
/// You cannot assume that startIndex will be zero. /// You cannot assume that startIndex will be zero.
/// </remarks> /// </remarks>
public delegate void DataAvailableHandler(byte[] data, int startIndex, int count); public delegate void DataAvailableHandler(byte[] data, int startIndex, int count);

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -84,7 +84,7 @@ namespace DotZLib
return !_isWriting; return !_isWriting;
} }
} }
/// <summary> /// <summary>
/// Returns false. /// Returns false.
@@ -96,7 +96,7 @@ namespace DotZLib
return false; return false;
} }
} }
/// <summary> /// <summary>
/// Returns true if this tsream is writeable, false otherwise /// Returns true if this tsream is writeable, false otherwise
/// </summary> /// </summary>
@@ -108,7 +108,7 @@ namespace DotZLib
} }
} }
#endregion #endregion
#region Destructor & IDispose stuff #region Destructor & IDispose stuff
/// <summary> /// <summary>
@@ -137,7 +137,7 @@ namespace DotZLib
} }
} }
#endregion #endregion
#region Basic reading and writing #region Basic reading and writing
/// <summary> /// <summary>
/// Attempts to read a number of bytes from the stream. /// Attempts to read a number of bytes from the stream.
@@ -244,7 +244,7 @@ namespace DotZLib
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
/// <summary> /// <summary>
/// Not suppported. /// Not suppported.
/// </summary> /// </summary>
@@ -256,7 +256,7 @@ namespace DotZLib
{ {
throw new NotSupportedException(); throw new NotSupportedException();
} }
/// <summary> /// <summary>
/// Flushes the <c>GZipStream</c>. /// Flushes the <c>GZipStream</c>.
/// </summary> /// </summary>
@@ -266,7 +266,7 @@ namespace DotZLib
{ {
// left empty on purpose // left empty on purpose
} }
/// <summary> /// <summary>
/// Gets/sets the current position in the <c>GZipStream</c>. Not suppported. /// Gets/sets the current position in the <c>GZipStream</c>. Not suppported.
/// </summary> /// </summary>
@@ -283,7 +283,7 @@ namespace DotZLib
throw new NotSupportedException(); throw new NotSupportedException();
} }
} }
/// <summary> /// <summary>
/// Gets the size of the stream. Not suppported. /// Gets the size of the stream. Not suppported.
/// </summary> /// </summary>

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -11,7 +11,7 @@ using System.Runtime.InteropServices;
namespace DotZLib namespace DotZLib
{ {
/// <summary> /// <summary>
/// Implements a data decompressor, using the inflate algorithm in the ZLib dll /// Implements a data decompressor, using the inflate algorithm in the ZLib dll
/// </summary> /// </summary>
@@ -84,7 +84,7 @@ namespace DotZLib
public override void Finish() public override void Finish()
{ {
int err; int err;
do do
{ {
err = inflate(ref _ztream, (int)FlushTypes.Finish); err = inflate(ref _ztream, (int)FlushTypes.Finish);
OnDataAvailable(); OnDataAvailable();

View File

@@ -1,7 +1,7 @@
// //
// <20> Copyright Henrik Ravn 2004 // <20> Copyright Henrik Ravn 2004
// //
// Use, modification and distribution are subject to the Boost Software License, Version 1.0. // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// //
@@ -225,7 +225,7 @@ namespace DotZLibTests
[Test] [Test]
public void Inflate_Expand() public void Inflate_Expand()
{ {
uncompressedData.Clear(); uncompressedData.Clear();
using (Inflater inf = new Inflater()) using (Inflater inf = new Inflater())

View File

@@ -1,6 +1,6 @@
This directory contains a .Net wrapper class library for the ZLib1.dll This directory contains a .Net wrapper class library for the ZLib1.dll
The wrapper includes support for inflating/deflating memory buffers, The wrapper includes support for inflating/deflating memory buffers,
.Net streaming wrappers for the gz streams part of zlib, and wrappers .Net streaming wrappers for the gz streams part of zlib, and wrappers
for the checksum parts of zlib. See DotZLib/UnitTests.cs for examples. for the checksum parts of zlib. See DotZLib/UnitTests.cs for examples.
@@ -26,11 +26,11 @@ Build instructions:
1. Using Visual Studio.Net 2003: 1. Using Visual Studio.Net 2003:
Open DotZLib.sln in VS.Net and build from there. Output file (DotZLib.dll) Open DotZLib.sln in VS.Net and build from there. Output file (DotZLib.dll)
will be found ./DotZLib/bin/release or ./DotZLib/bin/debug, depending on will be found ./DotZLib/bin/release or ./DotZLib/bin/debug, depending on
you are building the release or debug version of the library. Check you are building the release or debug version of the library. Check
DotZLib/UnitTests.cs for instructions on how to include unit tests in the DotZLib/UnitTests.cs for instructions on how to include unit tests in the
build. build.
2. Using NAnt: 2. Using NAnt:
Open a command prompt with access to the build environment and run nant Open a command prompt with access to the build environment and run nant
in the same directory as the DotZLib.build file. in the same directory as the DotZLib.build file.
@@ -38,15 +38,15 @@ Build instructions:
debug={true|false} to toggle between release/debug builds (default=true). debug={true|false} to toggle between release/debug builds (default=true).
nunit={true|false} to include or esclude unit tests (default=true). nunit={true|false} to include or esclude unit tests (default=true).
Also the target clean will remove binaries. Also the target clean will remove binaries.
Output file (DotZLib.dll) will be found in either ./DotZLib/bin/release Output file (DotZLib.dll) will be found in either ./DotZLib/bin/release
or ./DotZLib/bin/debug, depending on whether you are building the release or ./DotZLib/bin/debug, depending on whether you are building the release
or debug version of the library. or debug version of the library.
Examples: Examples:
nant -D:debug=false -D:nunit=false nant -D:debug=false -D:nunit=false
will build a release mode version of the library without unit tests. will build a release mode version of the library without unit tests.
nant nant
will build a debug version of the library with unit tests will build a debug version of the library with unit tests
nant clean nant clean
will remove all previously built files. will remove all previously built files.
@@ -54,5 +54,5 @@ Build instructions:
--------------------------------- ---------------------------------
Copyright (c) Henrik Ravn 2004 Copyright (c) Henrik Ravn 2004
Use, modification and distribution are subject to the Boost Software License, Version 1.0. Use, modification and distribution are subject to the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

View File

@@ -1,5 +1,5 @@
/* infback9.c -- inflate deflate64 data using a call-back interface /* infback9.c -- inflate deflate64 data using a call-back interface
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2008 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -242,7 +242,7 @@ void FAR *out_desc;
code const FAR *distcode; /* starting table for distance codes */ code const FAR *distcode; /* starting table for distance codes */
unsigned lenbits; /* index bits for lencode */ unsigned lenbits; /* index bits for lencode */
unsigned distbits; /* index bits for distcode */ unsigned distbits; /* index bits for distcode */
code this; /* current decoding table entry */ code here; /* current decoding table entry */
code last; /* parent table entry */ code last; /* parent table entry */
unsigned len; /* length to copy for repeats, bits to drop */ unsigned len; /* length to copy for repeats, bits to drop */
int ret; /* return code */ int ret; /* return code */
@@ -384,19 +384,19 @@ void FAR *out_desc;
state->have = 0; state->have = 0;
while (state->have < state->nlen + state->ndist) { while (state->have < state->nlen + state->ndist) {
for (;;) { for (;;) {
this = lencode[BITS(lenbits)]; here = lencode[BITS(lenbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if (this.val < 16) { if (here.val < 16) {
NEEDBITS(this.bits); NEEDBITS(here.bits);
DROPBITS(this.bits); DROPBITS(here.bits);
state->lens[state->have++] = this.val; state->lens[state->have++] = here.val;
} }
else { else {
if (this.val == 16) { if (here.val == 16) {
NEEDBITS(this.bits + 2); NEEDBITS(here.bits + 2);
DROPBITS(this.bits); DROPBITS(here.bits);
if (state->have == 0) { if (state->have == 0) {
strm->msg = (char *)"invalid bit length repeat"; strm->msg = (char *)"invalid bit length repeat";
mode = BAD; mode = BAD;
@@ -406,16 +406,16 @@ void FAR *out_desc;
copy = 3 + BITS(2); copy = 3 + BITS(2);
DROPBITS(2); DROPBITS(2);
} }
else if (this.val == 17) { else if (here.val == 17) {
NEEDBITS(this.bits + 3); NEEDBITS(here.bits + 3);
DROPBITS(this.bits); DROPBITS(here.bits);
len = 0; len = 0;
copy = 3 + BITS(3); copy = 3 + BITS(3);
DROPBITS(3); DROPBITS(3);
} }
else { else {
NEEDBITS(this.bits + 7); NEEDBITS(here.bits + 7);
DROPBITS(this.bits); DROPBITS(here.bits);
len = 0; len = 0;
copy = 11 + BITS(7); copy = 11 + BITS(7);
DROPBITS(7); DROPBITS(7);
@@ -433,7 +433,16 @@ void FAR *out_desc;
/* handle error breaks in while */ /* handle error breaks in while */
if (mode == BAD) break; if (mode == BAD) break;
/* build code tables */ /* check for end-of-block code (better have one) */
if (state->lens[256] == 0) {
strm->msg = (char *)"invalid code -- missing end-of-block";
mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftree9.h
concerning the ENOUGH constants, which depend on those values */
state->next = state->codes; state->next = state->codes;
lencode = (code const FAR *)(state->next); lencode = (code const FAR *)(state->next);
lenbits = 9; lenbits = 9;
@@ -460,28 +469,28 @@ void FAR *out_desc;
case LEN: case LEN:
/* get a literal, length, or end-of-block code */ /* get a literal, length, or end-of-block code */
for (;;) { for (;;) {
this = lencode[BITS(lenbits)]; here = lencode[BITS(lenbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if (this.op && (this.op & 0xf0) == 0) { if (here.op && (here.op & 0xf0) == 0) {
last = this; last = here;
for (;;) { for (;;) {
this = lencode[last.val + here = lencode[last.val +
(BITS(last.bits + last.op) >> last.bits)]; (BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + this.bits) <= bits) break; if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
DROPBITS(last.bits); DROPBITS(last.bits);
} }
DROPBITS(this.bits); DROPBITS(here.bits);
length = (unsigned)this.val; length = (unsigned)here.val;
/* process literal */ /* process literal */
if (this.op == 0) { if (here.op == 0) {
Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" : "inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", this.val)); "inflate: literal 0x%02x\n", here.val));
ROOM(); ROOM();
*put++ = (unsigned char)(length); *put++ = (unsigned char)(length);
left--; left--;
@@ -490,21 +499,21 @@ void FAR *out_desc;
} }
/* process end of block */ /* process end of block */
if (this.op & 32) { if (here.op & 32) {
Tracevv((stderr, "inflate: end of block\n")); Tracevv((stderr, "inflate: end of block\n"));
mode = TYPE; mode = TYPE;
break; break;
} }
/* invalid code */ /* invalid code */
if (this.op & 64) { if (here.op & 64) {
strm->msg = (char *)"invalid literal/length code"; strm->msg = (char *)"invalid literal/length code";
mode = BAD; mode = BAD;
break; break;
} }
/* length code -- get extra bits, if any */ /* length code -- get extra bits, if any */
extra = (unsigned)(this.op) & 31; extra = (unsigned)(here.op) & 31;
if (extra != 0) { if (extra != 0) {
NEEDBITS(extra); NEEDBITS(extra);
length += BITS(extra); length += BITS(extra);
@@ -514,30 +523,30 @@ void FAR *out_desc;
/* get distance code */ /* get distance code */
for (;;) { for (;;) {
this = distcode[BITS(distbits)]; here = distcode[BITS(distbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if ((this.op & 0xf0) == 0) { if ((here.op & 0xf0) == 0) {
last = this; last = here;
for (;;) { for (;;) {
this = distcode[last.val + here = distcode[last.val +
(BITS(last.bits + last.op) >> last.bits)]; (BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + this.bits) <= bits) break; if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
DROPBITS(last.bits); DROPBITS(last.bits);
} }
DROPBITS(this.bits); DROPBITS(here.bits);
if (this.op & 64) { if (here.op & 64) {
strm->msg = (char *)"invalid distance code"; strm->msg = (char *)"invalid distance code";
mode = BAD; mode = BAD;
break; break;
} }
offset = (unsigned)this.val; offset = (unsigned)here.val;
/* get distance extra bits, if any */ /* get distance extra bits, if any */
extra = (unsigned)(this.op) & 15; extra = (unsigned)(here.op) & 15;
if (extra != 0) { if (extra != 0) {
NEEDBITS(extra); NEEDBITS(extra);
offset += BITS(extra); offset += BITS(extra);

View File

@@ -1,5 +1,5 @@
/* inftree9.c -- generate Huffman trees for efficient decoding /* inftree9.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2005 Mark Adler * Copyright (C) 1995-2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -9,7 +9,7 @@
#define MAXBITS 15 #define MAXBITS 15
const char inflate9_copyright[] = const char inflate9_copyright[] =
" inflate9 1.2.3.1 Copyright 1995-2005 Mark Adler "; " inflate9 1.2.3.8 Copyright 1995-2010 Mark Adler ";
/* /*
If you use the zlib library in a product, an acknowledgment is welcome 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 in the documentation of your product. If for some reason you cannot
@@ -64,7 +64,7 @@ unsigned short FAR *work;
static const unsigned short lext[31] = { /* Length codes 257..285 extra */ static const unsigned short lext[31] = { /* Length codes 257..285 extra */
128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129, 128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129,
130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132, 130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132,
133, 133, 133, 133, 144, 74, 196}; 133, 133, 133, 133, 144, 78, 75};
static const unsigned short dbase[32] = { /* Distance codes 0..31 base */ static const unsigned short dbase[32] = { /* Distance codes 0..31 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49,
65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073,
@@ -160,11 +160,10 @@ unsigned short FAR *work;
entered in the tables. entered in the tables.
used keeps track of how many table entries have been allocated from the 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 provided *table space. It is checked for LENS and DIST tables against
against the space in *table, ENOUGH, minus the maximum space needed by the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the worst case distance code, MAXD. This should never happen, but the the initial root table size constants. See the comments in inftree9.h
sufficiency of ENOUGH has not been proven exhaustively, hence the check. for more information.
This assumes that when type == LENS, bits == 9.
sym increments through all symbols, and the loop terminates when sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This all codes of length max, i.e. all codes, have been processed. This
@@ -203,7 +202,8 @@ unsigned short FAR *work;
mask = used - 1; /* mask for comparing low */ mask = used - 1; /* mask for comparing low */
/* check available table space */ /* check available table space */
if (type == LENS && used >= ENOUGH - MAXD) if ((type == LENS && used >= ENOUGH_LENS) ||
(type == DISTS && used >= ENOUGH_DISTS))
return 1; return 1;
/* process all codes and make table entries */ /* process all codes and make table entries */
@@ -270,7 +270,8 @@ unsigned short FAR *work;
/* check for enough space */ /* check for enough space */
used += 1U << curr; used += 1U << curr;
if (type == LENS && used >= ENOUGH - MAXD) if ((type == LENS && used >= ENOUGH_LENS) ||
(type == DISTS && used >= ENOUGH_DISTS))
return 1; return 1;
/* point entry in root table to sub-table */ /* point entry in root table to sub-table */

View File

@@ -1,5 +1,5 @@
/* inftree9.h -- header to use inftree9.c /* inftree9.h -- header to use inftree9.c
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2008 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -35,15 +35,21 @@ typedef struct {
01000000 - invalid code 01000000 - invalid code
*/ */
/* Maximum size of dynamic tree. The maximum found in a long but non- /* Maximum size of the dynamic table. The maximum number of code structures is
exhaustive search was 1444 code structures (852 for length/literals 1446, which is the sum of 852 for literal/length codes and 594 for distance
and 592 for distances, the latter actually the result of an codes. These values were found by exhaustive searches using the program
exhaustive search). The true maximum is not known, but the value examples/enough.c found in the zlib distribtution. The arguments to that
below is more than safe. */ program are the number of symbols, the initial root table size, and the
#define ENOUGH 2048 maximum bit length of a code. "enough 286 9 15" for literal/length codes
#define MAXD 592 returns returns 852, and "enough 32 6 15" for distance codes returns 594.
The initial root table size (9 or 6) is found in the fifth argument of the
inflate_table() calls in infback9.c. If the root table size is changed,
then these maximum sizes would be need to be recalculated and updated. */
#define ENOUGH_LENS 852
#define ENOUGH_DISTS 594
#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
/* Type of code to build for inftable() */ /* Type of code to build for inflate_table9() */
typedef enum { typedef enum {
CODES, CODES,
LENS, LENS,

View File

@@ -406,7 +406,8 @@ LoopCmps:
add rdx,8+8+8 add rdx,8+8+8
jmp short LoopCmps jnz short LoopCmps
jmp short LenMaximum
LeaveLoopCmps16: add rdx,8 LeaveLoopCmps16: add rdx,8
LeaveLoopCmps8: add rdx,8 LeaveLoopCmps8: add rdx,8
LeaveLoopCmps: LeaveLoopCmps:

Binary file not shown.

View File

@@ -111,11 +111,11 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
type_ar ar; type_ar ar;
void inffas8664fnc(struct inffast_ar * par); void inffas8664fnc(struct inffast_ar * par);
#if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64)) #if (defined( __GNUC__ ) && defined( __amd64__ ) && ! defined( __i386 )) || (defined(_MSC_VER) && defined(_M_AMD64))
#define PAD_AVAIL_IN 6 #define PAD_AVAIL_IN 6
#define PAD_AVAIL_OUT 258 #define PAD_AVAIL_OUT 258
#else #else
#define PAD_AVAIL_IN 5 #define PAD_AVAIL_IN 5
#define PAD_AVAIL_OUT 257 #define PAD_AVAIL_OUT 257

View File

@@ -11,7 +11,7 @@
; ;
; ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK ; ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK
; ;
; (you can get Windows 2003 server DDK with ml64 and cl.exe for AMD64 from ; (you can get Windows 2003 server DDK with ml64 and cl.exe for AMD64 from
; http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price) ; http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price)
; ;
@@ -379,7 +379,7 @@ L_break_loop_with_status:
mov r14,[rsp-40] mov r14,[rsp-40]
mov r15,[rsp-48] mov r15,[rsp-48]
mov rbx,[rsp-56] mov rbx,[rsp-56]
ret 0 ret 0
; : ; :
; : "m" (ar) ; : "m" (ar)

Binary file not shown.

View File

@@ -24,5 +24,5 @@ run bld_64.bat with Microsoft Macro Assembler (x64) for AMD64 (ml64.exe)
ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK ml64.exe is given with Visual Studio 2005, Windows 2003 server DDK
You can get Windows 2003 server DDK with ml64 and cl for AMD64 from You can get Windows 2003 server DDK with ml64 and cl for AMD64 from
http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price) http://www.microsoft.com/whdc/devtools/ddk/default.mspx for low price)

View File

@@ -1,2 +1,2 @@
ml /coff /Zi /c /Flgvmat32.lst gvmat32.asm ml /coff /Zi /c /Flgvmat32.lst gvmat32.asm
ml /coff /Zi /c /Flinffas32.lst inffas32.asm ml /coff /Zi /c /Flinffas32.lst inffas32.asm

View File

@@ -14,7 +14,7 @@
; ;
; this file contain two implementation of longest_match ; this file contain two implementation of longest_match
; ;
; longest_match_7fff : written 1996 by Gilles Vollant optimized for ; longest_match_7fff : written 1996 by Gilles Vollant optimized for
; first Pentium. Assume s->w_mask == 0x7fff ; first Pentium. Assume s->w_mask == 0x7fff
; longest_match_686 : written by Brian raiter (1998), optimized for Pentium Pro ; longest_match_686 : written by Brian raiter (1998), optimized for Pentium Pro
; ;
@@ -39,7 +39,7 @@
; ;
; compile the asm file running ; compile the asm file running
; ml /coff /Zi /c /Flgvmat32.lst /DNOOLDPENTIUMCODE gvmat32.asm ; ml /coff /Zi /c /Flgvmat32.lst /DNOOLDPENTIUMCODE gvmat32.asm
; and do not include gvmat32c.c in your project (ou define also ; and do not include gvmat32c.c in your project (ou define also
; NOOLDPENTIUMCODE) ; NOOLDPENTIUMCODE)
; ;
; note : as I known, longest_match_686 is very faster than longest_match_7fff ; note : as I known, longest_match_686 is very faster than longest_match_7fff
@@ -113,7 +113,7 @@ IFDEF NOUNDERLINE
IFDEF NOOLDPENTIUMCODE IFDEF NOOLDPENTIUMCODE
public longest_match public longest_match
public match_init public match_init
ELSE ELSE
public longest_match_7fff public longest_match_7fff
public cpudetect32 public cpudetect32
public longest_match_686 public longest_match_686
@@ -959,7 +959,7 @@ IFDEF NOOLDPENTIUMCODE
_match_init proc near _match_init proc near
ret ret
_match_init endp _match_init endp
ENDIF ENDIF
ELSE ELSE
IFDEF NOUNDERLINE IFDEF NOUNDERLINE
longest_match_686 endp longest_match_686 endp

Binary file not shown.

View File

@@ -16,7 +16,7 @@
; * enabled. I will attempt to merge the MMX code into this version. Newer ; * enabled. I will attempt to merge the MMX code into this version. Newer
; * versions of this and inffast.S can be found at ; * versions of this and inffast.S can be found at
; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/ ; * http://www.eetbeetee.com/zlib/ and http://www.charm.net/~christop/zlib/
; * ; *
; * 2005 : modification by Gilles Vollant ; * 2005 : modification by Gilles Vollant
; */ ; */
; For Visual C++ 4.x and higher and ML 6.x and higher ; For Visual C++ 4.x and higher and ML 6.x and higher
@@ -33,7 +33,7 @@
; zlib122sup is 0 fort zlib 1.2.2.1 and lower ; zlib122sup is 0 fort zlib 1.2.2.1 and lower
; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head ; zlib122sup is 8 fort zlib 1.2.2.2 and more (with addition of dmax and head
; in inflate_state in inflate.h) ; in inflate_state in inflate.h)
zlib1222sup equ 8 zlib1222sup equ 8

Binary file not shown.

View File

@@ -1,67 +0,0 @@
Change in 1.01e (12 feb 05)
- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter)
- Fix possible memory leak in unzip.c (Zoran Stevanovic)
Change in 1.01b (20 may 04)
- Integrate patch from Debian package (submited by Mark Brown)
- Add tools mztools from Xavier Roche
Change in 1.01 (8 may 04)
- fix buffer overrun risk in unzip.c (Xavier Roche)
- fix a minor buffer insecurity in minizip.c (Mike Whittaker)
Change in 1.00: (10 sept 03)
- rename to 1.00
- cosmetic code change
Change in 0.22: (19 May 03)
- crypting support (unless you define NOCRYPT)
- append file in existing zipfile
Change in 0.21: (10 Mar 03)
- bug fixes
Change in 0.17: (27 Jan 02)
- bug fixes
Change in 0.16: (19 Jan 02)
- Support of ioapi for virtualize zip file access
Change in 0.15: (19 Mar 98)
- fix memory leak in minizip.c
Change in 0.14: (10 Mar 98)
- fix bugs in minizip.c sample for zipping big file
- fix problem in month in date handling
- fix bug in unzlocal_GetCurrentFileInfoInternal in unzip.c for
comment handling
Change in 0.13: (6 Mar 98)
- fix bugs in zip.c
- add real minizip sample
Change in 0.12: (4 Mar 98)
- add zip.c and zip.h for creates .zip file
- fix change_file_date in miniunz.c for Unix (Jean-loup Gailly)
- fix miniunz.c for file without specific record for directory
Change in 0.11: (3 Mar 98)
- fix bug in unzGetCurrentFileInfo for get extra field and comment
- enhance miniunz sample, remove the bad unztst.c sample
Change in 0.10: (2 Mar 98)
- fix bug in unzReadCurrentFile
- rename unzip* to unz* function and structure
- remove Windows-like hungary notation variable name
- modify some structure in unzip.h
- add somes comment in source
- remove unzipGetcCurrentFile function
- replace ZUNZEXPORT by ZEXPORT
- add unzGetLocalExtrafield for get the local extrafield info
- add a new sample, miniunz.c
Change in 0.4: (25 Feb 98)
- suppress the type unzipFileInZip.
Only on file in the zipfile can be open at the same time
- fix somes typo in code
- added tm_unz structure in unzip_file_info (date/time in readable format)

View File

@@ -0,0 +1,6 @@
MiniZip64 was derrived from MiniZip at version 1.01f
Change in 1.0 (Okt 2009)
- **TODO - Add history**

View File

@@ -0,0 +1,79 @@
MiniZip64 - Copyright (c) 2009-2010 - Mathias Svensson - Built from MiniZip by Gilles Vollant
Introduction
---------------------
MiniZip64 is built from MiniZip by Gilles Vollant ( http://www.winimage.com/zLibDll/minizip.html )
When adding ZIP64 support into minizip it would result into breaking compatibility with current minizip.
And since breaking compatibility in minizip is not wanted. I decided to create a fork of minizip
and create minizip64.
Even though MiniZip64 is build from MiniZip, all functions and struct's have changed name so that it
would not collide with each other.
Background
---------------------
When adding ZIP64 support I found that Even Rouault have added ZIP64 support for unzip.c into minizip
for a open source project called gdal ( http://www.gdal.org/ )
That was used as a starting point. And after that ZIP64 support was added to zip.c
some refactoring and code cleanup was also done.
Changed from MiniZip to MiniZip64
-------------------------------------
* Filenames has got a '64' at the end of them . eg unzip.c is now called unzip64.c
* Added ZIP64 support for unzip ( by Even Rouault )
* Added ZIP64 support for zip ( by Mathias Svensson )
* Reverted some changed that Even Rouault did.
* Bunch of patches received from Gulles Vollant that he received for MiniZip from various users.
* Added unzip patch for BZIP Compression method (patch create by Daniel Borca)
* Added BZIP Compress method for zip
* Did some refactoring and code cleanup
Credits
Gilles Vollant - Original MiniZip author
Even Rouault - ZIP64 unzip Support
Daniel Borca - BZip Compression method support in unzip
Mathias Svensson - ZIP64 zip support
Mathias Svensson - BZip Compression method support in zip
Resources
ZipLayout http://result42.com/projects/ZipFileLayout
Command line tool for Windows that shows the layout and information of the headers in a zip archive.
Used when debugging and validating the creation of zip files using MiniZip64
ZIP App Note http://www.pkware.com/documents/casestudies/APPNOTE.TXT
Zip File specification
Notes.
* To be able to use BZip compression method in zip64.c or unzip64.c the BZIP2 lib is needed and HAVE_BZIP2 need to be defined.
License
----------------------------------------------------------
Condition of use and distribution are the same than zlib :
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------

View File

@@ -87,13 +87,12 @@ static void init_keys(const char* passwd,unsigned long* pkeys,const unsigned lon
# define ZCR_SEED2 3141592654UL /* use PI as default pattern */ # define ZCR_SEED2 3141592654UL /* use PI as default pattern */
# endif # endif
static int crypthead(passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypting) static int crypthead(const char* passwd, /* password string */
const char *passwd; /* password string */ unsigned char* buf, /* where to write header */
unsigned char *buf; /* where to write header */ int bufSize,
int bufSize; unsigned long* pkeys,
unsigned long* pkeys; const unsigned long* pcrc_32_tab,
const unsigned long* pcrc_32_tab; unsigned long crcForCrypting)
unsigned long crcForCrypting;
{ {
int n; /* index in random header */ int n; /* index in random header */
int t; /* temporary */ int t; /* temporary */
@@ -124,8 +123,8 @@ static int crypthead(passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypting)
{ {
buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t); buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
} }
buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t); buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t); buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
return n; return n;
} }

View File

@@ -1,74 +1,86 @@
/* ioapi.c -- IO base function header for compress/uncompress .zip /* ioapi.h -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Version 1.01e, February 12th, 2005 Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Copyright (C) 1998-2005 Gilles Vollant
*/ */
#include <stdio.h> #if (defined(_WIN32))
#include <stdlib.h> #define _CRT_SECURE_NO_WARNINGS
#include <string.h> #endif
#include "zlib.h"
#include "ioapi.h" #include "ioapi.h"
voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)
{
if (pfilefunc->zfile_func64.zopen64_file != NULL)
return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode);
else
{
return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode);
}
}
long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)
{
if (pfilefunc->zfile_func64.zseek64_file != NULL)
return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin);
else
{
uLong offsetTruncated = (uLong)offset;
if (offsetTruncated != offset)
return -1;
else
return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin);
}
}
ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)
{
if (pfilefunc->zfile_func64.zseek64_file != NULL)
return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream);
else
{
uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream);
if ((tell_uLong) == ((uLong)-1))
return (ZPOS64_T)-1;
else
return tell_uLong;
}
}
void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32)
{
p_filefunc64_32->zfile_func64.zopen64_file = NULL;
p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file;
p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file;
p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file;
p_filefunc64_32->zfile_func64.ztell64_file = NULL;
p_filefunc64_32->zfile_func64.zseek64_file = NULL;
p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file;
p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque;
p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file;
p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file;
}
/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
#ifndef SEEK_CUR static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode));
#define SEEK_CUR 1 static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
#endif static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size));
static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream));
static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream));
static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream));
#ifndef SEEK_END static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
#define SEEK_END 2
#endif
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
voidpf ZCALLBACK fopen_file_func OF((
voidpf opaque,
const char* filename,
int mode));
uLong ZCALLBACK fread_file_func OF((
voidpf opaque,
voidpf stream,
void* buf,
uLong size));
uLong ZCALLBACK fwrite_file_func OF((
voidpf opaque,
voidpf stream,
const void* buf,
uLong size));
long ZCALLBACK ftell_file_func OF((
voidpf opaque,
voidpf stream));
long ZCALLBACK fseek_file_func OF((
voidpf opaque,
voidpf stream,
uLong offset,
int origin));
int ZCALLBACK fclose_file_func OF((
voidpf opaque,
voidpf stream));
int ZCALLBACK ferror_file_func OF((
voidpf opaque,
voidpf stream));
voidpf ZCALLBACK fopen_file_func (opaque, filename, mode)
voidpf opaque;
const char* filename;
int mode;
{ {
FILE* file = NULL; FILE* file = NULL;
const char* mode_fopen = NULL; const char* mode_fopen = NULL;
@@ -86,44 +98,55 @@ voidpf ZCALLBACK fopen_file_func (opaque, filename, mode)
return file; return file;
} }
static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode)
{
FILE* file = NULL;
const char* mode_fopen = NULL;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
mode_fopen = "rb";
else
if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
mode_fopen = "r+b";
else
if (mode & ZLIB_FILEFUNC_MODE_CREATE)
mode_fopen = "wb";
uLong ZCALLBACK fread_file_func (opaque, stream, buf, size) if ((filename!=NULL) && (mode_fopen != NULL))
voidpf opaque; file = fopen64((const char*)filename, mode_fopen);
voidpf stream; return file;
void* buf; }
uLong size;
static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
{ {
uLong ret; uLong ret;
ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
return ret; return ret;
} }
static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
uLong ZCALLBACK fwrite_file_func (opaque, stream, buf, size)
voidpf opaque;
voidpf stream;
const void* buf;
uLong size;
{ {
uLong ret; uLong ret;
ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
return ret; return ret;
} }
long ZCALLBACK ftell_file_func (opaque, stream) static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
voidpf opaque;
voidpf stream;
{ {
long ret; long ret;
ret = ftell((FILE *)stream); ret = ftell((FILE *)stream);
return ret; return ret;
} }
long ZCALLBACK fseek_file_func (opaque, stream, offset, origin)
voidpf opaque; static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
voidpf stream; {
uLong offset; ZPOS64_T ret;
int origin; ret = ftello64((FILE *)stream);
return ret;
}
static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin)
{ {
int fseek_origin=0; int fseek_origin=0;
long ret; long ret;
@@ -141,22 +164,45 @@ long ZCALLBACK fseek_file_func (opaque, stream, offset, origin)
default: return -1; default: return -1;
} }
ret = 0; ret = 0;
fseek((FILE *)stream, offset, fseek_origin); if (fseek((FILE *)stream, offset, fseek_origin) != 0)
ret = -1;
return ret; return ret;
} }
int ZCALLBACK fclose_file_func (opaque, stream) static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)
voidpf opaque; {
voidpf stream; int fseek_origin=0;
long ret;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
fseek_origin = SEEK_CUR;
break;
case ZLIB_FILEFUNC_SEEK_END :
fseek_origin = SEEK_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
fseek_origin = SEEK_SET;
break;
default: return -1;
}
ret = 0;
if(fseeko64((FILE *)stream, offset, fseek_origin) != 0)
ret = -1;
return ret;
}
static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
{ {
int ret; int ret;
ret = fclose((FILE *)stream); ret = fclose((FILE *)stream);
return ret; return ret;
} }
int ZCALLBACK ferror_file_func (opaque, stream) static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
voidpf opaque;
voidpf stream;
{ {
int ret; int ret;
ret = ferror((FILE *)stream); ret = ferror((FILE *)stream);
@@ -175,3 +221,15 @@ void fill_fopen_filefunc (pzlib_filefunc_def)
pzlib_filefunc_def->zerror_file = ferror_file_func; pzlib_filefunc_def->zerror_file = ferror_file_func;
pzlib_filefunc_def->opaque = NULL; pzlib_filefunc_def->opaque = NULL;
} }
void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = fopen64_file_func;
pzlib_filefunc_def->zread_file = fread_file_func;
pzlib_filefunc_def->zwrite_file = fwrite_file_func;
pzlib_filefunc_def->ztell64_file = ftell64_file_func;
pzlib_filefunc_def->zseek64_file = fseek64_file_func;
pzlib_filefunc_def->zclose_file = fclose_file_func;
pzlib_filefunc_def->zerror_file = ferror_file_func;
pzlib_filefunc_def->opaque = NULL;
}

View File

@@ -1,13 +1,98 @@
/* ioapi.h -- IO base function header for compress/uncompress .zip /* ioapi.h -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Version 1.01e, February 12th, 2005 Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Changes
Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
More if/def section may be needed to support other platforms
Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
(but you should use iowin32.c for windows instead)
Copyright (C) 1998-2005 Gilles Vollant
*/ */
#ifndef _ZLIBIOAPI_H #ifndef _ZLIBIOAPI64_H
#define _ZLIBIOAPI_H #define _ZLIBIOAPI64_H
#ifndef _WIN32
// Linux needs this to support file operation on files larger then 4+GB
// But might need better if/def to select just the platforms that needs them.
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include "zlib.h"
#ifdef _MSC_VER
#define fopen64 fopen
#if _MSC_VER >= 1400
#define ftello64 _ftelli64
#define fseeko64 _fseeki64
#else // old MSC
#define ftello64 ftell
#define fseeko64 fseek
#endif
#endif
/*
#ifndef ZPOS64_T
#ifdef _WIN32
#define ZPOS64_T fpos_t
#else
#include <stdint.h>
#define ZPOS64_T uint64_t
#endif
#endif
*/
#ifdef HAVE_MINIZIP64_CONF_H
#include "mz64conf.h"
#endif
/* a type choosen by DEFINE */
#ifdef HAVE_64BIT_INT_CUSTOM
typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T;
#else
#ifdef HAS_STDINT_H
#include "stdint.h"
typedef uint64_t ZPOS64_T;
#else
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 ZPOS64_T;
#else
typedef unsigned long long int ZPOS64_T;
#endif
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define ZLIB_FILEFUNC_SEEK_CUR (1) #define ZLIB_FILEFUNC_SEEK_CUR (1)
@@ -23,26 +108,27 @@
#ifndef ZCALLBACK #ifndef ZCALLBACK
#if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
#if (defined(WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) #define ZCALLBACK CALLBACK
#define ZCALLBACK CALLBACK #else
#else #define ZCALLBACK
#define ZCALLBACK #endif
#endif
#endif #endif
#ifdef __cplusplus
extern "C" {
#endif
typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
/* here is the "old" 32 bits structure structure */
typedef struct zlib_filefunc_def_s typedef struct zlib_filefunc_def_s
{ {
open_file_func zopen_file; open_file_func zopen_file;
@@ -55,21 +141,54 @@ typedef struct zlib_filefunc_def_s
voidpf opaque; voidpf opaque;
} zlib_filefunc_def; } zlib_filefunc_def;
typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode));
typedef struct zlib_filefunc64_def_s
{
open64_file_func zopen64_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell64_file_func ztell64_file;
seek64_file_func zseek64_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc64_def;
void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
#define ZREAD(filefunc,filestream,buf,size) ((*((filefunc).zread_file))((filefunc).opaque,filestream,buf,size)) /* now internal definition, only for zip.c and unzip.h */
#define ZWRITE(filefunc,filestream,buf,size) ((*((filefunc).zwrite_file))((filefunc).opaque,filestream,buf,size)) typedef struct zlib_filefunc64_32_def_s
#define ZTELL(filefunc,filestream) ((*((filefunc).ztell_file))((filefunc).opaque,filestream)) {
#define ZSEEK(filefunc,filestream,pos,mode) ((*((filefunc).zseek_file))((filefunc).opaque,filestream,pos,mode)) zlib_filefunc64_def zfile_func64;
#define ZCLOSE(filefunc,filestream) ((*((filefunc).zclose_file))((filefunc).opaque,filestream)) open_file_func zopen32_file;
#define ZERROR(filefunc,filestream) ((*((filefunc).zerror_file))((filefunc).opaque,filestream)) tell_file_func ztell32_file;
seek_file_func zseek32_file;
} zlib_filefunc64_32_def;
#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif #endif

View File

@@ -1,10 +1,14 @@
/* iowin32.c -- IO base function header for compress/uncompress .zip /* iowin32.c -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API Version 1.1, January 7th, 2010
This IO API version uses the Win32 API (for Microsoft Windows) part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Version 1.01e, February 12th, 2005 Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Copyright (C) 1998-2005 Gilles Vollant
*/ */
#include <stdlib.h> #include <stdlib.h>
@@ -21,40 +25,13 @@
#define INVALID_SET_FILE_POINTER ((DWORD)-1) #define INVALID_SET_FILE_POINTER ((DWORD)-1)
#endif #endif
voidpf ZCALLBACK win32_open_file_func OF(( voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode));
voidpf opaque, uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
const char* filename, uLong ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
int mode)); ZPOS64_T ZCALLBACK win32_tell64_file_func OF((voidpf opaque, voidpf stream));
long ZCALLBACK win32_seek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
uLong ZCALLBACK win32_read_file_func OF(( int ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream));
voidpf opaque, int ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream));
voidpf stream,
void* buf,
uLong size));
uLong ZCALLBACK win32_write_file_func OF((
voidpf opaque,
voidpf stream,
const void* buf,
uLong size));
long ZCALLBACK win32_tell_file_func OF((
voidpf opaque,
voidpf stream));
long ZCALLBACK win32_seek_file_func OF((
voidpf opaque,
voidpf stream,
uLong offset,
int origin));
int ZCALLBACK win32_close_file_func OF((
voidpf opaque,
voidpf stream));
int ZCALLBACK win32_error_file_func OF((
voidpf opaque,
voidpf stream));
typedef struct typedef struct
{ {
@@ -62,69 +39,121 @@ typedef struct
int error; int error;
} WIN32FILE_IOWIN; } WIN32FILE_IOWIN;
voidpf ZCALLBACK win32_open_file_func (opaque, filename, mode)
voidpf opaque;
const char* filename;
int mode;
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = 0;
voidpf ret=NULL;
dwDesiredAccess = dwShareMode = dwFlagsAndAttributes = 0; static void win32_translate_open_mode(int mode,
DWORD* lpdwDesiredAccess,
DWORD* lpdwCreationDisposition,
DWORD* lpdwShareMode,
DWORD* lpdwFlagsAndAttributes)
{
*lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
{ {
dwDesiredAccess = GENERIC_READ; *lpdwDesiredAccess = GENERIC_READ;
dwCreationDisposition = OPEN_EXISTING; *lpdwCreationDisposition = OPEN_EXISTING;
dwShareMode = FILE_SHARE_READ; *lpdwShareMode = FILE_SHARE_READ;
} }
else else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
{ {
dwDesiredAccess = GENERIC_WRITE | GENERIC_READ; *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
dwCreationDisposition = OPEN_EXISTING; *lpdwCreationDisposition = OPEN_EXISTING;
} }
else else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
if (mode & ZLIB_FILEFUNC_MODE_CREATE)
{ {
dwDesiredAccess = GENERIC_WRITE | GENERIC_READ; *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
dwCreationDisposition = CREATE_ALWAYS; *lpdwCreationDisposition = CREATE_ALWAYS;
} }
}
if ((filename!=NULL) && (dwDesiredAccess != 0)) static voidpf win32_build_iowin(HANDLE hFile)
hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, {
dwCreationDisposition, dwFlagsAndAttributes, NULL); voidpf ret=NULL;
if (hFile == INVALID_HANDLE_VALUE) if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
hFile = NULL;
if (hFile != NULL)
{ {
WIN32FILE_IOWIN w32fiow; WIN32FILE_IOWIN w32fiow;
w32fiow.hf = hFile; w32fiow.hf = hFile;
w32fiow.error = 0; w32fiow.error = 0;
ret = malloc(sizeof(WIN32FILE_IOWIN)); ret = malloc(sizeof(WIN32FILE_IOWIN));
if (ret==NULL) if (ret==NULL)
CloseHandle(hFile); CloseHandle(hFile);
else *((WIN32FILE_IOWIN*)ret) = w32fiow; else
*((WIN32FILE_IOWIN*)ret) = w32fiow;
} }
return ret; return ret;
} }
voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
uLong ZCALLBACK win32_read_file_func (opaque, stream, buf, size) win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
voidpf opaque;
voidpf stream; if ((filename!=NULL) && (dwDesiredAccess != 0))
void* buf; hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
uLong size;
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode)
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = NULL;
win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes);
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL);
return win32_build_iowin(hFile);
}
uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size)
{ {
uLong ret=0; uLong ret=0;
HANDLE hFile = NULL; HANDLE hFile = NULL;
if (stream!=NULL) if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf; hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL) if (hFile != NULL)
{
if (!ReadFile(hFile, buf, size, &ret, NULL)) if (!ReadFile(hFile, buf, size, &ret, NULL))
{ {
DWORD dwErr = GetLastError(); DWORD dwErr = GetLastError();
@@ -132,23 +161,21 @@ uLong ZCALLBACK win32_read_file_func (opaque, stream, buf, size)
dwErr = 0; dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
} }
}
return ret; return ret;
} }
uLong ZCALLBACK win32_write_file_func (opaque, stream, buf, size) uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size)
voidpf opaque;
voidpf stream;
const void* buf;
uLong size;
{ {
uLong ret=0; uLong ret=0;
HANDLE hFile = NULL; HANDLE hFile = NULL;
if (stream!=NULL) if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf; hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile !=NULL) if (hFile != NULL)
{
if (!WriteFile(hFile, buf, size, &ret, NULL)) if (!WriteFile(hFile, buf, size, &ret, NULL))
{ {
DWORD dwErr = GetLastError(); DWORD dwErr = GetLastError();
@@ -156,13 +183,12 @@ uLong ZCALLBACK win32_write_file_func (opaque, stream, buf, size)
dwErr = 0; dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
} }
}
return ret; return ret;
} }
long ZCALLBACK win32_tell_file_func (opaque, stream) long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream)
voidpf opaque;
voidpf stream;
{ {
long ret=-1; long ret=-1;
HANDLE hFile = NULL; HANDLE hFile = NULL;
@@ -183,11 +209,32 @@ long ZCALLBACK win32_tell_file_func (opaque, stream)
return ret; return ret;
} }
long ZCALLBACK win32_seek_file_func (opaque, stream, offset, origin) ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream)
voidpf opaque; {
voidpf stream; ZPOS64_T ret= (ZPOS64_T)-1;
uLong offset; HANDLE hFile = NULL;
int origin; if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream)->hf;
if (hFile)
{
LARGE_INTEGER li;
li.QuadPart = 0;
li.u.LowPart = SetFilePointer(hFile, li.u.LowPart, &li.u.HighPart, FILE_CURRENT);
if ( (li.LowPart == 0xFFFFFFFF) && (GetLastError() != NO_ERROR))
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = (ZPOS64_T)-1;
}
else
ret=li.QuadPart;
}
return ret;
}
long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin)
{ {
DWORD dwMoveMethod=0xFFFFFFFF; DWORD dwMoveMethod=0xFFFFFFFF;
HANDLE hFile = NULL; HANDLE hFile = NULL;
@@ -224,9 +271,46 @@ long ZCALLBACK win32_seek_file_func (opaque, stream, offset, origin)
return ret; return ret;
} }
int ZCALLBACK win32_close_file_func (opaque, stream) long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin)
voidpf opaque; {
voidpf stream; DWORD dwMoveMethod=0xFFFFFFFF;
HANDLE hFile = NULL;
long ret=-1;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream)->hf;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
dwMoveMethod = FILE_CURRENT;
break;
case ZLIB_FILEFUNC_SEEK_END :
dwMoveMethod = FILE_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
dwMoveMethod = FILE_BEGIN;
break;
default: return -1;
}
if (hFile)
{
LARGE_INTEGER* li = (LARGE_INTEGER*)&offset;
DWORD dwSet = SetFilePointer(hFile, li->u.LowPart, &li->u.HighPart, dwMoveMethod);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=0;
}
return ret;
}
int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream)
{ {
int ret=-1; int ret=-1;
@@ -244,9 +328,7 @@ int ZCALLBACK win32_close_file_func (opaque, stream)
return ret; return ret;
} }
int ZCALLBACK win32_error_file_func (opaque, stream) int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream)
voidpf opaque;
voidpf stream;
{ {
int ret=-1; int ret=-1;
if (stream!=NULL) if (stream!=NULL)
@@ -256,8 +338,7 @@ int ZCALLBACK win32_error_file_func (opaque, stream)
return ret; return ret;
} }
void fill_win32_filefunc (pzlib_filefunc_def) void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def)
zlib_filefunc_def* pzlib_filefunc_def;
{ {
pzlib_filefunc_def->zopen_file = win32_open_file_func; pzlib_filefunc_def->zopen_file = win32_open_file_func;
pzlib_filefunc_def->zread_file = win32_read_file_func; pzlib_filefunc_def->zread_file = win32_read_file_func;
@@ -266,5 +347,43 @@ void fill_win32_filefunc (pzlib_filefunc_def)
pzlib_filefunc_def->zseek_file = win32_seek_file_func; pzlib_filefunc_def->zseek_file = win32_seek_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func; pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func; pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque=NULL; pzlib_filefunc_def->opaque = NULL;
}
void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_func;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
}
void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell64_file = win32_tell64_file_func;
pzlib_filefunc_def->zseek64_file = win32_seek64_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque = NULL;
} }

View File

@@ -1,10 +1,14 @@
/* iowin32.h -- IO base function header for compress/uncompress .zip /* iowin32.h -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API Version 1.1, January 7th, 2010
This IO API version uses the Win32 API (for Microsoft Windows) part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Version 1.01e, February 12th, 2005 Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications for Zip64 support
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
For more info read MiniZip_info.txt
Copyright (C) 1998-2005 Gilles Vollant
*/ */
#include <windows.h> #include <windows.h>
@@ -15,6 +19,9 @@ extern "C" {
#endif #endif
void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def));
void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def));
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@@ -0,0 +1,25 @@
$ if f$search("ioapi.h_orig") .eqs. "" then copy ioapi.h ioapi.h_orig
$ open/write zdef vmsdefs.h
$ copy sys$input: zdef
$ deck
#define unix
#define fill_zlib_filefunc64_32_def_from_filefunc32 fillzffunc64from
#define Write_Zip64EndOfCentralDirectoryLocator Write_Zip64EoDLocator
#define Write_Zip64EndOfCentralDirectoryRecord Write_Zip64EoDRecord
#define Write_EndOfCentralDirectoryRecord Write_EoDRecord
$ eod
$ close zdef
$ copy vmsdefs.h,ioapi.h_orig ioapi.h
$ cc/include=[--]/prefix=all ioapi.c
$ cc/include=[--]/prefix=all miniunz.c
$ cc/include=[--]/prefix=all unzip.c
$ cc/include=[--]/prefix=all minizip.c
$ cc/include=[--]/prefix=all zip.c
$ link miniunz,unzip,ioapi,[--]libz.olb/lib
$ link minizip,zip,ioapi,[--]libz.olb/lib
$ mcr []minizip test minizip64_info.txt
$ mcr []miniunz -l test.zip
$ rename minizip64_info.txt; minizip64_info.txt_old
$ mcr []miniunz test.zip
$ delete test.zip;*
$exit

View File

@@ -1,10 +1,31 @@
/* /*
miniunz.c miniunz.c
Version 1.01e, February 12th, 2005 Version 1.1, January 7th, 2010
sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2005 Gilles Vollant Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
*/ */
#ifndef _WIN32
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@@ -27,7 +48,7 @@
#define WRITEBUFFERSIZE (8192) #define WRITEBUFFERSIZE (8192)
#define MAXFILENAME (256) #define MAXFILENAME (256)
#ifdef WIN32 #ifdef _WIN32
#define USEWIN32IOAPI #define USEWIN32IOAPI
#include "iowin32.h" #include "iowin32.h"
#endif #endif
@@ -51,11 +72,11 @@ void change_file_date(filename,dosdate,tmu_date)
uLong dosdate; uLong dosdate;
tm_unz tmu_date; tm_unz tmu_date;
{ {
#ifdef WIN32 #ifdef _WIN32
HANDLE hFile; HANDLE hFile;
FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite;
hFile = CreateFile(filename,GENERIC_READ | GENERIC_WRITE, hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE,
0,NULL,OPEN_EXISTING,0,NULL); 0,NULL,OPEN_EXISTING,0,NULL);
GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite);
DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal);
@@ -91,8 +112,8 @@ int mymkdir(dirname)
const char* dirname; const char* dirname;
{ {
int ret=0; int ret=0;
#ifdef WIN32 #ifdef _WIN32
ret = mkdir(dirname); ret = _mkdir(dirname);
#else #else
#ifdef unix #ifdef unix
ret = mkdir (dirname,0775); ret = mkdir (dirname,0775);
@@ -112,6 +133,11 @@ int makedir (newdir)
return 0; return 0;
buffer = (char*)malloc(len+1); buffer = (char*)malloc(len+1);
if (buffer==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
strcpy(buffer,newdir); strcpy(buffer,newdir);
if (buffer[len-1] == '/') { if (buffer[len-1] == '/') {
@@ -164,34 +190,61 @@ void do_help()
" -p extract crypted file using password\n\n"); " -p extract crypted file using password\n\n");
} }
void Display64BitsSize(ZPOS64_T n, int size_char)
{
/* to avoid compatibility problem , we do here the conversion */
char number[21];
int offset=19;
int pos_string = 19;
number[20]=0;
for (;;) {
number[offset]=(char)((n%10)+'0');
if (number[offset] != '0')
pos_string=offset;
n/=10;
if (offset==0)
break;
offset--;
}
{
int size_display_string = 19-pos_string;
while (size_char > size_display_string)
{
size_char--;
printf(" ");
}
}
printf("%s",&number[pos_string]);
}
int do_list(uf) int do_list(uf)
unzFile uf; unzFile uf;
{ {
uLong i; uLong i;
unz_global_info gi; unz_global_info64 gi;
int err; int err;
err = unzGetGlobalInfo (uf,&gi); err = unzGetGlobalInfo64(uf,&gi);
if (err!=UNZ_OK) if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err); printf("error %d with zipfile in unzGetGlobalInfo \n",err);
printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); printf(" Length Method Size Ratio Date Time CRC-32 Name\n");
printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); printf(" ------ ------ ---- ----- ---- ---- ------ ----\n");
for (i=0;i<gi.number_entry;i++) for (i=0;i<gi.number_entry;i++)
{ {
char filename_inzip[256]; char filename_inzip[256];
unz_file_info file_info; unz_file_info64 file_info;
uLong ratio=0; uLong ratio=0;
const char *string_method; const char *string_method;
char charCrypt=' '; char charCrypt=' ';
err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK) if (err!=UNZ_OK)
{ {
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
break; break;
} }
if (file_info.uncompressed_size>0) if (file_info.uncompressed_size>0)
ratio = (file_info.compressed_size*100)/file_info.uncompressed_size; ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size);
/* display a '*' if the file is crypted */ /* display a '*' if the file is crypted */
if ((file_info.flag & 1) != 0) if ((file_info.flag & 1) != 0)
@@ -210,13 +263,18 @@ int do_list(uf)
else if ((iLevel==2) || (iLevel==3)) else if ((iLevel==2) || (iLevel==3))
string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ string_method="Defl:F"; /* 2:fast , 3 : extra fast*/
} }
else
if (file_info.compression_method==Z_BZIP2ED)
{
string_method="BZip2 ";
}
else else
string_method="Unkn. "; string_method="Unkn. ";
printf("%7lu %6s%c%7lu %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", Display64BitsSize(file_info.uncompressed_size,7);
file_info.uncompressed_size,string_method, printf(" %6s%c",string_method,charCrypt);
charCrypt, Display64BitsSize(file_info.compressed_size,7);
file_info.compressed_size, printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n",
ratio, ratio,
(uLong)file_info.tmu_date.tm_mon + 1, (uLong)file_info.tmu_date.tm_mon + 1,
(uLong)file_info.tmu_date.tm_mday, (uLong)file_info.tmu_date.tm_mday,
@@ -252,9 +310,9 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
void* buf; void* buf;
uInt size_buf; uInt size_buf;
unz_file_info file_info; unz_file_info64 file_info;
uLong ratio=0; uLong ratio=0;
err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); err = unzGetCurrentFileInfo64(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK) if (err!=UNZ_OK)
{ {
@@ -306,7 +364,7 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
{ {
char rep=0; char rep=0;
FILE* ftestexist; FILE* ftestexist;
ftestexist = fopen(write_filename,"rb"); ftestexist = fopen64(write_filename,"rb");
if (ftestexist!=NULL) if (ftestexist!=NULL)
{ {
fclose(ftestexist); fclose(ftestexist);
@@ -317,7 +375,7 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
ret = scanf("%1s",answer); ret = scanf("%1s",answer);
if (ret != 1) if (ret != 1)
{ {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -337,7 +395,7 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
if ((skip==0) && (err==UNZ_OK)) if ((skip==0) && (err==UNZ_OK))
{ {
fout=fopen(write_filename,"wb"); fout=fopen64(write_filename,"wb");
/* some zipfile don't contain directory alone before file */ /* some zipfile don't contain directory alone before file */
if ((fout==NULL) && ((*popt_extract_without_path)==0) && if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
@@ -347,7 +405,7 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
*(filename_withoutpath-1)='\0'; *(filename_withoutpath-1)='\0';
makedir(write_filename); makedir(write_filename);
*(filename_withoutpath-1)=c; *(filename_withoutpath-1)=c;
fout=fopen(write_filename,"wb"); fout=fopen64(write_filename,"wb");
} }
if (fout==NULL) if (fout==NULL)
@@ -409,11 +467,11 @@ int do_extract(uf,opt_extract_without_path,opt_overwrite,password)
const char* password; const char* password;
{ {
uLong i; uLong i;
unz_global_info gi; unz_global_info64 gi;
int err; int err;
FILE* fout=NULL; FILE* fout=NULL;
err = unzGetGlobalInfo (uf,&gi); err = unzGetGlobalInfo64(uf,&gi);
if (err!=UNZ_OK) if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err); printf("error %d with zipfile in unzGetGlobalInfo \n",err);
@@ -470,6 +528,7 @@ int main(argc,argv)
const char *password=NULL; const char *password=NULL;
char filename_try[MAXFILENAME+16] = ""; char filename_try[MAXFILENAME+16] = "";
int i; int i;
int ret_value=0;
int opt_do_list=0; int opt_do_list=0;
int opt_do_extract=1; int opt_do_extract=1;
int opt_do_extract_withoutpath=0; int opt_do_extract_withoutpath=0;
@@ -532,7 +591,7 @@ int main(argc,argv)
{ {
# ifdef USEWIN32IOAPI # ifdef USEWIN32IOAPI
zlib_filefunc_def ffunc; zlib_filefunc64_def ffunc;
# endif # endif
strncpy(filename_try, zipfilename,MAXFILENAME-1); strncpy(filename_try, zipfilename,MAXFILENAME-1);
@@ -540,18 +599,18 @@ int main(argc,argv)
filename_try[ MAXFILENAME ] = '\0'; filename_try[ MAXFILENAME ] = '\0';
# ifdef USEWIN32IOAPI # ifdef USEWIN32IOAPI
fill_win32_filefunc(&ffunc); fill_win32_filefunc64A(&ffunc);
uf = unzOpen2(zipfilename,&ffunc); uf = unzOpen2_64(zipfilename,&ffunc);
# else # else
uf = unzOpen(zipfilename); uf = unzOpen64(zipfilename);
# endif # endif
if (uf==NULL) if (uf==NULL)
{ {
strcat(filename_try,".zip"); strcat(filename_try,".zip");
# ifdef USEWIN32IOAPI # ifdef USEWIN32IOAPI
uf = unzOpen2(filename_try,&ffunc); uf = unzOpen2_64(filename_try,&ffunc);
# else # else
uf = unzOpen(filename_try); uf = unzOpen64(filename_try);
# endif # endif
} }
} }
@@ -564,22 +623,26 @@ int main(argc,argv)
printf("%s opened\n",filename_try); printf("%s opened\n",filename_try);
if (opt_do_list==1) if (opt_do_list==1)
return do_list(uf); ret_value = do_list(uf);
else if (opt_do_extract==1) else if (opt_do_extract==1)
{ {
if (opt_extractdir && chdir(dirname)) #ifdef _WIN32
if (opt_extractdir && _chdir(dirname))
#else
if (opt_extractdir && chdir(dirname))
#endif
{ {
printf("Error changing into %s, aborting\n", dirname); printf("Error changing into %s, aborting\n", dirname);
exit(-1); exit(-1);
} }
if (filename_to_extract == NULL) if (filename_to_extract == NULL)
return do_extract(uf,opt_do_extract_withoutpath,opt_overwrite,password); ret_value = do_extract(uf, opt_do_extract_withoutpath, opt_overwrite, password);
else else
return do_extract_onefile(uf,filename_to_extract, ret_value = do_extract_onefile(uf, filename_to_extract, opt_do_extract_withoutpath, opt_overwrite, password);
opt_do_extract_withoutpath,opt_overwrite,password);
} }
unzCloseCurrentFile(uf);
return 0; unzClose(uf);
return ret_value;
} }

View File

@@ -1,10 +1,33 @@
/* /*
minizip.c minizip.c
Version 1.01e, February 12th, 2005 Version 1.1, January 7th, 2010
sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2005 Gilles Vollant Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
Modifications of Unzip for Zip64
Copyright (C) 2007-2008 Even Rouault
Modifications for Zip64 support on both zip and unzip
Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
*/ */
#ifndef _WIN32
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BIT
#define _FILE_OFFSET_BIT 64
#endif
#endif
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@@ -24,9 +47,9 @@
#include "zip.h" #include "zip.h"
#ifdef WIN32 #ifdef _WIN32
#define USEWIN32IOAPI #define USEWIN32IOAPI
#include "iowin32.h" #include "iowin32.h"
#endif #endif
@@ -34,7 +57,7 @@
#define WRITEBUFFERSIZE (16384) #define WRITEBUFFERSIZE (16384)
#define MAXFILENAME (256) #define MAXFILENAME (256)
#ifdef WIN32 #ifdef _WIN32
uLong filetime(f, tmzip, dt) uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */ char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */ tm_zip *tmzip; /* return value: access, modific. and creation times */
@@ -44,9 +67,9 @@ uLong filetime(f, tmzip, dt)
{ {
FILETIME ftLocal; FILETIME ftLocal;
HANDLE hFind; HANDLE hFind;
WIN32_FIND_DATA ff32; WIN32_FIND_DATAA ff32;
hFind = FindFirstFile(f,&ff32); hFind = FindFirstFileA(f,&ff32);
if (hFind != INVALID_HANDLE_VALUE) if (hFind != INVALID_HANDLE_VALUE)
{ {
FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal); FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
@@ -119,7 +142,7 @@ int check_exist_file(filename)
{ {
FILE* ftestexist; FILE* ftestexist;
int ret = 1; int ret = 1;
ftestexist = fopen(filename,"rb"); ftestexist = fopen64(filename,"rb");
if (ftestexist==NULL) if (ftestexist==NULL)
ret = 0; ret = 0;
else else
@@ -129,18 +152,20 @@ int check_exist_file(filename)
void do_banner() void do_banner()
{ {
printf("MiniZip 1.01b, demo of zLib + Zip package written by Gilles Vollant\n"); printf("MiniZip64 1.0, demo of zLib + MiniZip64 package, written by Gilles Vollant\n");
printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n");
printf("more info on MiniZip64 at http://result42.com/projects/MiniZip64\n\n");
} }
void do_help() void do_help()
{ {
printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] file.zip [files_to_add]\n\n" \ printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \
" -o Overwrite existing file.zip\n" \ " -o Overwrite existing file.zip\n" \
" -a Append to existing file.zip\n" \ " -a Append to existing file.zip\n" \
" -0 Store only\n" \ " -0 Store only\n" \
" -1 Compress faster\n" \ " -1 Compress faster\n" \
" -9 Compress better\n\n"); " -9 Compress better\n\n" \
" -j exclude path. store only the file name.\n\n");
} }
/* calculate the CRC32 of a file, /* calculate the CRC32 of a file,
@@ -149,7 +174,7 @@ int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigne
{ {
unsigned long calculate_crc=0; unsigned long calculate_crc=0;
int err=ZIP_OK; int err=ZIP_OK;
FILE * fin = fopen(filenameinzip,"rb"); FILE * fin = fopen64(filenameinzip,"rb");
unsigned long size_read = 0; unsigned long size_read = 0;
unsigned long total_read = 0; unsigned long total_read = 0;
if (fin==NULL) if (fin==NULL)
@@ -179,10 +204,33 @@ int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigne
fclose(fin); fclose(fin);
*result_crc=calculate_crc; *result_crc=calculate_crc;
printf("file %s crc %x\n",filenameinzip,calculate_crc); printf("file %s crc %lx\n", filenameinzip, calculate_crc);
return err; return err;
} }
int isLargeFile(const char* filename)
{
int largeFile = 0;
ZPOS64_T pos = 0;
FILE* pFile = fopen64(filename, "rb");
if(pFile != NULL)
{
int n = fseeko64(pFile, 0, SEEK_END);
pos = ftello64(pFile);
printf("File : %s is %lld bytes\n", filename, pos);
if(pos >= 0xffffffff)
largeFile = 1;
fclose(pFile);
}
return largeFile;
}
int main(argc,argv) int main(argc,argv)
int argc; int argc;
char *argv[]; char *argv[];
@@ -190,6 +238,7 @@ int main(argc,argv)
int i; int i;
int opt_overwrite=0; int opt_overwrite=0;
int opt_compress_level=Z_DEFAULT_COMPRESSION; int opt_compress_level=Z_DEFAULT_COMPRESSION;
int opt_exclude_path=0;
int zipfilenamearg = 0; int zipfilenamearg = 0;
char filename_try[MAXFILENAME+16]; char filename_try[MAXFILENAME+16];
int zipok; int zipok;
@@ -222,6 +271,8 @@ int main(argc,argv)
opt_overwrite = 2; opt_overwrite = 2;
if ((c>='0') && (c<='9')) if ((c>='0') && (c<='9'))
opt_compress_level = c-'0'; opt_compress_level = c-'0';
if ((c=='j') || (c=='J'))
opt_exclude_path = 1;
if (((c=='p') || (c=='P')) && (i+1<argc)) if (((c=='p') || (c=='P')) && (i+1<argc))
{ {
@@ -231,8 +282,12 @@ int main(argc,argv)
} }
} }
else else
{
if (zipfilenamearg == 0) if (zipfilenamearg == 0)
{
zipfilenamearg = i ; zipfilenamearg = i ;
}
}
} }
} }
@@ -245,7 +300,9 @@ int main(argc,argv)
} }
if (zipfilenamearg==0) if (zipfilenamearg==0)
{
zipok=0; zipok=0;
}
else else
{ {
int i,len; int i,len;
@@ -302,11 +359,11 @@ int main(argc,argv)
zipFile zf; zipFile zf;
int errclose; int errclose;
# ifdef USEWIN32IOAPI # ifdef USEWIN32IOAPI
zlib_filefunc_def ffunc; zlib_filefunc64_def ffunc;
fill_win32_filefunc(&ffunc); fill_win32_filefunc64A(&ffunc);
zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc); zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
# else # else
zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0); zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0);
# endif # endif
if (zf == NULL) if (zf == NULL)
@@ -329,8 +386,10 @@ int main(argc,argv)
FILE * fin; FILE * fin;
int size_read; int size_read;
const char* filenameinzip = argv[i]; const char* filenameinzip = argv[i];
const char *savefilenameinzip;
zip_fileinfo zi; zip_fileinfo zi;
unsigned long crcFile=0; unsigned long crcFile=0;
int zip64 = 0;
zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
@@ -348,19 +407,48 @@ int main(argc,argv)
if ((password != NULL) && (err==ZIP_OK)) if ((password != NULL) && (err==ZIP_OK))
err = getFileCrc(filenameinzip,buf,size_buf,&crcFile); err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
err = zipOpenNewFileInZip3(zf,filenameinzip,&zi, zip64 = isLargeFile(filenameinzip);
/* The path name saved, should not include a leading slash. */
/*if it did, windows/xp and dynazip couldn't read the zip file. */
savefilenameinzip = filenameinzip;
while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' )
{
savefilenameinzip++;
}
/*should the zip file contain any path at all?*/
if( opt_exclude_path )
{
const char *tmpptr;
const char *lastslash = 0;
for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++)
{
if( *tmpptr == '\\' || *tmpptr == '/')
{
lastslash = tmpptr;
}
}
if( lastslash != NULL )
{
savefilenameinzip = lastslash+1; // base filename follows last slash.
}
}
/**/
err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi,
NULL,0,NULL,0,NULL /* comment*/, NULL,0,NULL,0,NULL /* comment*/,
(opt_compress_level != 0) ? Z_DEFLATED : 0, (opt_compress_level != 0) ? Z_DEFLATED : 0,
opt_compress_level,0, opt_compress_level,0,
/* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */ /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
password,crcFile); password,crcFile, zip64);
if (err != ZIP_OK) if (err != ZIP_OK)
printf("error in opening %s in zipfile\n",filenameinzip); printf("error in opening %s in zipfile\n",filenameinzip);
else else
{ {
fin = fopen(filenameinzip,"rb"); fin = fopen64(filenameinzip,"rb");
if (fin==NULL) if (fin==NULL)
{ {
err=ZIP_ERRNO; err=ZIP_ERRNO;

View File

@@ -62,7 +62,7 @@ uLong* bytesRecovered;
unsigned int fnsize = READ_16(header + 26); /* file name length */ unsigned int fnsize = READ_16(header + 26); /* file name length */
unsigned int extsize = READ_16(header + 28); /* extra field length */ unsigned int extsize = READ_16(header + 28); /* extra field length */
filename[0] = extra[0] = '\0'; filename[0] = extra[0] = '\0';
/* Header */ /* Header */
if (fwrite(header, 1, 30, fpOut) == 30) { if (fwrite(header, 1, 30, fpOut) == 30) {
offset += 30; offset += 30;
@@ -70,7 +70,7 @@ uLong* bytesRecovered;
err = Z_ERRNO; err = Z_ERRNO;
break; break;
} }
/* Filename */ /* Filename */
if (fnsize > 0) { if (fnsize > 0) {
if (fread(filename, 1, fnsize, fpZip) == fnsize) { if (fread(filename, 1, fnsize, fpZip) == fnsize) {
@@ -103,7 +103,7 @@ uLong* bytesRecovered;
break; break;
} }
} }
/* Data */ /* Data */
{ {
int dataSize = cpsize; int dataSize = cpsize;
@@ -133,7 +133,7 @@ uLong* bytesRecovered;
} }
} }
} }
/* Central directory entry */ /* Central directory entry */
{ {
char header[46]; char header[46];
@@ -159,7 +159,7 @@ uLong* bytesRecovered;
/* Header */ /* Header */
if (fwrite(header, 1, 46, fpOutCD) == 46) { if (fwrite(header, 1, 46, fpOutCD) == 46) {
offsetCD += 46; offsetCD += 46;
/* Filename */ /* Filename */
if (fnsize > 0) { if (fnsize > 0) {
if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) {
@@ -172,7 +172,7 @@ uLong* bytesRecovered;
err = Z_STREAM_ERROR; err = Z_STREAM_ERROR;
break; break;
} }
/* Extra field */ /* Extra field */
if (extsize > 0) { if (extsize > 0) {
if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { if (fwrite(extra, 1, extsize, fpOutCD) == extsize) {
@@ -182,7 +182,7 @@ uLong* bytesRecovered;
break; break;
} }
} }
/* Comment field */ /* Comment field */
if (comsize > 0) { if (comsize > 0) {
if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) { if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) {
@@ -192,8 +192,8 @@ uLong* bytesRecovered;
break; break;
} }
} }
} else { } else {
err = Z_ERRNO; err = Z_ERRNO;
break; break;
@@ -225,17 +225,17 @@ uLong* bytesRecovered;
WRITE_32(header + 12, offsetCD); /* size of CD */ WRITE_32(header + 12, offsetCD); /* size of CD */
WRITE_32(header + 16, offset); /* offset to CD */ WRITE_32(header + 16, offset); /* offset to CD */
WRITE_16(header + 20, comsize); /* comment */ WRITE_16(header + 20, comsize); /* comment */
/* Header */ /* Header */
if (fwrite(header, 1, 22, fpOutCD) == 22) { if (fwrite(header, 1, 22, fpOutCD) == 22) {
/* Comment field */ /* Comment field */
if (comsize > 0) { if (comsize > 0) {
if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) { if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) {
err = Z_ERRNO; err = Z_ERRNO;
} }
} }
} else { } else {
err = Z_ERRNO; err = Z_ERRNO;
} }
@@ -257,14 +257,14 @@ uLong* bytesRecovered;
fclose(fpOutCD); fclose(fpOutCD);
} }
} }
/* Close */ /* Close */
fclose(fpZip); fclose(fpZip);
fclose(fpOut); fclose(fpOut);
/* Wipe temporary file */ /* Wipe temporary file */
(void)remove(fileOutTmp); (void)remove(fileOutTmp);
/* Number of recovered entries */ /* Number of recovered entries */
if (err == Z_OK) { if (err == Z_OK) {
if (nRecovered != NULL) { if (nRecovered != NULL) {

View File

@@ -17,14 +17,14 @@ extern "C" {
#include "unzip.h" #include "unzip.h"
/* Repair a ZIP file (missing central directory) /* Repair a ZIP file (missing central directory)
file: file to recover file: file to recover
fileOut: output file after recovery fileOut: output file after recovery
fileOutTmp: temporary file name used for recovery fileOutTmp: temporary file name used for recovery
*/ */
extern int ZEXPORT unzRepair(const char* file, extern int ZEXPORT unzRepair(const char* file,
const char* fileOut, const char* fileOut,
const char* fileOutTmp, const char* fileOutTmp,
uLong* nRecovered, uLong* nRecovered,
uLong* bytesRecovered); uLong* bytesRecovered);

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,20 @@
/* unzip.h -- IO for uncompress .zip files using zlib /* unzip.h -- IO for uncompress .zip files using zlib
Version 1.01e, February 12th, 2005 Version 1.1, January 7th, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2005 Gilles Vollant Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g Modifications of Unzip for Zip64
WinZip, InfoZip tools and compatible. Copyright (C) 2007-2008 Even Rouault
Multi volume ZipFile (span) are not supported. Modifications for Zip64 support on both zip and unzip
Encryption compatible with pkzip 2.04g only supported Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
Old compressions used by old PKZip 1.x are not supported
For more info read MiniZip_info.txt
I WAIT FEEDBACK at mail info@winimage.com ---------------------------------------------------------------------------------
Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
Condition of use and distribution are the same than zlib : Condition of use and distribution are the same than zlib :
This software is provided 'as-is', without any express or implied This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages warranty. In no event will the authors be held liable for any damages
@@ -32,18 +32,16 @@
misrepresented as being the original software. misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution. 3. This notice may not be removed or altered from any source distribution.
---------------------------------------------------------------------------------
Changes
See header of unzip64.c
*/ */
/* for more info about .ZIP format, see #ifndef _unz64_H
http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip #define _unz64_H
http://www.info-zip.org/pub/infozip/doc/
PkWare has also a specification at :
ftp://ftp.pkware.com/probdesc.zip
*/
#ifndef _unz_H
#define _unz_H
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
@@ -53,10 +51,16 @@ extern "C" {
#include "zlib.h" #include "zlib.h"
#endif #endif
#ifndef _ZLIBIOAPI_H #ifndef _ZLIBIOAPI_H
#include "ioapi.h" #include "ioapi.h"
#endif #endif
#ifdef HAVE_BZIP2
#include "bzlib.h"
#endif
#define Z_BZIP2ED 12
#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) #if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted /* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */ from (void*) without cast */
@@ -89,15 +93,42 @@ typedef struct tm_unz_s
/* unz_global_info structure contain global data about the ZIPfile /* unz_global_info structure contain global data about the ZIPfile
These data comes from the end of central dir */ These data comes from the end of central dir */
typedef struct unz_global_info64_s
{
ZPOS64_T number_entry; /* total number of entries in
the central dir on this disk */
uLong size_comment; /* size of the global comment of the zipfile */
} unz_global_info64;
typedef struct unz_global_info_s typedef struct unz_global_info_s
{ {
uLong number_entry; /* total number of entries in uLong number_entry; /* total number of entries in
the central dir on this disk */ the central dir on this disk */
uLong size_comment; /* size of the global comment of the zipfile */ uLong size_comment; /* size of the global comment of the zipfile */
} unz_global_info; } unz_global_info;
/* unz_file_info contain information about a file in the zipfile */ /* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_info64_s
{
uLong version; /* version made by 2 bytes */
uLong version_needed; /* version needed to extract 2 bytes */
uLong flag; /* general purpose bit flag 2 bytes */
uLong compression_method; /* compression method 2 bytes */
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
uLong crc; /* crc-32 4 bytes */
ZPOS64_T compressed_size; /* compressed size 8 bytes */
ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */
uLong size_filename; /* filename length 2 bytes */
uLong size_file_extra; /* extra field length 2 bytes */
uLong size_file_comment; /* file comment length 2 bytes */
uLong disk_num_start; /* disk number start 2 bytes */
uLong internal_fa; /* internal file attributes 2 bytes */
uLong external_fa; /* external file attributes 4 bytes */
tm_unz tmu_date;
} unz_file_info64;
typedef struct unz_file_info_s typedef struct unz_file_info_s
{ {
uLong version; /* version made by 2 bytes */ uLong version; /* version made by 2 bytes */
@@ -133,6 +164,7 @@ extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1,
extern unzFile ZEXPORT unzOpen OF((const char *path)); extern unzFile ZEXPORT unzOpen OF((const char *path));
extern unzFile ZEXPORT unzOpen64 OF((const void *path));
/* /*
Open a Zip file. path contain the full pathname (by example, Open a Zip file. path contain the full pathname (by example,
on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer
@@ -141,8 +173,14 @@ extern unzFile ZEXPORT unzOpen OF((const char *path));
return value is NULL. return value is NULL.
Else, the return value is a unzFile Handle, usable with other function Else, the return value is a unzFile Handle, usable with other function
of this unzip package. of this unzip package.
the "64" function take a const void* pointer, because the path is just the
value passed to the open64_file_func callback.
Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path
is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char*
does not describe the reality
*/ */
extern unzFile ZEXPORT unzOpen2 OF((const char *path, extern unzFile ZEXPORT unzOpen2 OF((const char *path,
zlib_filefunc_def* pzlib_filefunc_def)); zlib_filefunc_def* pzlib_filefunc_def));
/* /*
@@ -150,6 +188,13 @@ extern unzFile ZEXPORT unzOpen2 OF((const char *path,
for read/write the zip file (see ioapi.h) for read/write the zip file (see ioapi.h)
*/ */
extern unzFile ZEXPORT unzOpen2_64 OF((const void *path,
zlib_filefunc64_def* pzlib_filefunc_def));
/*
Open a Zip file, like unz64Open, but provide a set of file low level API
for read/write the zip file (see ioapi.h)
*/
extern int ZEXPORT unzClose OF((unzFile file)); extern int ZEXPORT unzClose OF((unzFile file));
/* /*
Close a ZipFile opened with unzipOpen. Close a ZipFile opened with unzipOpen.
@@ -159,6 +204,9 @@ extern int ZEXPORT unzClose OF((unzFile file));
extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
unz_global_info *pglobal_info)); unz_global_info *pglobal_info));
extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file,
unz_global_info64 *pglobal_info));
/* /*
Write info about the ZipFile in the *pglobal_info structure. Write info about the ZipFile in the *pglobal_info structure.
No preparation of the structure is needed No preparation of the structure is needed
@@ -221,8 +269,31 @@ extern int ZEXPORT unzGoToFilePos(
unzFile file, unzFile file,
unz_file_pos* file_pos); unz_file_pos* file_pos);
typedef struct unz64_file_pos_s
{
ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */
ZPOS64_T num_of_file; /* # of file */
} unz64_file_pos;
extern int ZEXPORT unzGetFilePos64(
unzFile file,
unz64_file_pos* file_pos);
extern int ZEXPORT unzGoToFilePos64(
unzFile file,
const unz64_file_pos* file_pos);
/* ****************************************** */ /* ****************************************** */
extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file,
unz_file_info64 *pfile_info,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize));
extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
unz_file_info *pfile_info, unz_file_info *pfile_info,
char *szFileName, char *szFileName,
@@ -244,6 +315,14 @@ extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
(commentBufferSize is the size of the buffer) (commentBufferSize is the size of the buffer)
*/ */
/** Addition for GDAL : START */
extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file));
/** Addition for GDAL : END */
/***************************************************************************/ /***************************************************************************/
/* for reading the content of the current zipfile, you can open it, read data /* for reading the content of the current zipfile, you can open it, read data
from it, and close it (you can close it before reading all the file) from it, and close it (you can close it before reading all the file)
@@ -312,6 +391,8 @@ extern int ZEXPORT unzReadCurrentFile OF((unzFile file,
*/ */
extern z_off_t ZEXPORT unztell OF((unzFile file)); extern z_off_t ZEXPORT unztell OF((unzFile file));
extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file));
/* /*
Give the current position in uncompressed data Give the current position in uncompressed data
*/ */
@@ -340,9 +421,11 @@ extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
/***************************************************************************/ /***************************************************************************/
/* Get the current file offset */ /* Get the current file offset */
extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file);
extern uLong ZEXPORT unzGetOffset (unzFile file); extern uLong ZEXPORT unzGetOffset (unzFile file);
/* Set the current file offset */ /* Set the current file offset */
extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos);
extern int ZEXPORT unzSetOffset (unzFile file, uLong pos); extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
@@ -351,4 +434,4 @@ extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
} }
#endif #endif
#endif /* _unz_H */ #endif /* _unz64_H */

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,15 @@
/* zip.h -- IO for compress .zip files using zlib /* zip.h -- IO on .zip files using zlib
Version 1.01e, February 12th, 2005 Version 1.1, January 7th, 2010
part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
Copyright (C) 1998-2005 Gilles Vollant Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
This unzip package allow creates .ZIP file, compatible with PKZip 2.04g Modifications for Zip64 support
WinZip, InfoZip tools and compatible. Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
Multi volume ZipFile (span) are not supported.
Encryption compatible with pkzip 2.04g only supported
Old compressions used by old PKZip 1.x are not supported
For uncompress .zip file, look at unzip.h For more info read MiniZip_info.txt
---------------------------------------------------------------------------
I WAIT FEEDBACK at mail info@winimage.com
Visit also http://www.winimage.com/zLibDll/unzip.html for evolution
Condition of use and distribution are the same than zlib : Condition of use and distribution are the same than zlib :
@@ -33,23 +29,23 @@
misrepresented as being the original software. misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution. 3. This notice may not be removed or altered from any source distribution.
---------------------------------------------------------------------------
Changes
See header of zip.h
*/ */
/* for more info about .ZIP format, see #ifndef _zip12_H
http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip #define _zip12_H
http://www.info-zip.org/pub/infozip/doc/
PkWare has also a specification at :
ftp://ftp.pkware.com/probdesc.zip
*/
#ifndef _zip_H
#define _zip_H
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
//#define HAVE_BZIP2
#ifndef _ZLIB_H #ifndef _ZLIB_H
#include "zlib.h" #include "zlib.h"
#endif #endif
@@ -58,6 +54,12 @@ extern "C" {
#include "ioapi.h" #include "ioapi.h"
#endif #endif
#ifdef HAVE_BZIP2
#include "bzlib.h"
#endif
#define Z_BZIP2ED 12
#if defined(STRICTZIP) || defined(STRICTZIPUNZIP) #if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted /* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */ from (void*) without cast */
@@ -112,6 +114,7 @@ typedef const char* zipcharpc;
#define APPEND_STATUS_ADDINZIP (2) #define APPEND_STATUS_ADDINZIP (2)
extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append)); extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append));
/* /*
Create a zipfile. Create a zipfile.
pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on
@@ -136,6 +139,11 @@ extern zipFile ZEXPORT zipOpen2 OF((const char *pathname,
zipcharpc* globalcomment, zipcharpc* globalcomment,
zlib_filefunc_def* pzlib_filefunc_def)); zlib_filefunc_def* pzlib_filefunc_def));
extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname,
int append,
zipcharpc* globalcomment,
zlib_filefunc64_def* pzlib_filefunc_def));
extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
const char* filename, const char* filename,
const zip_fileinfo* zipfi, const zip_fileinfo* zipfi,
@@ -146,6 +154,19 @@ extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
const char* comment, const char* comment,
int method, int method,
int level)); int level));
extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int zip64));
/* /*
Open a file in the ZIP for writing. Open a file in the ZIP for writing.
filename : the filename in zip (if NULL, '-' without quote will be used filename : the filename in zip (if NULL, '-' without quote will be used
@@ -157,6 +178,9 @@ extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
if comment != NULL, comment contain the comment string if comment != NULL, comment contain the comment string
method contain the compression method (0 for store, Z_DEFLATED for deflate) method contain the compression method (0 for store, Z_DEFLATED for deflate)
level contain the level of compression (can be Z_DEFAULT_COMPRESSION) level contain the level of compression (can be Z_DEFAULT_COMPRESSION)
zip64 is set to 1 if a zip64 extended information block should be added to the local file header.
this MUST be '1' if the uncompressed size is >= 0xffffffff.
*/ */
@@ -172,6 +196,19 @@ extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file,
int level, int level,
int raw)); int raw));
extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int zip64));
/* /*
Same than zipOpenNewFileInZip, except if raw=1, we write raw file Same than zipOpenNewFileInZip, except if raw=1, we write raw file
*/ */
@@ -191,13 +228,79 @@ extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file,
int memLevel, int memLevel,
int strategy, int strategy,
const char* password, const char* password,
uLong crcForCtypting)); uLong crcForCrypting));
extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCrypting,
int zip64
));
/* /*
Same than zipOpenNewFileInZip2, except Same than zipOpenNewFileInZip2, except
windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 windowBits,memLevel,,strategy : see parameter strategy in deflateInit2
password : crypting password (NULL for no crypting) password : crypting password (NULL for no crypting)
crcForCtypting : crc of file to compress (needed for crypting) crcForCrypting : crc of file to compress (needed for crypting)
*/
extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCrypting,
uLong versionMadeBy,
uLong flagBase
));
extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCrypting,
uLong versionMadeBy,
uLong flagBase,
int zip64
));
/*
Same than zipOpenNewFileInZip4, except
versionMadeBy : value for Version made by field
flag : value for flag field (compression level info will be added)
*/ */
@@ -216,8 +319,13 @@ extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file,
uLong uncompressed_size, uLong uncompressed_size,
uLong crc32)); uLong crc32));
extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file,
ZPOS64_T uncompressed_size,
uLong crc32));
/* /*
Close the current file in the zipfile, for fiel opened with Close the current file in the zipfile, for file opened with
parameter raw=1 in zipOpenNewFileInZip2 parameter raw=1 in zipOpenNewFileInZip2
uncompressed_size and crc32 are value for the uncompressed size uncompressed_size and crc32 are value for the uncompressed size
*/ */
@@ -228,8 +336,27 @@ extern int ZEXPORT zipClose OF((zipFile file,
Close the zipfile Close the zipfile
*/ */
extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader));
/*
zipRemoveExtraInfoBlock - Added by Mathias Svensson
Remove extra information block from a extra information data for the local file header or central directory header
It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode.
0x0001 is the signature header for the ZIP64 extra information blocks
usage.
Remove ZIP64 Extra information from a central director extra field data
zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001);
Remove ZIP64 Extra information from a Local File Header extra field data
zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001);
*/
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* _zip_H */ #endif /* _zip64_H */

View File

@@ -18,10 +18,10 @@ LDFLAGS =
# variables # variables
ZLIB_LIB = zlib.lib ZLIB_LIB = zlib.lib
OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzio.obj infback.obj OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzio.obj gzlib.obj gzread.obj
OBJ2 = inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzio.obj+infback.obj OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzio.obj+gzlib.obj+gzread.obj
OBJP2 = +inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
# targets # targets
@@ -38,8 +38,16 @@ crc32.obj: crc32.c zlib.h zconf.h crc32.h
deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
gzio.obj: gzio.c zutil.h zlib.h zconf.h gzio.obj: gzio.c zutil.h zlib.h zconf.h
gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
gzread.obj: gzread.c zlib.h zconf.h gzguts.h
gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
inffast.h inffixed.h inffast.h inffixed.h

View File

@@ -1,8 +1,8 @@
/* /*
* puff.c * puff.c
* Copyright (C) 2002-2004 Mark Adler * Copyright (C) 2002-2008 Mark Adler
* For conditions of distribution and use, see copyright notice in puff.h * For conditions of distribution and use, see copyright notice in puff.h
* version 1.8, 9 Jan 2004 * version 2.0, 25 Jul 2008
* *
* puff.c is a simple inflate written to be an unambiguous way to specify the * puff.c is a simple inflate written to be an unambiguous way to specify the
* deflate format. It is not written for speed but rather simplicity. As a * deflate format. It is not written for speed but rather simplicity. As a
@@ -61,6 +61,12 @@
* 1.7 3 Mar 2003 - Added test code for distribution * 1.7 3 Mar 2003 - Added test code for distribution
* - Added zlib-like license * - Added zlib-like license
* 1.8 9 Jan 2004 - Added some comments on no distance codes case * 1.8 9 Jan 2004 - Added some comments on no distance codes case
* 1.9 21 Feb 2008 - Fix bug on 16-bit integer architectures [Pohland]
* - Catch missing end-of-block symbol error
* 2.0 25 Jul 2008 - Add #define to permit distance too far back
* - Add option in TEST code for puff to write the data
* - Add option in TEST code to skip input bytes
* - Allow TEST code to read from piped stdin
*/ */
#include <setjmp.h> /* for setjmp(), longjmp(), and jmp_buf */ #include <setjmp.h> /* for setjmp(), longjmp(), and jmp_buf */
@@ -194,7 +200,7 @@ struct huffman {
* Decode a code from the stream s using huffman table h. Return the symbol or * Decode a code from the stream s using huffman table h. Return the symbol or
* a negative value if there is an error. If all of the lengths are zero, i.e. * a negative value if there is an error. If all of the lengths are zero, i.e.
* an empty code, or if the code is incomplete and an invalid code is received, * an empty code, or if the code is incomplete and an invalid code is received,
* then -9 is returned after reading MAXBITS bits. * then -10 is returned after reading MAXBITS bits.
* *
* Format notes: * Format notes:
* *
@@ -226,14 +232,14 @@ local int decode(struct state *s, struct huffman *h)
for (len = 1; len <= MAXBITS; len++) { for (len = 1; len <= MAXBITS; len++) {
code |= bits(s, 1); /* get next bit */ code |= bits(s, 1); /* get next bit */
count = h->count[len]; count = h->count[len];
if (code < first + count) /* if length len, return symbol */ if (code - count < first) /* if length len, return symbol */
return h->symbol[index + (code - first)]; return h->symbol[index + (code - first)];
index += count; /* else update for next length */ index += count; /* else update for next length */
first += count; first += count;
first <<= 1; first <<= 1;
code <<= 1; code <<= 1;
} }
return -9; /* ran out of codes */ return -10; /* ran out of codes */
} }
/* /*
@@ -263,7 +269,7 @@ local int decode(struct state *s, struct huffman *h)
code |= bitbuf & 1; code |= bitbuf & 1;
bitbuf >>= 1; bitbuf >>= 1;
count = *next++; count = *next++;
if (code < first + count) { /* if length len, return symbol */ if (code - count < first) { /* if length len, return symbol */
s->bitbuf = bitbuf; s->bitbuf = bitbuf;
s->bitcnt = (s->bitcnt - len) & 7; s->bitcnt = (s->bitcnt - len) & 7;
return h->symbol[index + (code - first)]; return h->symbol[index + (code - first)];
@@ -280,7 +286,7 @@ local int decode(struct state *s, struct huffman *h)
bitbuf = s->in[s->incnt++]; bitbuf = s->in[s->incnt++];
if (left > 8) left = 8; if (left > 8) left = 8;
} }
return -9; /* ran out of codes */ return -10; /* ran out of codes */
} }
#endif /* SLOW */ #endif /* SLOW */
@@ -448,21 +454,27 @@ local int codes(struct state *s,
else if (symbol > 256) { /* length */ else if (symbol > 256) { /* length */
/* get and compute length */ /* get and compute length */
symbol -= 257; symbol -= 257;
if (symbol >= 29) return -9; /* invalid fixed code */ if (symbol >= 29) return -10; /* invalid fixed code */
len = lens[symbol] + bits(s, lext[symbol]); len = lens[symbol] + bits(s, lext[symbol]);
/* get and check distance */ /* get and check distance */
symbol = decode(s, distcode); symbol = decode(s, distcode);
if (symbol < 0) return symbol; /* invalid symbol */ if (symbol < 0) return symbol; /* invalid symbol */
dist = dists[symbol] + bits(s, dext[symbol]); dist = dists[symbol] + bits(s, dext[symbol]);
#ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
if (dist > s->outcnt) if (dist > s->outcnt)
return -10; /* distance too far back */ return -11; /* distance too far back */
#endif
/* copy length bytes from distance bytes back */ /* copy length bytes from distance bytes back */
if (s->out != NIL) { if (s->out != NIL) {
if (s->outcnt + len > s->outlen) return 1; if (s->outcnt + len > s->outlen) return 1;
while (len--) { while (len--) {
s->out[s->outcnt] = s->out[s->outcnt - dist]; s->out[s->outcnt] =
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
dist > s->outcnt ? 0 :
#endif
s->out[s->outcnt - dist];
s->outcnt++; s->outcnt++;
} }
} }
@@ -680,6 +692,10 @@ local int dynamic(struct state *s)
} }
} }
/* check for end-of-block code -- there better be one! */
if (lengths[256] == 0)
return -9;
/* build huffman table for literal/length codes */ /* build huffman table for literal/length codes */
err = construct(&lencode, lengths, nlen); err = construct(&lencode, lengths, nlen);
if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1)) if (err < 0 || (err > 0 && nlen - lencode.count[0] != 1))
@@ -724,8 +740,9 @@ local int dynamic(struct state *s)
* -6: dynamic block code description: repeat more than specified lengths * -6: dynamic block code description: repeat more than specified lengths
* -7: dynamic block code description: invalid literal/length code lengths * -7: dynamic block code description: invalid literal/length code lengths
* -8: dynamic block code description: invalid distance code lengths * -8: dynamic block code description: invalid distance code lengths
* -9: invalid literal/length or distance code in fixed or dynamic block * -9: dynamic block code description: missing end-of-block code
* -10: distance is too far back in fixed or dynamic block * -10: invalid literal/length or distance code in fixed or dynamic block
* -11: distance is too far back in fixed or dynamic block
* *
* Format notes: * Format notes:
* *
@@ -783,54 +800,142 @@ int puff(unsigned char *dest, /* pointer to destination pointer */
} }
#ifdef TEST #ifdef TEST
/* Example of how to use puff() */ /* Examples of how to use puff().
Usage: puff [-w] [-nnn] file
... | puff [-w] [-nnn]
where file is the input file with deflate data, nnn is the number of bytes
of input to skip before inflating (e.g. to skip a zlib or gzip header), and
-w is used to write the decompressed data to stdout */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
local unsigned char *yank(char *name, unsigned long *len) /* Return size times approximately the cube root of 2, keeping the result as 1,
3, or 5 times a power of 2 -- the result is always > size, until the result
is the maximum value of an unsigned long, where it remains. This is useful
to keep reallocations less than ~33% over the actual data. */
local size_t bythirds(size_t size)
{ {
unsigned long size; int n;
unsigned char *buf; size_t m;
m = size;
for (n = 0; m; n++)
m >>= 1;
if (n < 3)
return size + 1;
n -= 3;
m = size >> n;
m += m == 6 ? 2 : 1;
m <<= n;
return m > size ? m : (size_t)(-1);
}
/* Read the input file *name, or stdin if name is NULL, into allocated memory.
Reallocate to larger buffers until the entire file is read in. Return a
pointer to the allocated data, or NULL if there was a memory allocation
failure. *len is the number of bytes of data read from the input file (even
if load() returns NULL). If the input file was empty or could not be opened
or read, *len is zero. */
local void *load(char *name, size_t *len)
{
size_t size;
void *buf, *swap;
FILE *in; FILE *in;
struct stat s;
*len = 0; *len = 0;
if (stat(name, &s)) return NULL; buf = malloc(size = 4096);
if ((s.st_mode & S_IFMT) != S_IFREG) return NULL; if (buf == NULL)
size = (unsigned long)(s.st_size); return NULL;
if (size == 0 || (off_t)size != s.st_size) return NULL; in = name == NULL ? stdin : fopen(name, "rb");
in = fopen(name, "r"); if (in != NULL) {
if (in == NULL) return NULL; for (;;) {
buf = malloc(size); *len += fread((char *)buf + *len, 1, size - *len, in);
if (buf != NULL && fread(buf, 1, size, in) != size) { if (*len < size) break;
free(buf); size = bythirds(size);
buf = NULL; if (size == *len || (swap = realloc(buf, size)) == NULL) {
free(buf);
buf = NULL;
break;
}
buf = swap;
}
fclose(in);
} }
fclose(in);
*len = size;
return buf; return buf;
} }
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int ret; int ret, skip = 0, put = 0;
unsigned char *source; char *arg, *name = NULL;
unsigned long len, sourcelen, destlen; unsigned char *source = NULL, *dest;
size_t len = 0;
unsigned long sourcelen, destlen;
if (argc < 2) return 2; /* process arguments */
source = yank(argv[1], &len); while (arg = *++argv, --argc)
if (source == NULL) return 2; if (arg[0] == '-') {
sourcelen = len; if (arg[1] == 'w' && arg[2] == 0)
ret = puff(NIL, &destlen, source, &sourcelen); put = 1;
if (ret) else if (arg[1] >= '0' && arg[1] <= '9')
printf("puff() failed with return code %d\n", ret); skip = atoi(arg + 1);
else { else {
printf("puff() succeeded uncompressing %lu bytes\n", destlen); fprintf(stderr, "invalid option %s\n", arg);
if (sourcelen < len) printf("%lu compressed bytes unused\n", return 3;
len - sourcelen); }
}
else if (name != NULL) {
fprintf(stderr, "only one file name allowed\n");
return 3;
}
else
name = arg;
source = load(name, &len);
if (source == NULL) {
fprintf(stderr, "memory allocation failure\n");
return 4;
} }
if (len == 0) {
fprintf(stderr, "could not read %s, or it was empty\n",
name == NULL ? "<stdin>" : name);
free(source);
return 3;
}
if (skip >= len) {
fprintf(stderr, "skip request of %d leaves no input\n", skip);
free(source);
return 3;
}
/* test inflate data with offset skip */
len -= skip;
sourcelen = (unsigned long)len;
ret = puff(NIL, &destlen, source + skip, &sourcelen);
if (ret)
fprintf(stderr, "puff() failed with return code %d\n", ret);
else {
fprintf(stderr, "puff() succeeded uncompressing %lu bytes\n", destlen);
if (sourcelen < len) fprintf(stderr, "%lu compressed bytes unused\n",
len - sourcelen);
}
/* if requested, inflate again and write decompressd data to stdout */
if (put) {
dest = malloc(destlen);
if (dest == NULL) {
fprintf(stderr, "memory allocation failure\n");
free(source);
return 4;
}
puff(dest, &destlen, source + skip, &sourcelen);
fwrite(dest, 1, destlen, stdout);
free(dest);
}
/* clean up */
free(source); free(source);
return ret; return ret;
} }

View File

@@ -1,6 +1,6 @@
/* puff.h /* puff.h
Copyright (C) 2002, 2003 Mark Adler, all rights reserved Copyright (C) 2002-2008 Mark Adler, all rights reserved
version 1.7, 3 Mar 2002 version 1.9, 10 Jan 2008
This software is provided 'as-is', without any express or implied This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages warranty. In no event will the author be held liable for any damages

View File

@@ -103,12 +103,12 @@ DWORD GetMsecSincePerfCounter(LARGE_INTEGER beginTime64,BOOL fComputeTimeQueryPe
MyDoMinus64(&ticks,endTime64,beginTime64); MyDoMinus64(&ticks,endTime64,beginTime64);
QueryPerformanceFrequency(&ticksPerSecond); QueryPerformanceFrequency(&ticksPerSecond);
{ {
ticksShifted = Int64ShrlMod32(*(DWORDLONG*)&ticks,dwLog); ticksShifted = Int64ShrlMod32(*(DWORDLONG*)&ticks,dwLog);
tickSecShifted = Int64ShrlMod32(*(DWORDLONG*)&ticksPerSecond,dwLog); tickSecShifted = Int64ShrlMod32(*(DWORDLONG*)&ticksPerSecond,dwLog);
} }
dwRet = (DWORD)((((DWORD)ticksShifted)*1000)/(DWORD)(tickSecShifted)); dwRet = (DWORD)((((DWORD)ticksShifted)*1000)/(DWORD)(tickSecShifted));
dwRet *=1; dwRet *=1;

View File

@@ -30,9 +30,9 @@ Build instructions for Visual Studio 2005 (32 bits or 64 bits)
Build instructions for Visual Studio 2005 64 bits, PSDK compiler Build instructions for Visual Studio 2005 64 bits, PSDK compiler
---------------------------------------------------------------- ----------------------------------------------------------------
at the time of writing this text file, Visual Studio 2005 (and at the time of writing this text file, Visual Studio 2005 (and
Microsoft Visual C++ 8.0) is on the beta 2 stage. Microsoft Visual C++ 8.0) is on the beta 2 stage.
Using you can get the free 64 bits compiler from Platform SDK, Using you can get the free 64 bits compiler from Platform SDK,
which is NOT a beta, and compile using the Visual studio 2005 IDE which is NOT a beta, and compile using the Visual studio 2005 IDE
see http://www.winimage.com/misc/sdk64onvs2005/ for instruction see http://www.winimage.com/misc/sdk64onvs2005/ for instruction

View File

@@ -2,8 +2,8 @@
#define IDR_VERSION1 1 #define IDR_VERSION1 1
IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE IDR_VERSION1 VERSIONINFO MOVEABLE IMPURE LOADONCALL DISCARDABLE
FILEVERSION 1,2,3,1 FILEVERSION 1,2,3,8
PRODUCTVERSION 1,2,3,1 PRODUCTVERSION 1,2,3,8
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
FILEFLAGS 0 FILEFLAGS 0
FILEOS VOS_DOS_WINDOWS32 FILEOS VOS_DOS_WINDOWS32
@@ -17,12 +17,12 @@ BEGIN
BEGIN BEGIN
VALUE "FileDescription", "zlib data compression library\0" VALUE "FileDescription", "zlib data compression library\0"
VALUE "FileVersion", "1.2.3.1\0" VALUE "FileVersion", "1.2.3.8\0"
VALUE "InternalName", "zlib\0" VALUE "InternalName", "zlib\0"
VALUE "OriginalFilename", "zlib.dll\0" VALUE "OriginalFilename", "zlib.dll\0"
VALUE "ProductName", "ZLib.DLL\0" VALUE "ProductName", "ZLib.DLL\0"
VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0" VALUE "Comments","DLL support by Alessandro Iacopetti & Gilles Vollant\0"
VALUE "LegalCopyright", "(C) 1995-2003 Jean-loup Gailly & Mark Adler\0" VALUE "LegalCopyright", "(C) 1995-2010 Jean-loup Gailly & Mark Adler\0"
END END
END END
BLOCK "VarFileInfo" BLOCK "VarFileInfo"

View File

@@ -200,9 +200,21 @@
<File <File
RelativePath="..\..\masmx86\gvmat32c.c"> RelativePath="..\..\masmx86\gvmat32c.c">
</File> </File>
<File
RelativePath="..\..\..\gzclose.c">
</File>
<File <File
RelativePath="..\..\..\gzio.c"> RelativePath="..\..\..\gzio.c">
</File> </File>
<File
RelativePath="..\..\..\gzlib.c">
</File>
<File
RelativePath="..\..\..\gzread.c">
</File>
<File
RelativePath="..\..\..\gzwrite.c">
</File>
<File <File
RelativePath="..\..\..\infback.c"> RelativePath="..\..\..\infback.c">
</File> </File>

View File

@@ -347,9 +347,21 @@
Name="VCCLCompilerTool"/> Name="VCCLCompilerTool"/>
</FileConfiguration> </FileConfiguration>
</File> </File>
<File
RelativePath="..\..\..\gzclose.c">
</File>
<File <File
RelativePath="..\..\..\gzio.c"> RelativePath="..\..\..\gzio.c">
</File> </File>
<File
RelativePath="..\..\..\gzlib.c">
</File>
<File
RelativePath="..\..\..\gzread.c">
</File>
<File
RelativePath="..\..\..\gzwrite.c">
</File>
<File <File
RelativePath="..\..\..\infback.c"> RelativePath="..\..\..\infback.c">
</File> </File>

View File

@@ -760,8 +760,19 @@
</FileConfiguration> </FileConfiguration>
</File> </File>
<File <File
RelativePath="..\..\..\gzio.c" RelativePath="..\..\..\gzclose.c">
> </File>
<File
RelativePath="..\..\..\gzio.c">
</File>
<File
RelativePath="..\..\..\gzlib.c">
</File>
<File
RelativePath="..\..\..\gzread.c">
</File>
<File
RelativePath="..\..\..\gzwrite.c">
</File> </File>
<File <File
RelativePath="..\..\..\infback.c" RelativePath="..\..\..\infback.c"

View File

@@ -1005,8 +1005,19 @@
</FileConfiguration> </FileConfiguration>
</File> </File>
<File <File
RelativePath="..\..\..\gzio.c" RelativePath="..\..\..\gzclose.c">
> </File>
<File
RelativePath="..\..\..\gzio.c">
</File>
<File
RelativePath="..\..\..\gzlib.c">
</File>
<File
RelativePath="..\..\..\gzread.c">
</File>
<File
RelativePath="..\..\..\gzwrite.c">
</File> </File>
<File <File
RelativePath="..\..\..\infback.c" RelativePath="..\..\..\infback.c"

33
crc32.c
View File

@@ -1,5 +1,5 @@
/* crc32.c -- compute the CRC-32 of a data stream /* crc32.c -- compute the CRC-32 of a data stream
* Copyright (C) 1995-2005 Mark Adler * Copyright (C) 1995-2006 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
* *
* Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
@@ -53,7 +53,7 @@
/* Definitions for doing the crc four data bytes at a time. */ /* Definitions for doing the crc four data bytes at a time. */
#ifdef BYFOUR #ifdef BYFOUR
# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ # define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \
(((w)&0xff00)<<8)+(((w)&0xff)<<24)) (((w)&0xff00)<<8)+(((w)&0xff)<<24))
local unsigned long crc32_little OF((unsigned long, local unsigned long crc32_little OF((unsigned long,
const unsigned char FAR *, unsigned)); const unsigned char FAR *, unsigned));
@@ -68,6 +68,8 @@
local unsigned long gf2_matrix_times OF((unsigned long *mat, local unsigned long gf2_matrix_times OF((unsigned long *mat,
unsigned long vec)); unsigned long vec));
local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2);
#ifdef DYNAMIC_CRC_TABLE #ifdef DYNAMIC_CRC_TABLE
@@ -367,22 +369,22 @@ local void gf2_matrix_square(square, mat)
} }
/* ========================================================================= */ /* ========================================================================= */
uLong ZEXPORT crc32_combine(crc1, crc2, len2) local uLong crc32_combine_(crc1, crc2, len2)
uLong crc1; uLong crc1;
uLong crc2; uLong crc2;
z_off_t len2; z_off64_t len2;
{ {
int n; int n;
unsigned long row; unsigned long row;
unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
/* degenerate case */ /* degenerate case (also disallow negative lengths) */
if (len2 == 0) if (len2 <= 0)
return crc1; return crc1;
/* put operator for one zero bit in odd */ /* put operator for one zero bit in odd */
odd[0] = 0xedb88320L; /* CRC-32 polynomial */ odd[0] = 0xedb88320UL; /* CRC-32 polynomial */
row = 1; row = 1;
for (n = 1; n < GF2_DIM; n++) { for (n = 1; n < GF2_DIM; n++) {
odd[n] = row; odd[n] = row;
@@ -421,3 +423,20 @@ uLong ZEXPORT crc32_combine(crc1, crc2, len2)
crc1 ^= crc2; crc1 ^= crc2;
return crc1; return crc1;
} }
/* ========================================================================= */
uLong ZEXPORT crc32_combine(crc1, crc2, len2)
uLong crc1;
uLong crc2;
z_off_t len2;
{
return crc32_combine_(crc1, crc2, len2);
}
uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
uLong crc1;
uLong crc2;
z_off64_t len2;
{
return crc32_combine_(crc1, crc2, len2);
}

210
deflate.c
View File

@@ -1,5 +1,5 @@
/* deflate.c -- compress data using the deflation algorithm /* deflate.c -- compress data using the deflation algorithm
* Copyright (C) 1995-2005 Jean-loup Gailly. * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -52,7 +52,7 @@
#include "deflate.h" #include "deflate.h"
const char deflate_copyright[] = const char deflate_copyright[] =
" deflate 1.2.3.1 Copyright 1995-2005 Jean-loup Gailly "; " deflate 1.2.3.8 Copyright 1995-2010 Jean-loup Gailly and Mark Adler ";
/* /*
If you use the zlib library in a product, an acknowledgment is welcome 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 in the documentation of your product. If for some reason you cannot
@@ -79,19 +79,18 @@ local block_state deflate_fast OF((deflate_state *s, int flush));
#ifndef FASTEST #ifndef FASTEST
local block_state deflate_slow OF((deflate_state *s, int flush)); local block_state deflate_slow OF((deflate_state *s, int flush));
#endif #endif
local block_state deflate_rle OF((deflate_state *s, int flush));
local block_state deflate_huff OF((deflate_state *s, int flush));
local void lm_init OF((deflate_state *s)); local void lm_init OF((deflate_state *s));
local void putShortMSB OF((deflate_state *s, uInt b)); local void putShortMSB OF((deflate_state *s, uInt b));
local void flush_pending OF((z_streamp strm)); local void flush_pending OF((z_streamp strm));
local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
#ifndef FASTEST
#ifdef ASMV #ifdef ASMV
void match_init OF((void)); /* asm code initialization */ void match_init OF((void)); /* asm code initialization */
uInt longest_match OF((deflate_state *s, IPos cur_match)); uInt longest_match OF((deflate_state *s, IPos cur_match));
#else #else
local uInt longest_match OF((deflate_state *s, IPos cur_match)); local uInt longest_match OF((deflate_state *s, IPos cur_match));
#endif #endif
#endif
local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
#ifdef DEBUG #ifdef DEBUG
local void check_match OF((deflate_state *s, IPos start, IPos match, local void check_match OF((deflate_state *s, IPos start, IPos match,
@@ -110,11 +109,6 @@ local void check_match OF((deflate_state *s, IPos start, IPos match,
#endif #endif
/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ /* 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 /* 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 * 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 * exclude worst case performance for pathological files. Better values may be
@@ -288,6 +282,8 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
s->high_water = 0; /* nothing written to s->window yet */
s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
@@ -332,8 +328,8 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
strm->adler = adler32(strm->adler, dictionary, dictLength); strm->adler = adler32(strm->adler, dictionary, dictLength);
if (length < MIN_MATCH) return Z_OK; if (length < MIN_MATCH) return Z_OK;
if (length > MAX_DIST(s)) { if (length > s->w_size) {
length = MAX_DIST(s); length = s->w_size;
dictionary += dictLength - length; /* use the tail of the dictionary */ dictionary += dictLength - length; /* use the tail of the dictionary */
} }
zmemcpy(s->window, dictionary, length); zmemcpy(s->window, dictionary, length);
@@ -435,9 +431,10 @@ int ZEXPORT deflateParams(strm, level, strategy)
} }
func = configuration_table[s->level].func; func = configuration_table[s->level].func;
if (func != configuration_table[level].func && strm->total_in != 0) { if ((strategy != s->strategy || func != configuration_table[level].func) &&
strm->total_in != 0) {
/* Flush the last buffer: */ /* Flush the last buffer: */
err = deflate(strm, Z_PARTIAL_FLUSH); err = deflate(strm, Z_BLOCK);
} }
if (s->level != level) { if (s->level != level) {
s->level = level; s->level = level;
@@ -513,16 +510,16 @@ uLong ZEXPORT deflateBound(strm, sourceLen)
break; break;
case 2: /* gzip wrapper */ case 2: /* gzip wrapper */
wraplen = 18; wraplen = 18;
if (s->gzhead != NULL) { /* user-supplied gzip header */ if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
if (s->gzhead->extra != NULL) if (s->gzhead->extra != Z_NULL)
wraplen += 2 + s->gzhead->extra_len; wraplen += 2 + s->gzhead->extra_len;
str = s->gzhead->name; str = s->gzhead->name;
if (str != NULL) if (str != Z_NULL)
do { do {
wraplen++; wraplen++;
} while (*str++); } while (*str++);
str = s->gzhead->comment; str = s->gzhead->comment;
if (str != NULL) if (str != Z_NULL)
do { do {
wraplen++; wraplen++;
} while (*str++); } while (*str++);
@@ -539,7 +536,8 @@ uLong ZEXPORT deflateBound(strm, sourceLen)
return complen + wraplen; return complen + wraplen;
/* default settings: return tight bound for that case */ /* default settings: return tight bound for that case */
return compressBound(sourceLen) - 6 + wraplen; return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
(sourceLen >> 25) + 13 - 6 + wraplen;
} }
/* ========================================================================= /* =========================================================================
@@ -589,7 +587,7 @@ int ZEXPORT deflate (strm, flush)
deflate_state *s; deflate_state *s;
if (strm == Z_NULL || strm->state == Z_NULL || if (strm == Z_NULL || strm->state == Z_NULL ||
flush > Z_FINISH || flush < 0) { flush > Z_BLOCK || flush < 0) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
s = strm->state; s = strm->state;
@@ -613,7 +611,7 @@ int ZEXPORT deflate (strm, flush)
put_byte(s, 31); put_byte(s, 31);
put_byte(s, 139); put_byte(s, 139);
put_byte(s, 8); put_byte(s, 8);
if (s->gzhead == NULL) { if (s->gzhead == Z_NULL) {
put_byte(s, 0); put_byte(s, 0);
put_byte(s, 0); put_byte(s, 0);
put_byte(s, 0); put_byte(s, 0);
@@ -640,7 +638,7 @@ int ZEXPORT deflate (strm, flush)
(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
4 : 0)); 4 : 0));
put_byte(s, s->gzhead->os & 0xff); put_byte(s, s->gzhead->os & 0xff);
if (s->gzhead->extra != NULL) { if (s->gzhead->extra != Z_NULL) {
put_byte(s, s->gzhead->extra_len & 0xff); put_byte(s, s->gzhead->extra_len & 0xff);
put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
} }
@@ -682,7 +680,7 @@ int ZEXPORT deflate (strm, flush)
} }
#ifdef GZIP #ifdef GZIP
if (s->status == EXTRA_STATE) { if (s->status == EXTRA_STATE) {
if (s->gzhead->extra != NULL) { if (s->gzhead->extra != Z_NULL) {
uInt beg = s->pending; /* start of bytes to update crc */ uInt beg = s->pending; /* start of bytes to update crc */
while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
@@ -710,7 +708,7 @@ int ZEXPORT deflate (strm, flush)
s->status = NAME_STATE; s->status = NAME_STATE;
} }
if (s->status == NAME_STATE) { if (s->status == NAME_STATE) {
if (s->gzhead->name != NULL) { if (s->gzhead->name != Z_NULL) {
uInt beg = s->pending; /* start of bytes to update crc */ uInt beg = s->pending; /* start of bytes to update crc */
int val; int val;
@@ -741,7 +739,7 @@ int ZEXPORT deflate (strm, flush)
s->status = COMMENT_STATE; s->status = COMMENT_STATE;
} }
if (s->status == COMMENT_STATE) { if (s->status == COMMENT_STATE) {
if (s->gzhead->comment != NULL) { if (s->gzhead->comment != Z_NULL) {
uInt beg = s->pending; /* start of bytes to update crc */ uInt beg = s->pending; /* start of bytes to update crc */
int val; int val;
@@ -819,7 +817,9 @@ int ZEXPORT deflate (strm, flush)
(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
block_state bstate; block_state bstate;
bstate = (*(configuration_table[s->level].func))(s, flush); bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
(s->strategy == Z_RLE ? deflate_rle(s, flush) :
(*(configuration_table[s->level].func))(s, flush));
if (bstate == finish_started || bstate == finish_done) { if (bstate == finish_started || bstate == finish_done) {
s->status = FINISH_STATE; s->status = FINISH_STATE;
@@ -840,13 +840,17 @@ int ZEXPORT deflate (strm, flush)
if (bstate == block_done) { if (bstate == block_done) {
if (flush == Z_PARTIAL_FLUSH) { if (flush == Z_PARTIAL_FLUSH) {
_tr_align(s); _tr_align(s);
} else { /* FULL_FLUSH or SYNC_FLUSH */ } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
_tr_stored_block(s, (char*)0, 0L, 0); _tr_stored_block(s, (char*)0, 0L, 0);
/* For a full flush, this empty block will be recognized /* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync(). * as a special marker by inflate_sync().
*/ */
if (flush == Z_FULL_FLUSH) { if (flush == Z_FULL_FLUSH) {
CLEAR_HASH(s); /* forget history */ CLEAR_HASH(s); /* forget history */
if (s->lookahead == 0) {
s->strstart = 0;
s->block_start = 0L;
}
} }
} }
flush_pending(strm); flush_pending(strm);
@@ -1199,12 +1203,13 @@ local uInt longest_match(s, cur_match)
return s->lookahead; return s->lookahead;
} }
#endif /* ASMV */ #endif /* ASMV */
#endif /* FASTEST */
#else /* FASTEST */
/* --------------------------------------------------------------------------- /* ---------------------------------------------------------------------------
* Optimized version for level == 1 or strategy == Z_RLE only * Optimized version for FASTEST only
*/ */
local uInt longest_match_fast(s, cur_match) local uInt longest_match(s, cur_match)
deflate_state *s; deflate_state *s;
IPos cur_match; /* current match */ IPos cur_match; /* current match */
{ {
@@ -1257,6 +1262,8 @@ local uInt longest_match_fast(s, cur_match)
return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
} }
#endif /* FASTEST */
#ifdef DEBUG #ifdef DEBUG
/* =========================================================================== /* ===========================================================================
* Check that the match at match_start is indeed a match. * Check that the match at match_start is indeed a match.
@@ -1335,7 +1342,6 @@ local void fill_window(s)
later. (Using level 0 permanently is not an optimal usage of later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.) zlib, so we don't care about this pathological case.)
*/ */
/* %%% avoid this when Z_RLE */
n = s->hash_size; n = s->hash_size;
p = &s->head[n]; p = &s->head[n];
do { do {
@@ -1387,6 +1393,40 @@ local void fill_window(s)
*/ */
} while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
if (s->high_water < s->window_size) {
ulg curr = s->strstart + (ulg)(s->lookahead);
ulg init;
if (s->high_water < curr) {
/* Previous high water mark below current data -- zero WIN_INIT
* bytes or up to end of window, whichever is less.
*/
init = s->window_size - curr;
if (init > WIN_INIT)
init = WIN_INIT;
zmemzero(s->window + curr, (unsigned)init);
s->high_water = curr + init;
}
else if (s->high_water < (ulg)curr + WIN_INIT) {
/* High water mark at or above current data, but below current data
* plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
* to end of window, whichever is less.
*/
init = (ulg)curr + WIN_INIT - s->high_water;
if (init > s->window_size - s->high_water)
init = s->window_size - s->high_water;
zmemzero(s->window + s->high_water, (unsigned)init);
s->high_water += init;
}
}
} }
/* =========================================================================== /* ===========================================================================
@@ -1481,7 +1521,7 @@ local block_state deflate_fast(s, flush)
deflate_state *s; deflate_state *s;
int flush; int flush;
{ {
IPos hash_head = NIL; /* head of the hash chain */ IPos hash_head; /* head of the hash chain */
int bflush; /* set if current block must be flushed */ int bflush; /* set if current block must be flushed */
for (;;) { for (;;) {
@@ -1501,6 +1541,7 @@ local block_state deflate_fast(s, flush)
/* Insert the string window[strstart .. strstart+2] in the /* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain: * dictionary, and set hash_head to the head of the hash chain:
*/ */
hash_head = NIL;
if (s->lookahead >= MIN_MATCH) { if (s->lookahead >= MIN_MATCH) {
INSERT_STRING(s, s->strstart, hash_head); INSERT_STRING(s, s->strstart, hash_head);
} }
@@ -1513,19 +1554,8 @@ local block_state deflate_fast(s, flush)
* of window index 0 (in particular we have to avoid a match * of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file). * of the string with itself at the start of the input file).
*/ */
#ifdef FASTEST s->match_length = longest_match (s, hash_head);
if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || /* longest_match() sets match_start */
(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->strategy != Z_RLE) {
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) { if (s->match_length >= MIN_MATCH) {
check_match(s, s->strstart, s->match_start, s->match_length); check_match(s, s->strstart, s->match_start, s->match_length);
@@ -1587,7 +1617,7 @@ local block_state deflate_slow(s, flush)
deflate_state *s; deflate_state *s;
int flush; int flush;
{ {
IPos hash_head = NIL; /* head of hash chain */ IPos hash_head; /* head of hash chain */
int bflush; /* set if current block must be flushed */ int bflush; /* set if current block must be flushed */
/* Process the input block. */ /* Process the input block. */
@@ -1608,6 +1638,7 @@ local block_state deflate_slow(s, flush)
/* Insert the string window[strstart .. strstart+2] in the /* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain: * dictionary, and set hash_head to the head of the hash chain:
*/ */
hash_head = NIL;
if (s->lookahead >= MIN_MATCH) { if (s->lookahead >= MIN_MATCH) {
INSERT_STRING(s, s->strstart, hash_head); INSERT_STRING(s, s->strstart, hash_head);
} }
@@ -1623,12 +1654,8 @@ local block_state deflate_slow(s, flush)
* of window index 0 (in particular we have to avoid a match * of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file). * of the string with itself at the start of the input file).
*/ */
if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { s->match_length = longest_match (s, hash_head);
s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */
} 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 (s->match_length <= 5 && (s->strategy == Z_FILTERED
#if TOO_FAR <= 32767 #if TOO_FAR <= 32767
@@ -1706,7 +1733,6 @@ local block_state deflate_slow(s, flush)
} }
#endif /* FASTEST */ #endif /* FASTEST */
#if 0
/* =========================================================================== /* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance * For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of * one. Do not maintain a hash table. (It will be regenerated if this run of
@@ -1716,11 +1742,9 @@ local block_state deflate_rle(s, flush)
deflate_state *s; deflate_state *s;
int flush; int flush;
{ {
int bflush; /* set if current block must be flushed */ int bflush; /* set if current block must be flushed */
uInt run; /* length of run */ uInt prev; /* byte at distance one to match */
uInt max; /* maximum length of run */ Bytef *scan, *strend; /* scan goes up to strend for length of run */
uInt prev; /* byte at distance one to match */
Bytef *scan; /* scan for end of run */
for (;;) { for (;;) {
/* Make sure that we always have enough lookahead, except /* Make sure that we always have enough lookahead, except
@@ -1736,23 +1760,33 @@ local block_state deflate_rle(s, flush)
} }
/* See how many times the previous byte repeats */ /* See how many times the previous byte repeats */
run = 0; s->match_length = 0;
if (s->strstart > 0) { /* if there is a previous byte, that is */ if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
scan = s->window + s->strstart - 1; scan = s->window + s->strstart - 1;
prev = *scan++; prev = *scan;
do { if (prev == *++scan && prev == *++scan && prev == *++scan) {
if (*scan++ != prev) strend = s->window + s->strstart + MAX_MATCH;
break; do {
} while (++run < max); } while (prev == *++scan && prev == *++scan &&
prev == *++scan && prev == *++scan &&
prev == *++scan && prev == *++scan &&
prev == *++scan && prev == *++scan &&
scan < strend);
s->match_length = MAX_MATCH - (int)(strend - scan);
if (s->match_length > s->lookahead)
s->match_length = s->lookahead;
}
} }
/* Emit match if have run of MIN_MATCH or longer, else emit literal */ /* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (run >= MIN_MATCH) { if (s->match_length >= MIN_MATCH) {
check_match(s, s->strstart, s->strstart - 1, run); check_match(s, s->strstart, s->strstart - 1, s->match_length);
_tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
s->lookahead -= run; _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
s->strstart += run;
s->lookahead -= s->match_length;
s->strstart += s->match_length;
s->match_length = 0;
} else { } else {
/* No match, output a literal byte */ /* No match, output a literal byte */
Tracevv((stderr,"%c", s->window[s->strstart])); Tracevv((stderr,"%c", s->window[s->strstart]));
@@ -1765,4 +1799,36 @@ local block_state deflate_rle(s, flush)
FLUSH_BLOCK(s, flush == Z_FINISH); FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done; return flush == Z_FINISH ? finish_done : block_done;
} }
#endif
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
local block_state deflate_huff(s, flush)
deflate_state *s;
int flush;
{
int bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s->lookahead == 0) {
fill_window(s);
if (s->lookahead == 0) {
if (flush == Z_NO_FLUSH)
return need_more;
break; /* flush the current block */
}
}
/* Output a literal byte */
s->match_length = 0;
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;
}

View File

@@ -1,5 +1,5 @@
/* deflate.h -- internal compression state /* deflate.h -- internal compression state
* Copyright (C) 1995-2005 Jean-loup Gailly * Copyright (C) 1995-2009 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -260,6 +260,13 @@ typedef struct internal_state {
* are always zero. * are always zero.
*/ */
ulg high_water;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
} FAR deflate_state; } FAR deflate_state;
/* Output a byte on the stream. /* Output a byte on the stream.
@@ -278,6 +285,10 @@ typedef struct internal_state {
* distances are limited to MAX_DIST instead of WSIZE. * distances are limited to MAX_DIST instead of WSIZE.
*/ */
#define WIN_INIT MAX_MATCH
/* Number of bytes after end of data in window to initialize in order to avoid
memory checker errors from longest match routines */
/* in trees.c */ /* in trees.c */
void _tr_init OF((deflate_state *s)); void _tr_init OF((deflate_state *s));
int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));

View File

@@ -121,7 +121,7 @@ At least for deflate's output that generates new trees every several 10's of
kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code
would take too long if you're only decoding several thousand symbols. At the would take too long if you're only decoding several thousand symbols. At the
other extreme, you could make a new table for every bit in the code. In fact, other extreme, you could make a new table for every bit in the code. In fact,
that's essentially a Huffman tree. But then you spend two much time that's essentially a Huffman tree. But then you spend too much time
traversing the tree while decoding, even for short symbols. traversing the tree while decoding, even for short symbols.
So the number of bits for the first lookup table is a trade of the time to So the number of bits for the first lookup table is a trade of the time to

View File

@@ -1,4 +1,10 @@
This directory contains examples of the use of zlib. This directory contains examples of the use of zlib and other relevant
programs and documentation.
enough.c
calculation and justification of ENOUGH parameter in inftrees.h
- calculates the maximum table space used in inflate tree
construction over all possible Huffman codes
fitblk.c fitblk.c
compress just enough input to nearly fill a requested output size compress just enough input to nearly fill a requested output size
@@ -23,9 +29,10 @@ gzjoin.c
gzlog.c gzlog.c
gzlog.h gzlog.h
efficiently maintain a message log file in gzip format efficiently and robustly maintain a message log file in gzip format
- illustrates use of raw deflate and Z_SYNC_FLUSH - illustrates use of raw deflate, Z_PARTIAL_FLUSH, deflatePrime(),
- illustrates use of gzip header extra field and deflateSetDictionary()
- illustrates use of a gzip header extra field
zlib_how.html zlib_how.html
painfully comprehensive description of zpipe.c (see below) painfully comprehensive description of zpipe.c (see below)

569
examples/enough.c Normal file
View File

@@ -0,0 +1,569 @@
/* enough.c -- determine the maximum size of inflate's Huffman code tables over
* all possible valid and complete Huffman codes, subject to a length limit.
* Copyright (C) 2007, 2008 Mark Adler
* Version 1.3 17 February 2008 Mark Adler
*/
/* Version history:
1.0 3 Jan 2007 First version (derived from codecount.c version 1.4)
1.1 4 Jan 2007 Use faster incremental table usage computation
Prune examine() search on previously visited states
1.2 5 Jan 2007 Comments clean up
As inflate does, decrease root for short codes
Refuse cases where inflate would increase root
1.3 17 Feb 2008 Add argument for initial root table size
Fix bug for initial root table size == max - 1
Use a macro to compute the history index
*/
/*
Examine all possible Huffman codes for a given number of symbols and a
maximum code length in bits to determine the maximum table size for zilb's
inflate. Only complete Huffman codes are counted.
Two codes are considered distinct if the vectors of the number of codes per
length are not identical. So permutations of the symbol assignments result
in the same code for the counting, as do permutations of the assignments of
the bit values to the codes (i.e. only canonical codes are counted).
We build a code from shorter to longer lengths, determining how many symbols
are coded at each length. At each step, we have how many symbols remain to
be coded, what the last code length used was, and how many bit patterns of
that length remain unused. Then we add one to the code length and double the
number of unused patterns to graduate to the next code length. We then
assign all portions of the remaining symbols to that code length that
preserve the properties of a correct and eventually complete code. Those
properties are: we cannot use more bit patterns than are available; and when
all the symbols are used, there are exactly zero possible bit patterns
remaining.
The inflate Huffman decoding algorithm uses two-level lookup tables for
speed. There is a single first-level table to decode codes up to root bits
in length (root == 9 in the current inflate implementation). The table
has 1 << root entries and is indexed by the next root bits of input. Codes
shorter than root bits have replicated table entries, so that the correct
entry is pointed to regardless of the bits that follow the short code. If
the code is longer than root bits, then the table entry points to a second-
level table. The size of that table is determined by the longest code with
that root-bit prefix. If that longest code has length len, then the table
has size 1 << (len - root), to index the remaining bits in that set of
codes. Each subsequent root-bit prefix then has its own sub-table. The
total number of table entries required by the code is calculated
incrementally as the number of codes at each bit length is populated. When
all of the codes are shorter than root bits, then root is reduced to the
longest code length, resulting in a single, smaller, one-level table.
The inflate algorithm also provides for small values of root (relative to
the log2 of the number of symbols), where the shortest code has more bits
than root. In that case, root is increased to the length of the shortest
code. This program, by design, does not handle that case, so it is verified
that the number of symbols is less than 2^(root + 1).
In order to speed up the examination (by about ten orders of magnitude for
the default arguments), the intermediate states in the build-up of a code
are remembered and previously visited branches are pruned. The memory
required for this will increase rapidly with the total number of symbols and
the maximum code length in bits. However this is a very small price to pay
for the vast speedup.
First, all of the possible Huffman codes are counted, and reachable
intermediate states are noted by a non-zero count in a saved-results array.
Second, the intermediate states that lead to (root + 1) bit or longer codes
are used to look at all sub-codes from those junctures for their inflate
memory usage. (The amount of memory used is not affected by the number of
codes of root bits or less in length.) Third, the visited states in the
construction of those sub-codes and the associated calculation of the table
size is recalled in order to avoid recalculating from the same juncture.
Beginning the code examination at (root + 1) bit codes, which is enabled by
identifying the reachable nodes, accounts for about six of the orders of
magnitude of improvement for the default arguments. About another four
orders of magnitude come from not revisiting previous states. Out of
approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes
need to be examined to cover all of the possible table memory usage cases
for the default arguments of 286 symbols limited to 15-bit codes.
Note that an unsigned long long type is used for counting. It is quite easy
to exceed the capacity of an eight-byte integer with a large number of
symbols and a large maximum code length, so multiple-precision arithmetic
would need to replace the unsigned long long arithmetic in that case. This
program will abort if an overflow occurs. The big_t type identifies where
the counting takes place.
An unsigned long long type is also used for calculating the number of
possible codes remaining at the maximum length. This limits the maximum
code length to the number of bits in a long long minus the number of bits
needed to represent the symbols in a flat code. The code_t type identifies
where the bit pattern counting takes place.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define local static
/* special data types */
typedef unsigned long long big_t; /* type for code counting */
typedef unsigned long long code_t; /* type for bit pattern counting */
struct tab { /* type for been here check */
size_t len; /* length of bit vector in char's */
char *vec; /* allocated bit vector */
};
/* The array for saving results, num[], is indexed with this triplet:
syms: number of symbols remaining to code
left: number of available bit patterns at length len
len: number of bits in the codes currently being assigned
Those indices are constrained thusly when saving results:
syms: 3..totsym (totsym == total symbols to code)
left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
len: 1..max - 1 (max == maximum code length in bits)
syms == 2 is not saved since that immediately leads to a single code. left
must be even, since it represents the number of available bit patterns at
the current length, which is double the number at the previous length.
left ends at syms-1 since left == syms immediately results in a single code.
(left > sym is not allowed since that would result in an incomplete code.)
len is less than max, since the code completes immediately when len == max.
The offset into the array is calculated for the three indices with the
first one (syms) being outermost, and the last one (len) being innermost.
We build the array with length max-1 lists for the len index, with syms-3
of those for each symbol. There are totsym-2 of those, with each one
varying in length as a function of sym. See the calculation of index in
count() for the index, and the calculation of size in main() for the size
of the array.
For the deflate example of 286 symbols limited to 15-bit codes, the array
has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than
half of the space allocated for saved results is actually used -- not all
possible triplets are reached in the generation of valid Huffman codes.
*/
/* The array for tracking visited states, done[], is itself indexed identically
to the num[] array as described above for the (syms, left, len) triplet.
Each element in the array is further indexed by the (mem, rem) doublet,
where mem is the amount of inflate table space used so far, and rem is the
remaining unused entries in the current inflate sub-table. Each indexed
element is simply one bit indicating whether the state has been visited or
not. Since the ranges for mem and rem are not known a priori, each bit
vector is of a variable size, and grows as needed to accommodate the visited
states. mem and rem are used to calculate a single index in a triangular
array. Since the range of mem is expected in the default case to be about
ten times larger than the range of rem, the array is skewed to reduce the
memory usage, with eight times the range for mem than for rem. See the
calculations for offset and bit in beenhere() for the details.
For the deflate example of 286 symbols limited to 15-bit codes, the bit
vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[]
array itself.
*/
/* Globals to avoid propagating constants or constant pointers recursively */
local int max; /* maximum allowed bit length for the codes */
local int root; /* size of base code table in bits */
local int large; /* largest code table so far */
local size_t size; /* number of elements in num and done */
local int *code; /* number of symbols assigned to each bit length */
local big_t *num; /* saved results array for code counting */
local struct tab *done; /* states already evaluated array */
/* Index function for num[] and done[] */
#define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(max-1)+k-1)
/* Free allocated space. Uses globals code, num, and done. */
local void cleanup(void)
{
size_t n;
if (done != NULL) {
for (n = 0; n < size; n++)
if (done[n].len)
free(done[n].vec);
free(done);
}
if (num != NULL)
free(num);
if (code != NULL)
free(code);
}
/* Return the number of possible Huffman codes using bit patterns of lengths
len through max inclusive, coding syms symbols, with left bit patterns of
length len unused -- return -1 if there is an overflow in the counting.
Keep a record of previous results in num to prevent repeating the same
calculation. Uses the globals max and num. */
local big_t count(int syms, int len, int left)
{
big_t sum; /* number of possible codes from this juncture */
big_t got; /* value returned from count() */
int least; /* least number of syms to use at this juncture */
int most; /* most number of syms to use at this juncture */
int use; /* number of bit patterns to use in next call */
size_t index; /* index of this case in *num */
/* see if only one possible code */
if (syms == left)
return 1;
/* note and verify the expected state */
assert(syms > left && left > 0 && len < max);
/* see if we've done this one already */
index = INDEX(syms, left, len);
got = num[index];
if (got)
return got; /* we have -- return the saved result */
/* we need to use at least this many bit patterns so that the code won't be
incomplete at the next length (more bit patterns than symbols) */
least = (left << 1) - syms;
if (least < 0)
least = 0;
/* we can use at most this many bit patterns, lest there not be enough
available for the remaining symbols at the maximum length (if there were
no limit to the code length, this would become: most = left - 1) */
most = (((code_t)left << (max - len)) - syms) /
(((code_t)1 << (max - len)) - 1);
/* count all possible codes from this juncture and add them up */
sum = 0;
for (use = least; use <= most; use++) {
got = count(syms - use, len + 1, (left - use) << 1);
sum += got;
if (got == -1 || sum < got) /* overflow */
return -1;
}
/* verify that all recursive calls are productive */
assert(sum != 0);
/* save the result and return it */
num[index] = sum;
return sum;
}
/* Return true if we've been here before, set to true if not. Set a bit in a
bit vector to indicate visiting this state. Each (syms,len,left) state
has a variable size bit vector indexed by (mem,rem). The bit vector is
lengthened if needed to allow setting the (mem,rem) bit. */
local int beenhere(int syms, int len, int left, int mem, int rem)
{
size_t index; /* index for this state's bit vector */
size_t offset; /* offset in this state's bit vector */
int bit; /* mask for this state's bit */
size_t length; /* length of the bit vector in bytes */
char *vector; /* new or enlarged bit vector */
/* point to vector for (syms,left,len), bit in vector for (mem,rem) */
index = INDEX(syms, left, len);
mem -= 1 << root;
offset = (mem >> 3) + rem;
offset = ((offset * (offset + 1)) >> 1) + rem;
bit = 1 << (mem & 7);
/* see if we've been here */
length = done[index].len;
if (offset < length && (done[index].vec[offset] & bit) != 0)
return 1; /* done this! */
/* we haven't been here before -- set the bit to show we have now */
/* see if we need to lengthen the vector in order to set the bit */
if (length <= offset) {
/* if we have one already, enlarge it, zero out the appended space */
if (length) {
do {
length <<= 1;
} while (length <= offset);
vector = realloc(done[index].vec, length);
if (vector != NULL)
memset(vector + done[index].len, 0, length - done[index].len);
}
/* otherwise we need to make a new vector and zero it out */
else {
length = 1 << (len - root);
while (length <= offset)
length <<= 1;
vector = calloc(length, sizeof(char));
}
/* in either case, bail if we can't get the memory */
if (vector == NULL) {
fputs("abort: unable to allocate enough memory\n", stderr);
cleanup();
exit(1);
}
/* install the new vector */
done[index].len = length;
done[index].vec = vector;
}
/* set the bit */
done[index].vec[offset] |= bit;
return 0;
}
/* Examine all possible codes from the given node (syms, len, left). Compute
the amount of memory required to build inflate's decoding tables, where the
number of code structures used so far is mem, and the number remaining in
the current sub-table is rem. Uses the globals max, code, root, large, and
done. */
local void examine(int syms, int len, int left, int mem, int rem)
{
int least; /* least number of syms to use at this juncture */
int most; /* most number of syms to use at this juncture */
int use; /* number of bit patterns to use in next call */
/* see if we have a complete code */
if (syms == left) {
/* set the last code entry */
code[len] = left;
/* complete computation of memory used by this code */
while (rem < left) {
left -= rem;
rem = 1 << (len - root);
mem += rem;
}
assert(rem == left);
/* if this is a new maximum, show the entries used and the sub-code */
if (mem > large) {
large = mem;
printf("max %d: ", mem);
for (use = root + 1; use <= max; use++)
if (code[use])
printf("%d[%d] ", code[use], use);
putchar('\n');
fflush(stdout);
}
/* remove entries as we drop back down in the recursion */
code[len] = 0;
return;
}
/* prune the tree if we can */
if (beenhere(syms, len, left, mem, rem))
return;
/* we need to use at least this many bit patterns so that the code won't be
incomplete at the next length (more bit patterns than symbols) */
least = (left << 1) - syms;
if (least < 0)
least = 0;
/* we can use at most this many bit patterns, lest there not be enough
available for the remaining symbols at the maximum length (if there were
no limit to the code length, this would become: most = left - 1) */
most = (((code_t)left << (max - len)) - syms) /
(((code_t)1 << (max - len)) - 1);
/* occupy least table spaces, creating new sub-tables as needed */
use = least;
while (rem < use) {
use -= rem;
rem = 1 << (len - root);
mem += rem;
}
rem -= use;
/* examine codes from here, updating table space as we go */
for (use = least; use <= most; use++) {
code[len] = use;
examine(syms - use, len + 1, (left - use) << 1,
mem + (rem ? 1 << (len - root) : 0), rem << 1);
if (rem == 0) {
rem = 1 << (len - root);
mem += rem;
}
rem--;
}
/* remove entries as we drop back down in the recursion */
code[len] = 0;
}
/* Look at all sub-codes starting with root + 1 bits. Look at only the valid
intermediate code states (syms, left, len). For each completed code,
calculate the amount of memory required by inflate to build the decoding
tables. Find the maximum amount of memory required and show the code that
requires that maximum. Uses the globals max, root, and num. */
local void enough(int syms)
{
int n; /* number of remaing symbols for this node */
int left; /* number of unused bit patterns at this length */
size_t index; /* index of this case in *num */
/* clear code */
for (n = 0; n <= max; n++)
code[n] = 0;
/* look at all (root + 1) bit and longer codes */
large = 1 << root; /* base table */
if (root < max) /* otherwise, there's only a base table */
for (n = 3; n <= syms; n++)
for (left = 2; left < n; left += 2)
{
/* look at all reachable (root + 1) bit nodes, and the
resulting codes (complete at root + 2 or more) */
index = INDEX(n, left, root + 1);
if (root + 1 < max && num[index]) /* reachable node */
examine(n, root + 1, left, 1 << root, 0);
/* also look at root bit codes with completions at root + 1
bits (not saved in num, since complete), just in case */
if (num[index - 1] && n <= left << 1)
examine((n - left) << 1, root + 1, (n - left) << 1,
1 << root, 0);
}
/* done */
printf("done: maximum of %d table entries\n", large);
}
/*
Examine and show the total number of possible Huffman codes for a given
maximum number of symbols, initial root table size, and maximum code length
in bits -- those are the command arguments in that order. The default
values are 286, 9, and 15 respectively, for the deflate literal/length code.
The possible codes are counted for each number of coded symbols from two to
the maximum. The counts for each of those and the total number of codes are
shown. The maximum number of inflate table entires is then calculated
across all possible codes. Each new maximum number of table entries and the
associated sub-code (starting at root + 1 == 10 bits) is shown.
To count and examine Huffman codes that are not length-limited, provide a
maximum length equal to the number of symbols minus one.
For the deflate literal/length code, use "enough". For the deflate distance
code, use "enough 30 6".
This uses the %llu printf format to print big_t numbers, which assumes that
big_t is an unsigned long long. If the big_t type is changed (for example
to a multiple precision type), the method of printing will also need to be
updated.
*/
int main(int argc, char **argv)
{
int syms; /* total number of symbols to code */
int n; /* number of symbols to code for this run */
big_t got; /* return value of count() */
big_t sum; /* accumulated number of codes over n */
/* set up globals for cleanup() */
code = NULL;
num = NULL;
done = NULL;
/* get arguments -- default to the deflate literal/length code */
syms = 286;
root = 9;
max = 15;
if (argc > 1) {
syms = atoi(argv[1]);
if (argc > 2) {
root = atoi(argv[2]);
if (argc > 3)
max = atoi(argv[3]);
}
}
if (argc > 4 || syms < 2 || root < 1 || max < 1) {
fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
stderr);
return 1;
}
/* if not restricting the code length, the longest is syms - 1 */
if (max > syms - 1)
max = syms - 1;
/* determine the number of bits in a code_t */
n = 0;
while (((code_t)1 << n) != 0)
n++;
/* make sure that the calculation of most will not overflow */
if (max > n || syms - 2 >= (((code_t)0 - 1) >> (max - 1))) {
fputs("abort: code length too long for internal types\n", stderr);
return 1;
}
/* reject impossible code requests */
if (syms - 1 > ((code_t)1 << max) - 1) {
fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
syms, max);
return 1;
}
/* allocate code vector */
code = calloc(max + 1, sizeof(int));
if (code == NULL) {
fputs("abort: unable to allocate enough memory\n", stderr);
return 1;
}
/* determine size of saved results array, checking for overflows,
allocate and clear the array (set all to zero with calloc()) */
if (syms == 2) /* iff max == 1 */
num = NULL; /* won't be saving any results */
else {
size = syms >> 1;
if (size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) ||
(size *= n, size > ((size_t)0 - 1) / (n = max - 1)) ||
(size *= n, size > ((size_t)0 - 1) / sizeof(big_t)) ||
(num = calloc(size, sizeof(big_t))) == NULL) {
fputs("abort: unable to allocate enough memory\n", stderr);
cleanup();
return 1;
}
}
/* count possible codes for all numbers of symbols, add up counts */
sum = 0;
for (n = 2; n <= syms; n++) {
got = count(n, 1, 2);
sum += got;
if (got == -1 || sum < got) { /* overflow */
fputs("abort: can't count that high!\n", stderr);
cleanup();
return 1;
}
printf("%llu %d-codes\n", got, n);
}
printf("%llu total codes for 2 to %d symbols", sum, syms);
if (max < syms - 1)
printf(" (%d-bit length limit)\n", max);
else
puts(" (no length limit)");
/* allocate and clear done array for beenhere() */
if (syms == 2)
done = NULL;
else if (size > ((size_t)0 - 1) / sizeof(struct tab) ||
(done = calloc(size, sizeof(struct tab))) == NULL) {
fputs("abort: unable to allocate enough memory\n", stderr);
cleanup();
return 1;
}
/* find and show maximum inflate table usage */
if (root > max) /* reduce root to max length */
root = max;
if (syms < ((code_t)1 << (root + 1)))
enough(syms);
else
puts("cannot handle minimum code lengths > root");
/* done */
cleanup();
return 0;
}

View File

@@ -1,7 +1,7 @@
/* gun.c -- simple gunzip to give an example of the use of inflateBack() /* gun.c -- simple gunzip to give an example of the use of inflateBack()
* Copyright (C) 2003, 2005 Mark Adler * Copyright (C) 2003, 2005, 2008, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
Version 1.3 12 June 2005 Mark Adler */ Version 1.6 17 January 2010 Mark Adler */
/* Version history: /* Version history:
1.0 16 Feb 2003 First version for testing of inflateBack() 1.0 16 Feb 2003 First version for testing of inflateBack()
@@ -15,6 +15,9 @@
1.2 20 Mar 2005 Add Unix compress (LZW) decompression 1.2 20 Mar 2005 Add Unix compress (LZW) decompression
Copy file attributes from input file to output file Copy file attributes from input file to output file
1.3 12 Jun 2005 Add casts for error messages [Oberhumer] 1.3 12 Jun 2005 Add casts for error messages [Oberhumer]
1.4 8 Dec 2006 LZW decompression speed improvements
1.5 9 Feb 2008 Avoid warning in latest version of gcc
1.6 17 Jan 2010 Avoid signed/unsigned comparison warnings
*/ */
/* /*
@@ -197,14 +200,14 @@ local int lunpipe(unsigned have, unsigned char *next, struct ind *indp,
int outfile, z_stream *strm) int outfile, z_stream *strm)
{ {
int last; /* last byte read by NEXT(), or -1 if EOF */ int last; /* last byte read by NEXT(), or -1 if EOF */
int chunk; /* bytes left in current chunk */ unsigned chunk; /* bytes left in current chunk */
int left; /* bits left in rem */ int left; /* bits left in rem */
unsigned rem; /* unused bits from input */ unsigned rem; /* unused bits from input */
int bits; /* current bits per code */ int bits; /* current bits per code */
unsigned code; /* code, table traversal index */ unsigned code; /* code, table traversal index */
unsigned mask; /* mask for current bits codes */ unsigned mask; /* mask for current bits codes */
int max; /* maximum bits per code for this stream */ int max; /* maximum bits per code for this stream */
int flags; /* compress flags, then block compress flag */ unsigned flags; /* compress flags, then block compress flag */
unsigned end; /* last valid entry in prefix/suffix tables */ unsigned end; /* last valid entry in prefix/suffix tables */
unsigned temp; /* current code */ unsigned temp; /* current code */
unsigned prev; /* previous code */ unsigned prev; /* previous code */
@@ -212,6 +215,7 @@ local int lunpipe(unsigned have, unsigned char *next, struct ind *indp,
unsigned stack; /* next position for reversed string */ unsigned stack; /* next position for reversed string */
unsigned outcnt; /* bytes in output buffer */ unsigned outcnt; /* bytes in output buffer */
struct outd outd; /* output structure */ struct outd outd; /* output structure */
unsigned char *p;
/* set up output */ /* set up output */
outd.outfile = outfile; outd.outfile = outfile;
@@ -322,10 +326,12 @@ local int lunpipe(unsigned have, unsigned char *next, struct ind *indp,
} }
/* walk through linked list to generate output in reverse order */ /* walk through linked list to generate output in reverse order */
p = match + stack;
while (code >= 256) { while (code >= 256) {
match[stack++] = suffix[code]; *p++ = suffix[code];
code = prefix[code]; code = prefix[code];
} }
stack = p - match;
match[stack++] = (unsigned char)code; match[stack++] = (unsigned char)code;
final = code; final = code;
@@ -349,9 +355,11 @@ local int lunpipe(unsigned have, unsigned char *next, struct ind *indp,
} }
outcnt = 0; outcnt = 0;
} }
p = match + stack;
do { do {
outbuf[outcnt++] = match[--stack]; outbuf[outcnt++] = *--p;
} while (stack); } while (p > match);
stack = 0;
/* loop for next code with final and prev as the last match, rem and /* loop for next code with final and prev as the last match, rem and
left provide the first 0..7 bits of the next code, end is the last left provide the first 0..7 bits of the next code, end is the last
@@ -375,7 +383,7 @@ local int gunpipe(z_stream *strm, int infile, int outfile)
{ {
int ret, first, last; int ret, first, last;
unsigned have, flags, len; unsigned have, flags, len;
unsigned char *next; unsigned char *next = NULL;
struct ind ind, *indp; struct ind ind, *indp;
struct outd outd; struct outd outd;
@@ -471,10 +479,10 @@ local int gunpipe(z_stream *strm, int infile, int outfile)
/* check trailer */ /* check trailer */
ret = Z_BUF_ERROR; ret = Z_BUF_ERROR;
if (NEXT() != (outd.crc & 0xff) || if (NEXT() != (int)(outd.crc & 0xff) ||
NEXT() != ((outd.crc >> 8) & 0xff) || NEXT() != (int)((outd.crc >> 8) & 0xff) ||
NEXT() != ((outd.crc >> 16) & 0xff) || NEXT() != (int)((outd.crc >> 16) & 0xff) ||
NEXT() != ((outd.crc >> 24) & 0xff)) { NEXT() != (int)((outd.crc >> 24) & 0xff)) {
/* crc error */ /* crc error */
if (last != -1) { if (last != -1) {
strm->msg = (char *)"incorrect data check"; strm->msg = (char *)"incorrect data check";
@@ -482,10 +490,10 @@ local int gunpipe(z_stream *strm, int infile, int outfile)
} }
break; break;
} }
if (NEXT() != (outd.total & 0xff) || if (NEXT() != (int)(outd.total & 0xff) ||
NEXT() != ((outd.total >> 8) & 0xff) || NEXT() != (int)((outd.total >> 8) & 0xff) ||
NEXT() != ((outd.total >> 16) & 0xff) || NEXT() != (int)((outd.total >> 16) & 0xff) ||
NEXT() != ((outd.total >> 24) & 0xff)) { NEXT() != (int)((outd.total >> 24) & 0xff)) {
/* length error */ /* length error */
if (last != -1) { if (last != -1) {
strm->msg = (char *)"incorrect length check"; strm->msg = (char *)"incorrect length check";
@@ -642,8 +650,8 @@ int main(int argc, char **argv)
argv++; argv++;
test = 0; test = 0;
if (argc && strcmp(*argv, "-h") == 0) { if (argc && strcmp(*argv, "-h") == 0) {
fprintf(stderr, "gun 1.3 (12 Jun 2005)\n"); fprintf(stderr, "gun 1.6 (17 Jan 2010)\n");
fprintf(stderr, "Copyright (c) 2005 Mark Adler\n"); fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n");
fprintf(stderr, "usage: gun [-t] [file1.gz [file2.Z ...]]\n"); fprintf(stderr, "usage: gun [-t] [file1.gz [file2.Z ...]]\n");
return 0; return 0;
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
/* gzlog.h /* gzlog.h
Copyright (C) 2004 Mark Adler, all rights reserved Copyright (C) 2004, 2008 Mark Adler, all rights reserved
version 1.0, 26 Nov 2004 version 2.0, 25 Apr 2008
This software is provided 'as-is', without any express or implied This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages warranty. In no event will the author be held liable for any damages
@@ -21,38 +21,69 @@
Mark Adler madler@alumni.caltech.edu Mark Adler madler@alumni.caltech.edu
*/ */
/* Version History:
1.0 26 Nov 2004 First version
2.0 25 Apr 2008 Complete redesign for recovery of interrupted operations
Interface changed slightly in that now path is a prefix
Compression now occurs as needed during gzlog_write()
gzlog_write() now always leaves the log file as valid gzip
*/
/* /*
The gzlog object allows writing short messages to a gzipped log file, The gzlog object allows writing short messages to a gzipped log file,
opening the log file locked for small bursts, and then closing it. The log opening the log file locked for small bursts, and then closing it. The log
object works by appending stored data to the gzip file until 1 MB has been object works by appending stored (uncompressed) data to the gzip file until
accumulated. At that time, the stored data is compressed, and replaces the 1 MB has been accumulated. At that time, the stored data is compressed, and
uncompressed data in the file. The log file is truncated to its new size at replaces the uncompressed data in the file. The log file is truncated to
that time. After closing, the log file is always valid gzip file that can its new size at that time. After each write operation, the log file is a
decompressed to recover what was written. valid gzip file that can decompressed to recover what was written.
A gzip header "extra" field contains two file offsets for appending. The The gzlog operations can be interupted at any point due to an application or
first points to just after the last compressed data. The second points to system crash, and the log file will be recovered the next time the log is
the last stored block in the deflate stream, which is empty. All of the opened with gzlog_open().
data between those pointers is uncompressed.
*/ */
#ifndef GZLOG_H
#define GZLOG_H
/* gzlog object type */
typedef void gzlog;
/* Open a gzlog object, creating the log file if it does not exist. Return /* Open a gzlog object, creating the log file if it does not exist. Return
NULL on error. Note that gzlog_open() could take a long time to return if NULL on error. Note that gzlog_open() could take a while to complete if it
there is difficulty in locking the file. */ has to wait to verify that a lock is stale (possibly for five minutes), or
void *gzlog_open(char *path); if there is significant contention with other instantiations of this object
when locking the resource. path is the prefix of the file names created by
this object. If path is "foo", then the log file will be "foo.gz", and
other auxiliary files will be created and destroyed during the process:
"foo.dict" for a compression dictionary, "foo.temp" for a temporary (next)
dictionary, "foo.add" for data being added or compressed, "foo.lock" for the
lock file, and "foo.repairs" to log recovery operations performed due to
interrupted gzlog operations. A gzlog_open() followed by a gzlog_close()
will recover a previously interrupted operation, if any. */
gzlog *gzlog_open(char *path);
/* Write to a gzlog object. Return non-zero on error. This function will /* Write to a gzlog object. Return zero on success, -1 if there is a file i/o
simply write data to the file uncompressed. Compression of the data error on any of the gzlog files (this should not happen if gzlog_open()
will not occur until gzlog_close() is called. It is expected that succeeded, unless the device has run out of space or leftover auxiliary
gzlog_write() is used for a short message, and then gzlog_close() is files have permissions or ownership that prevent their use), -2 if there is
called. If a large amount of data is to be written, then the application a memory allocation failure, or -3 if the log argument is invalid (e.g. if
should write no more than 1 MB at a time with gzlog_write() before it was not created by gzlog_open()). This function will write data to the
calling gzlog_close() and then gzlog_open() again. */ file uncompressed, until 1 MB has been accumulated, at which time that data
int gzlog_write(void *log, char *data, size_t len); will be compressed. The log file will be a valid gzip file upon successful
return. */
int gzlog_write(gzlog *log, void *data, size_t len);
/* Close a gzlog object. Return non-zero on error. The log file is locked /* Force compression of any uncompressed data in the log. This should be used
until this function is called. This function will compress stored data sparingly, if at all. The main application would be when a log file will
at the end of the gzip file if at least 1 MB has been accumulated. Note not be appended to again. If this is used to compress frequently while
that the file will not be a valid gzip file until this function completes. appending, it will both significantly increase the execution time and
*/ reduce the compression ratio. The return codes are the same as for
int gzlog_close(void *log); gzlog_write(). */
int gzlog_compress(gzlog *log);
/* Close a gzlog object. Return zero on success, -3 if the log argument is
invalid. The log object is freed, and so cannot be referenced again. */
int gzlog_close(gzlog *log);
#endif

29
gzclose.c Normal file
View File

@@ -0,0 +1,29 @@
/* gzclose.c -- zlib gzclose() function
* Copyright (C) 2004, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifndef OLD_GZIO
#include "gzguts.h"
/* gzclose() is in a separate file so that it is linked in only if it is used.
That way the other gzclose functions can be used instead to avoid linking in
unneeded compression or decompression routines. */
int ZEXPORT gzclose(file)
gzFile file;
{
#ifndef NO_GZCOMPRESS
gz_statep state;
if (file == NULL)
return Z_STREAM_ERROR;
state = (gz_statep)file;
return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);
#else
return gzclose_r(file);
#endif
}
#endif /* !OLD_GZIO */

132
gzguts.h Normal file
View File

@@ -0,0 +1,132 @@
/* gzguts.h -- zlib internal header definitions for gz* operations
* Copyright (C) 2004, 2005, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifdef _LARGEFILE64_SOURCE
# ifndef _LARGEFILE_SOURCE
# define _LARGEFILE_SOURCE
# endif
# ifdef _FILE_OFFSET_BITS
# undef _FILE_OFFSET_BITS
# endif
#endif
#define ZLIB_INTERNAL
#include <stdio.h>
#include "zlib.h"
#ifdef STDC
# include <string.h>
# include <stdlib.h>
# include <limits.h>
#endif
#include <fcntl.h>
#ifdef NO_DEFLATE /* for compatibility with old definition */
# define NO_GZCOMPRESS
#endif
#ifdef WIN32
# include <io.h>
# define vsnprintf _vsnprintf
#endif
#ifndef local
# define local static
#endif
/* compile with -Dlocal if your debugger can't find static symbols */
/* gz* functions always use library allocation functions */
#ifndef STDC
extern voidp malloc OF((uInt size));
extern void free OF((voidpf ptr));
#endif
/* get errno and strerror definition */
#if defined UNDER_CE && defined NO_ERRNO_H
# include <windows.h>
# define zstrerror() gz_strwinerror((DWORD)GetLastError())
#else
# ifdef STDC
# include <errno.h>
# define zstrerror() strerror(errno)
# else
# define zstrerror() "stdio error (consult errno)"
# endif
#endif
/* MVS fdopen() */
#ifdef __MVS__
#pragma map (fdopen , "\174\174FDOPEN")
FILE *fdopen(int, const char *);
#endif
#ifdef _LARGEFILE64_SOURCE
# define z_off64_t off64_t
#else
# define z_off64_t z_off_t
#endif
/* default i/o buffer size -- double this for output when reading */
#define GZBUFSIZE 8192
/* gzip modes, also provide a little integrity check on the passed structure */
#define GZ_NONE 0
#define GZ_READ 7247
#define GZ_WRITE 31153
#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */
/* values for gz_state how */
#define LOOK 0 /* look for a gzip header */
#define COPY 1 /* copy input directly */
#define GZIP 2 /* decompress a gzip stream */
/* internal gzip file state data structure */
typedef struct {
/* used for both reading and writing */
int mode; /* see gzip modes above */
int fd; /* file descriptor */
char *path; /* path or fd for error messages */
z_off64_t pos; /* current position in uncompressed data */
unsigned size; /* buffer size, zero if not allocated yet */
unsigned want; /* requested buffer size, default is GZBUFSIZE */
unsigned char *in; /* input buffer */
unsigned char *out; /* output buffer (double-sized when reading) */
unsigned char *next; /* next output data to deliver or write */
/* just for reading */
unsigned have; /* amount of output data unused at next */
int eof; /* true if end of input file reached */
z_off64_t start; /* where the gzip data started, for rewinding */
z_off64_t raw; /* where the raw data started, for seeking */
int how; /* 0: get header, 1: copy, 2: decompress */
int direct; /* true if last read direct, false if gzip */
/* just for writing */
int level; /* compression level */
int strategy; /* compression strategy */
/* seek request */
z_off64_t skip; /* amount to skip (already rewound if backwards) */
int seek; /* true if seek request pending */
/* error information */
int err; /* error code */
char *msg; /* error message */
/* zlib inflate or deflate stream */
z_stream strm; /* stream structure in-place (not a pointer) */
} gz_state;
typedef gz_state FAR *gz_statep;
/* shared functions */
ZEXTERN void ZEXPORT gz_error OF((gz_statep, int, const char *));
#if defined UNDER_CE && defined NO_ERRNO_H
ZEXTERN char ZEXPORT *gz_strwinerror OF((DWORD error));
#endif
/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
value -- needed when comparing unsigned to z_off64_t, which is signed
(possible z_off64_t types off_t, off64_t, and long are all signed) */
#ifdef INT_MAX
# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)
#else
ZEXTERN unsigned ZEXPORT gz_intmax OF((void));
# define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
#endif

267
gzio.c
View File

@@ -1,5 +1,5 @@
/* gzio.c -- IO on .gz files /* gzio.c -- IO on .gz files
* Copyright (C) 1995-2006 Jean-loup Gailly. * Copyright (C) 1995-2010 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
* *
* Compile this file with -DNO_GZCOMPRESS to avoid the compression code. * Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
@@ -7,6 +7,17 @@
/* @(#) $Id$ */ /* @(#) $Id$ */
#ifdef OLD_GZIO
#ifdef _LARGEFILE64_SOURCE
# ifndef _LARGEFILE_SOURCE
# define _LARGEFILE_SOURCE
# endif
# ifdef _FILE_OFFSET_BITS
# undef _FILE_OFFSET_BITS
# endif
#endif
#include "zutil.h" #include "zutil.h"
#include <stdio.h> #include <stdio.h>
@@ -29,8 +40,62 @@ struct internal_state {int dummy;}; /* for buggy compilers */
# define Z_PRINTF_BUFSIZE 4096 # define Z_PRINTF_BUFSIZE 4096
#endif #endif
#if defined UNDER_CE && defined NO_ERRNO_H
# include <windows.h>
/* Map the Windows error number in ERROR to a locale-dependent error
message string and return a pointer to it. Typically, the values
for ERROR come from GetLastError.
The string pointed to shall not be modified by the application,
but may be overwritten by a subsequent call to strwinerror
The strwinerror function does not change the current setting
of GetLastError. */
local char *strwinerror (error)
DWORD error;
{
static char buf[1024];
wchar_t *msgbuf;
DWORD lasterr = GetLastError();
DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
error,
0, /* Default language */
(LPVOID)&msgbuf,
0,
NULL);
if (chars != 0) {
/* If there is an \r\n appended, zap it. */
if (chars >= 2
&& msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
chars -= 2;
msgbuf[chars] = 0;
}
if (chars > sizeof (buf) - 1) {
chars = sizeof (buf) - 1;
msgbuf[chars] = 0;
}
wcstombs(buf, msgbuf, chars + 1);
LocalFree(msgbuf);
}
else {
sprintf(buf, "unknown win32 error (%ld)", error);
}
SetLastError(lasterr);
return buf;
}
#endif /* UNDER_CE && NO_ERRNO_H */
#ifdef __MVS__ #ifdef __MVS__
# pragma map (fdopen , "\174\174FDOPEN") #pragma map (fdopen , "\174\174FDOPEN")
FILE *fdopen(int, const char *); FILE *fdopen(int, const char *);
#endif #endif
@@ -39,6 +104,14 @@ extern voidp malloc OF((uInt size));
extern void free OF((voidpf ptr)); extern void free OF((voidpf ptr));
#endif #endif
#ifdef NO_FSEEKO
# define FSEEK fseek
# define FTELL ftell
#else
# define FSEEK fseeko
# define FTELL ftello
#endif
#define ALLOC(size) malloc(size) #define ALLOC(size) malloc(size)
#define TRYFREE(p) {if (p) free(p);} #define TRYFREE(p) {if (p) free(p);}
@@ -54,31 +127,32 @@ static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
typedef struct gz_stream { typedef struct gz_stream {
z_stream stream; z_stream stream;
int z_err; /* error code for last stream operation */ int z_err; /* error code for last stream operation */
int z_eof; /* set if end of input file */ int z_eof; /* set if end of input file */
FILE *file; /* .gz file */ FILE *file; /* .gz file */
Byte *inbuf; /* input buffer */ Byte *inbuf; /* input buffer */
Byte *outbuf; /* output buffer */ Byte *outbuf; /* output buffer */
uLong crc; /* crc32 of uncompressed data */ uLong crc; /* crc32 of uncompressed data */
char *msg; /* error message */ char *msg; /* error message */
char *path; /* path name for debugging only */ char *path; /* path name for debugging only */
int transparent; /* 1 if input file is not a .gz file */ int transparent; /* 1 if input file is not a .gz file */
char mode; /* 'w' or 'r' */ char mode; /* 'w' or 'r' */
z_off_t start; /* start of compressed data in file (header skipped) */ z_off64_t start; /* start of compressed data in file */
z_off_t in; /* bytes into deflate or inflate */ z_off64_t in; /* bytes into deflate or inflate */
z_off_t out; /* bytes out of deflate or inflate */ z_off64_t out; /* bytes out of deflate or inflate */
int back; /* one character push-back */ int back; /* one character push-back */
int last; /* true if push-back is last character */ int last; /* true if push-back is last character */
} gz_stream; } gz_stream;
local gzFile gz_open OF((const char *path, const char *mode, int fd)); local gzFile gz_open OF((const char *, const char *, int, int));
local int do_flush OF((gzFile file, int flush)); local z_off64_t gz_seek OF((gzFile, z_off64_t, int, int));
local int get_byte OF((gz_stream *s)); local int do_flush OF((gzFile, int));
local void check_header OF((gz_stream *s)); local int get_byte OF((gz_stream *));
local int destroy OF((gz_stream *s)); local void check_header OF((gz_stream *));
local void putLong OF((FILE *file, uLong x)); local int destroy OF((gz_stream *));
local uLong getLong OF((gz_stream *s)); local void putLong OF((FILE *, uLong));
local uLong getLong OF((gz_stream *));
/* =========================================================================== /* ===========================================================================
Opens a gzip (.gz) file for reading or writing. The mode parameter Opens a gzip (.gz) file for reading or writing. The mode parameter
@@ -89,10 +163,11 @@ local uLong getLong OF((gz_stream *s));
can be checked to distinguish the two cases (if errno is zero, the can be checked to distinguish the two cases (if errno is zero, the
zlib error is Z_MEM_ERROR). zlib error is Z_MEM_ERROR).
*/ */
local gzFile gz_open (path, mode, fd) local gzFile gz_open (path, mode, fd, use64)
const char *path; const char *path;
const char *mode; const char *mode;
int fd; int fd;
int use64;
{ {
int err; int err;
int level = Z_DEFAULT_COMPRESSION; /* compression level */ int level = Z_DEFAULT_COMPRESSION; /* compression level */
@@ -113,6 +188,7 @@ local gzFile gz_open (path, mode, fd)
s->stream.next_in = s->inbuf = Z_NULL; s->stream.next_in = s->inbuf = Z_NULL;
s->stream.next_out = s->outbuf = Z_NULL; s->stream.next_out = s->outbuf = Z_NULL;
s->stream.avail_in = s->stream.avail_out = 0; s->stream.avail_in = s->stream.avail_out = 0;
s->stream.state = Z_NULL;
s->file = NULL; s->file = NULL;
s->z_err = Z_OK; s->z_err = Z_OK;
s->z_eof = 0; s->z_eof = 0;
@@ -164,20 +240,17 @@ local gzFile gz_open (path, mode, fd)
s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
err = inflateInit2(&(s->stream), -MAX_WBITS); err = inflateInit2(&(s->stream), -MAX_WBITS);
/* windowBits is passed < 0 to tell that there is no zlib header. /* 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) { if (err != Z_OK || s->inbuf == Z_NULL) {
return destroy(s), (gzFile)Z_NULL; return destroy(s), (gzFile)Z_NULL;
} }
} }
s->stream.avail_out = Z_BUFSIZE; s->stream.avail_out = Z_BUFSIZE;
errno = 0; zseterrno(0);
s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); s->file = fd == -1 ?
(use64 ? F_OPEN64(path, fmode) : F_OPEN(path, fmode)) :
(FILE*)fdopen(fd, fmode);
if (s->file == NULL) { if (s->file == NULL) {
return destroy(s), (gzFile)Z_NULL; return destroy(s), (gzFile)Z_NULL;
@@ -198,7 +271,7 @@ local gzFile gz_open (path, mode, fd)
*/ */
} else { } else {
check_header(s); /* skip the .gz header */ check_header(s); /* skip the .gz header */
s->start = ftell(s->file) - s->stream.avail_in; s->start = FTELL(s->file) - s->stream.avail_in;
} }
return (gzFile)s; return (gzFile)s;
@@ -211,7 +284,17 @@ gzFile ZEXPORT gzopen (path, mode)
const char *path; const char *path;
const char *mode; const char *mode;
{ {
return gz_open (path, mode, -1); return gz_open (path, mode, -1, 0);
}
/* ===========================================================================
Opens a gzip (.gz) file for reading or writing for 64-bit offsets
*/
gzFile ZEXPORT gzopen64 (path, mode)
const char *path;
const char *mode;
{
return gz_open (path, mode, -1, 1);
} }
/* =========================================================================== /* ===========================================================================
@@ -224,10 +307,10 @@ gzFile ZEXPORT gzdopen (fd, mode)
{ {
char name[46]; /* allow for up to 128-bit integers */ char name[46]; /* allow for up to 128-bit integers */
if (fd < 0) return (gzFile)Z_NULL; if (fd == -1) return (gzFile)Z_NULL;
sprintf(name, "<fd:%d>", fd); /* for debugging */ sprintf(name, "<fd:%d>", fd); /* for debugging */
return gz_open (name, mode, fd); return gz_open (name, mode, fd, 0);
} }
/* =========================================================================== /* ===========================================================================
@@ -265,7 +348,7 @@ local int get_byte(s)
{ {
if (s->z_eof) return EOF; if (s->z_eof) return EOF;
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
errno = 0; zseterrno(0);
s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
s->z_eof = 1; s->z_eof = 1;
@@ -301,7 +384,7 @@ local void check_header(s)
len = s->stream.avail_in; len = s->stream.avail_in;
if (len < 2) { if (len < 2) {
if (len) s->inbuf[0] = s->stream.next_in[0]; if (len) s->inbuf[0] = s->stream.next_in[0];
errno = 0; zseterrno(0);
len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
if (len == 0) s->z_eof = 1; if (len == 0) s->z_eof = 1;
if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
@@ -377,7 +460,7 @@ local int destroy (s)
} }
if (s->file != NULL && fclose(s->file)) { if (s->file != NULL && fclose(s->file)) {
#ifdef ESPIPE #ifdef ESPIPE
if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ if (zerrno() != ESPIPE) /* fclose is broken for pipes in HP/UX */
#endif #endif
err = Z_ERRNO; err = Z_ERRNO;
} }
@@ -446,12 +529,12 @@ int ZEXPORT gzread (file, buf, len)
len -= s->stream.avail_out; len -= s->stream.avail_out;
s->in += len; s->in += len;
s->out += len; s->out += len;
if (len == 0) s->z_eof = 1; if (len == 0 && feof(s->file)) s->z_eof = 1;
return (int)len; return (int)len;
} }
if (s->stream.avail_in == 0 && !s->z_eof) { if (s->stream.avail_in == 0 && !s->z_eof) {
errno = 0; zseterrno(0);
s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
s->z_eof = 1; s->z_eof = 1;
@@ -767,10 +850,11 @@ int ZEXPORT gzflush (file, flush)
SEEK_END is not implemented, returns error. SEEK_END is not implemented, returns error.
In this version of the library, gzseek can be extremely slow. In this version of the library, gzseek can be extremely slow.
*/ */
z_off_t ZEXPORT gzseek (file, offset, whence) local z_off64_t gz_seek (file, offset, whence, use64)
gzFile file; gzFile file;
z_off_t offset; z_off64_t offset;
int whence; int whence;
int use64;
{ {
gz_stream *s = (gz_stream*)file; gz_stream *s = (gz_stream*)file;
@@ -819,7 +903,13 @@ z_off_t ZEXPORT gzseek (file, offset, whence)
s->back = EOF; s->back = EOF;
s->stream.avail_in = 0; s->stream.avail_in = 0;
s->stream.next_in = s->inbuf; s->stream.next_in = s->inbuf;
if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; #ifdef _LARGEFILE64_SOURCE
if ((use64 ? fseeko64(s->file, offset, SEEK_SET) :
FSEEK(s->file, offset, SEEK_SET)) < 0)
return -1L;
#else
if (FSEEK(s->file, offset, SEEK_SET) < 0) return -1L;
#endif
s->in = s->out = offset; s->in = s->out = offset;
return offset; return offset;
@@ -854,6 +944,29 @@ z_off_t ZEXPORT gzseek (file, offset, whence)
return s->out; return s->out;
} }
/* ===========================================================================
Define external functions gzseek() and gzseek64() using local gz_seek().
*/
z_off_t ZEXPORT gzseek (file, offset, whence)
gzFile file;
z_off_t offset;
int whence;
{
return (z_off_t)gz_seek(file, offset, whence, 0);
}
z_off64_t ZEXPORT gzseek64 (file, offset, whence)
gzFile file;
z_off64_t offset;
int whence;
{
#ifdef _LARGEFILE64_SOURCE
return gz_seek(file, offset, whence, 1);
#else
return gz_seek(file, offset, whence, 0);
#endif
}
/* =========================================================================== /* ===========================================================================
Rewinds input file. Rewinds input file.
*/ */
@@ -873,7 +986,7 @@ int ZEXPORT gzrewind (file)
if (!s->transparent) (void)inflateReset(&s->stream); if (!s->transparent) (void)inflateReset(&s->stream);
s->in = 0; s->in = 0;
s->out = 0; s->out = 0;
return fseek(s->file, s->start, SEEK_SET); return FSEEK(s->file, s->start, SEEK_SET);
} }
/* =========================================================================== /* ===========================================================================
@@ -887,6 +1000,15 @@ z_off_t ZEXPORT gztell (file)
return gzseek(file, 0L, SEEK_CUR); return gzseek(file, 0L, SEEK_CUR);
} }
/* ===========================================================================
64-bit version
*/
z_off64_t ZEXPORT gztell64 (file)
gzFile file;
{
return gzseek64(file, 0L, SEEK_CUR);
}
/* =========================================================================== /* ===========================================================================
Returns 1 when EOF has previously been detected reading the given Returns 1 when EOF has previously been detected reading the given
input stream, otherwise zero. input stream, otherwise zero.
@@ -974,10 +1096,14 @@ int ZEXPORT gzclose (file)
return destroy((gz_stream*)file); return destroy((gz_stream*)file);
} }
#if defined(STDC) && !defined(_WIN32_WCE) #if defined UNDER_CE && defined NO_ERRNO_H
# define zstrerror(errnum) strerror(errnum) # define zstrerror(errnum) strwinerror((DWORD)errnum)
#else #else
# define zstrerror(errnum) "" # if defined (STDC)
# define zstrerror(errnum) strerror(errnum)
# else
# define zstrerror(errnum) ""
# endif
#endif #endif
/* =========================================================================== /* ===========================================================================
@@ -1001,7 +1127,7 @@ const char * ZEXPORT gzerror (file, errnum)
*errnum = s->z_err; *errnum = s->z_err;
if (*errnum == Z_OK) return (const char*)""; if (*errnum == Z_OK) return (const char*)"";
m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); m = (char*)(*errnum == Z_ERRNO ? zstrerror(zerrno()) : s->stream.msg);
if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
@@ -1027,3 +1153,44 @@ void ZEXPORT gzclearerr (file)
s->z_eof = 0; s->z_eof = 0;
clearerr(s->file); clearerr(s->file);
} }
/* new functions in gzlib, but only partially implemented here */
int ZEXPORT gzbuffer (file, size)
gzFile file;
unsigned size;
{
return -1;
}
z_off_t ZEXPORT gzoffset (file)
gzFile file;
{
return -1;
}
z_off64_t ZEXPORT gzoffset64 (file)
gzFile file;
{
return -1;
}
int ZEXPORT gzclose_r (file)
gzFile file;
{
return gzclose(file);
}
int ZEXPORT gzclose_w (file)
gzFile file;
{
return gzclose(file);
}
int gzio_old = 1;
#else /* !OLD_GZIO */
int gzio_old = 0;
#endif /* OLD_GZIO */

536
gzlib.c Normal file
View File

@@ -0,0 +1,536 @@
/* gzlib.c -- zlib functions common to reading and writing gzip files
* Copyright (C) 2004, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifndef OLD_GZIO
#include "gzguts.h"
#ifdef _LARGEFILE64_SOURCE
# define LSEEK lseek64
#else
# define LSEEK lseek
#endif
/* Local functions */
local void gz_reset OF((gz_statep));
local gzFile gz_open OF((const char *, int, const char *));
#if defined UNDER_CE && defined NO_ERRNO_H
/* Map the Windows error number in ERROR to a locale-dependent error message
string and return a pointer to it. Typically, the values for ERROR come
from GetLastError.
The string pointed to shall not be modified by the application, but may be
overwritten by a subsequent call to gz_strwinerror
The gz_strwinerror function does not change the current setting of
GetLastError. */
char ZEXPORT *gz_strwinerror (error)
DWORD error;
{
static char buf[1024];
wchar_t *msgbuf;
DWORD lasterr = GetLastError();
DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
error,
0, /* Default language */
(LPVOID)&msgbuf,
0,
NULL);
if (chars != 0) {
/* If there is an \r\n appended, zap it. */
if (chars >= 2
&& msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
chars -= 2;
msgbuf[chars] = 0;
}
if (chars > sizeof (buf) - 1) {
chars = sizeof (buf) - 1;
msgbuf[chars] = 0;
}
wcstombs(buf, msgbuf, chars + 1);
LocalFree(msgbuf);
}
else {
sprintf(buf, "unknown win32 error (%ld)", error);
}
SetLastError(lasterr);
return buf;
}
#endif /* UNDER_CE && NO_ERRNO_H */
/* Reset gzip file state */
local void gz_reset(state)
gz_statep state;
{
if (state->mode == GZ_READ) { /* for reading ... */
state->have = 0; /* no output data available */
state->eof = 0; /* not at end of file */
state->how = LOOK; /* look for gzip header */
state->direct = 1; /* default for empty file */
}
state->seek = 0; /* no seek request pending */
gz_error(state, Z_OK, NULL); /* clear error */
state->pos = 0; /* no uncompressed data yet */
state->strm.avail_in = 0; /* no input data yet */
}
/* Open a gzip file either by name or file descriptor. */
local gzFile gz_open(path, fd, mode)
const char *path;
int fd;
const char *mode;
{
gz_statep state;
/* allocate gzFile structure to return */
state = malloc(sizeof(gz_state));
if (state == NULL)
return NULL;
state->size = 0; /* no buffers allocated yet */
state->want = GZBUFSIZE; /* requested buffer size */
state->msg = NULL; /* no error message yet */
/* interpret mode */
state->mode = GZ_NONE;
state->level = Z_DEFAULT_COMPRESSION;
state->strategy = Z_DEFAULT_STRATEGY;
while (*mode) {
if (*mode >= '0' && *mode <= '9')
state->level = *mode - '0';
else
switch (*mode) {
case 'r':
state->mode = GZ_READ;
break;
#ifndef NO_GZCOMPRESS
case 'w':
state->mode = GZ_WRITE;
break;
case 'a':
state->mode = GZ_APPEND;
break;
#endif
case '+': /* can't read and write at the same time */
free(state);
return NULL;
case 'b': /* ignore -- will request binary anyway */
break;
case 'f':
state->strategy = Z_FILTERED;
break;
case 'h':
state->strategy = Z_HUFFMAN_ONLY;
break;
case 'R':
state->strategy = Z_RLE;
break;
case 'F':
state->strategy = Z_FIXED;
default: /* could consider as an error, but just ignore */
;
}
mode++;
}
/* must provide an "r", "w", or "a" */
if (state->mode == GZ_NONE) {
free(state);
return NULL;
}
/* open the file with the appropriate mode (or just use fd) */
state->fd = fd != -1 ? fd :
open(path,
#ifdef O_LARGEFILE
O_LARGEFILE |
#endif
#ifdef O_BINARY
O_BINARY |
#endif
(state->mode == GZ_READ ?
O_RDONLY :
(O_WRONLY | O_CREAT | (
state->mode == GZ_WRITE ?
O_TRUNC :
O_APPEND))),
0666);
if (state->fd == -1) {
free(state);
return NULL;
}
if (state->mode == GZ_APPEND)
state->mode = GZ_WRITE; /* simplify later checks */
/* save the path name for error messages */
state->path = malloc(strlen(path) + 1);
if (state->path == NULL) {
free(state);
return NULL;
}
strcpy(state->path, path);
/* save the current position for rewinding (only if reading) */
if (state->mode == GZ_READ) {
state->start = LSEEK(state->fd, 0, SEEK_CUR);
if (state->start == -1) state->start = 0;
}
/* initialize stream */
gz_reset(state);
/* return stream */
return (gzFile)state;
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen64(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzdopen(fd, mode)
int fd;
const char *mode;
{
char path[46]; /* identifier for error messages */
if (fd == -1)
return NULL;
#ifdef NO_snprintf
sprintf(path, "<fd:%d>", fd); /* big enough for 128-bit integers */
#else
snprintf(path, sizeof(path), "<fd:%d>", fd);
#endif
return gz_open(path, fd, mode);
}
/* -- see zlib.h -- */
int ZEXPORT gzbuffer(file, size)
gzFile file;
unsigned size;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* make sure we haven't already allocated memory */
if (state->size != 0)
return -1;
/* check and set requested size */
if (size == 0)
return -1;
state->want = size;
return 0;
}
/* -- see zlib.h -- */
int ZEXPORT gzrewind(file)
gzFile file;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ || state->err != Z_OK)
return -1;
/* back up and start over */
if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
return -1;
gz_reset(state);
return 0;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzseek64(file, offset, whence)
gzFile file;
z_off64_t offset;
int whence;
{
unsigned n;
z_off64_t ret;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* check that there's no error */
if (state->err != Z_OK)
return -1;
/* can only seek from start or relative to current position */
if (whence != SEEK_SET && whence != SEEK_CUR)
return -1;
/* normalize offset to a SEEK_CUR specification */
if (whence == SEEK_SET)
offset -= state->pos;
/* if within raw area while reading, just go there */
if (state->mode == GZ_READ && state->how == COPY &&
state->pos + offset >= state->raw) {
ret = LSEEK(state->fd, offset, SEEK_CUR);
if (ret == -1)
return -1;
state->have = 0;
state->eof = 0;
state->seek = 0;
gz_error(state, Z_OK, NULL);
state->strm.avail_in = 0;
state->pos += offset;
return state->pos;
}
/* calculate skip amount, rewinding if needed for back seek when reading */
if (offset < 0) {
if (state->mode != GZ_READ) /* writing -- can't go backwards */
return -1;
offset += state->pos;
if (offset < 0) /* before start of file! */
return -1;
if (gzrewind(file) == -1) /* rewind, then skip to offset */
return -1;
}
/* if reading, skip what's in output buffer (one less gzgetc() check) */
if (state->mode == GZ_READ) {
n = GT_OFF(state->have) || (z_off64_t)state->have > offset ?
(unsigned)offset : state->have;
state->have -= n;
state->next += n;
state->pos += n;
offset -= n;
}
/* request skip (if not zero) */
if (offset) {
state->seek = 1;
state->skip = offset;
}
return state->pos + offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzseek(file, offset, whence)
gzFile file;
z_off_t offset;
int whence;
{
z_off64_t ret;
ret = gzseek64(file, (z_off64_t)offset, whence);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gztell64(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* return position */
return state->pos + (state->seek ? state->skip : 0);
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gztell(file)
gzFile file;
{
z_off64_t ret;
ret = gztell64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzoffset64(file)
gzFile file;
{
z_off64_t offset;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* compute and return effective offset in file */
offset = LSEEK(state->fd, 0, SEEK_CUR);
if (offset == -1)
return -1;
if (state->mode == GZ_READ) /* reading */
offset -= state->strm.avail_in; /* don't count buffered input */
return offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzoffset(file)
gzFile file;
{
z_off64_t ret;
ret = gzoffset64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
int ZEXPORT gzeof(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return 0;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return 0;
/* return end-of-file state */
return state->mode == GZ_READ ? (state->eof && state->have == 0) : 0;
}
/* -- see zlib.h -- */
const char * ZEXPORT gzerror(file, errnum)
gzFile file;
int *errnum;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return NULL;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return NULL;
/* return error information */
*errnum = state->err;
return state->msg == NULL ? "" : state->msg;
}
/* -- see zlib.h -- */
void ZEXPORT gzclearerr(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return;
/* clear error and end-of-file */
if (state->mode == GZ_READ)
state->eof = 0;
gz_error(state, Z_OK, NULL);
}
/* Create an error message in allocated memory and set state->err and
state->msg accordingly. Free any previous error message already there. Do
not try to free or allocate space if the error is Z_MEM_ERROR (out of
memory). Simply save the error message as a static string. If there is an
allocation failure constructing the error message, then convert the error to
out of memory. */
void ZEXPORT gz_error(state, err, msg)
gz_statep state;
int err;
const char *msg;
{
/* free previously allocated message and clear */
if (state->msg != NULL) {
if (state->err != Z_MEM_ERROR)
free(state->msg);
state->msg = NULL;
}
/* set error code, and if no message, then done */
state->err = err;
if (msg == NULL)
return;
/* for an out of memory error, save as static string */
if (err == Z_MEM_ERROR) {
state->msg = (char *)msg;
return;
}
/* construct error message with path */
if ((state->msg = malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) {
state->err = Z_MEM_ERROR;
state->msg = (char *)"out of memory";
return;
}
strcpy(state->msg, state->path);
strcat(state->msg, ": ");
strcat(state->msg, msg);
return;
}
#ifndef INT_MAX
/* portably return maximum value for an int (when limits.h presumed not
available) -- we need to do this to cover cases where 2's complement not
used, since C standard permits 1's complement and sign-bit representations,
otherwise we could just use ((unsigned)-1) >> 1 */
unsigned ZEXPORT gz_intmax()
{
unsigned p, q;
p = 1;
do {
q = p;
p <<= 1;
p++;
} while (p > q);
return q >> 1;
}
#endif
#endif /* !OLD_GZIO */

659
gzread.c Normal file
View File

@@ -0,0 +1,659 @@
/* gzread.c -- zlib functions for reading gzip files
* Copyright (C) 2004, 2005, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifndef OLD_GZIO
#include "gzguts.h"
/* Local functions */
local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));
local int gz_avail OF((gz_statep));
local int gz_next4 OF((gz_statep, unsigned long *));
local int gz_head OF((gz_statep));
local int gz_decomp OF((gz_statep));
local int gz_make OF((gz_statep));
local int gz_skip OF((gz_statep, z_off64_t));
/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from
state->fd, and update state->eof, state->err, and state->msg as appropriate.
This function needs to loop on read(), since read() is not guaranteed to
read the number of bytes requested, depending on the type of descriptor. */
local int gz_load(state, buf, len, have)
gz_statep state;
unsigned char *buf;
unsigned len;
unsigned *have;
{
int ret;
*have = 0;
do {
ret = read(state->fd, buf + *have, len - *have);
if (ret <= 0)
break;
*have += ret;
} while (*have < len);
if (ret < 0) {
gz_error(state, Z_ERRNO, zstrerror());
return -1;
}
if (ret == 0)
state->eof = 1;
return 0;
}
/* Load up input buffer and set eof flag if last data loaded -- return -1 on
error, 0 otherwise. Note that the eof flag is set when the end of the input
file is reached, even though there may be unused data in the buffer. Once
that data has been used, no more attempts will be made to read the file.
gz_avail() assumes that strm->avail_in == 0. */
local int gz_avail(state)
gz_statep state;
{
z_streamp strm = &(state->strm);
if (state->err != Z_OK)
return -1;
if (state->eof == 0) {
if (gz_load(state, state->in, state->size, &(strm->avail_in)) == -1)
return -1;
strm->next_in = state->in;
}
return 0;
}
/* Get next byte from input, or -1 if end or error. */
#define NEXT() ((strm->avail_in == 0 && gz_avail(state) == -1) ? -1 : \
(strm->avail_in == 0 ? -1 : \
(strm->avail_in--, *(strm->next_in)++)))
/* Get a four-byte little-endian integer and return 0 on success and the value
in *ret. Otherwise -1 is returned and *ret is not modified. */
local int gz_next4(state, ret)
gz_statep state;
unsigned long *ret;
{
int ch;
unsigned long val;
z_streamp strm = &(state->strm);
val = NEXT();
val += (unsigned)NEXT() << 8;
val += (unsigned long)NEXT() << 16;
ch = NEXT();
if (ch == -1)
return -1;
val += (unsigned long)ch << 24;
*ret = val;
return 0;
}
/* Look for gzip header, set up for inflate or copy. state->have must be zero.
If this is the first time in, allocate required memory. state->how will be
left unchanged if there is no more input data available, will be set to COPY
if there is no gzip header and direct copying will be performed, or it will
be set to GZIP for decompression, and the gzip header will be skipped so
that the next available input data is the raw deflate stream. If direct
copying, then leftover input data from the input buffer will be copied to
the output buffer. In that case, all further file reads will be directly to
either the output buffer or a user buffer. If decompressing, the inflate
state and the check value will be initialized. gz_head() will return 0 on
success or -1 on failure. Failures may include read errors or gzip header
errors. */
local int gz_head(state)
gz_statep state;
{
z_streamp strm = &(state->strm);
int flags;
unsigned len;
/* allocate read buffers and inflate memory */
if (state->size == 0) {
/* allocate buffers */
state->in = malloc(state->want);
state->out = malloc(state->want << 1);
if (state->in == NULL || state->out == NULL) {
if (state->out != NULL)
free(state->out);
if (state->in != NULL)
free(state->in);
gz_error(state, Z_MEM_ERROR, "out of memory");
return -1;
}
state->size = state->want;
/* allocate inflate memory */
state->strm.zalloc = Z_NULL;
state->strm.zfree = Z_NULL;
state->strm.opaque = Z_NULL;
state->strm.avail_in = 0;
state->strm.next_in = Z_NULL;
if (inflateInit2(&(state->strm), -15) != Z_OK) { /* raw inflate */
free(state->out);
free(state->in);
state->size = 0;
gz_error(state, Z_MEM_ERROR, "out of memory");
return -1;
}
}
/* get some data in the input buffer */
if (strm->avail_in == 0) {
if (gz_avail(state) == -1)
return -1;
if (strm->avail_in == 0)
return 0;
}
/* look for the gzip magic header bytes 31 and 139 */
if (strm->next_in[0] == 31) {
strm->avail_in--;
strm->next_in++;
if (strm->avail_in == 0 && gz_avail(state) == -1)
return -1;
if (strm->avail_in && strm->next_in[0] == 139) {
/* we have a gzip header, woo hoo! */
strm->avail_in--;
strm->next_in++;
/* skip rest of header */
if (NEXT() != 8) { /* compression method */
gz_error(state, Z_DATA_ERROR, "unknown compression method");
return -1;
}
flags = NEXT();
if (flags & 0xe0) { /* reserved flag bits */
gz_error(state, Z_DATA_ERROR, "unknown header flags set");
return -1;
}
NEXT(); /* modification time */
NEXT();
NEXT();
NEXT();
NEXT(); /* extra flags */
NEXT(); /* operating system */
if (flags & 4) { /* extra field */
len = (unsigned)NEXT();
len += (unsigned)NEXT() << 8;
while (len--)
if (NEXT() < 0)
break;
}
if (flags & 8) /* file name */
while (NEXT() > 0)
;
if (flags & 16) /* comment */
while (NEXT() > 0)
;
if (flags & 2) { /* header crc */
NEXT();
NEXT();
}
/* an unexpected end of file is not checked for here -- it will be
noticed on the first request for uncompressed data */
/* set up for decompression */
inflateReset(strm);
strm->adler = crc32(0L, Z_NULL, 0);
state->how = GZIP;
state->direct = 0;
return 0;
}
else {
/* not a gzip file -- save first byte (31) and fall to raw i/o */
state->out[0] = 31;
state->have = 1;
}
}
/* doing raw i/o, save start of raw data for seeking, copy any leftover
input to output -- this assumes that the output buffer is larger than
the input buffer, which also assures space for gzungetc() */
state->raw = state->pos;
state->next = state->out;
if (strm->avail_in) {
memcpy(state->next + state->have, strm->next_in, strm->avail_in);
state->have += strm->avail_in;
strm->avail_in = 0;
}
state->how = COPY;
state->direct = 1;
return 0;
}
/* Decompress from input to the provided next_out and avail_out in the state.
If the end of the compressed data is reached, then verify the gzip trailer
check value and length (modulo 2^32). state->have and state->next are set
to point to the just decompressed data, and the crc is updated. If the
trailer is verified, state->how is reset to LOOK to look for the next gzip
stream or raw data, once state->have is depleted. Returns 0 on success, -1
on failure. Failures may include invalid compressed data or a failed gzip
trailer verification. */
local int gz_decomp(state)
gz_statep state;
{
int ret;
unsigned had;
unsigned long crc, len;
z_streamp strm = &(state->strm);
/* fill output buffer up to end of deflate stream */
had = strm->avail_out;
do {
/* get more input for inflate() */
if (strm->avail_in == 0 && gz_avail(state) == -1)
return -1;
if (strm->avail_in == 0) {
gz_error(state, Z_DATA_ERROR, "unexpected end of file");
return -1;
}
/* decompress and handle errors */
ret = inflate(strm, Z_NO_FLUSH);
if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
gz_error(state, Z_STREAM_ERROR,
"internal error: inflate stream corrupt");
return -1;
}
if (ret == Z_MEM_ERROR) {
gz_error(state, Z_MEM_ERROR, "out of memory");
return -1;
}
if (ret == Z_DATA_ERROR) { /* deflate stream invalid */
gz_error(state, Z_DATA_ERROR,
strm->msg == NULL ? "compressed data error" : strm->msg);
return -1;
}
} while (strm->avail_out && ret != Z_STREAM_END);
/* update available output and crc check value */
state->have = had - strm->avail_out;
state->next = strm->next_out - state->have;
strm->adler = crc32(strm->adler, state->next, state->have);
/* check gzip trailer if at end of deflate stream */
if (ret == Z_STREAM_END) {
if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) {
gz_error(state, Z_DATA_ERROR, "unexpected end of file");
return -1;
}
if (crc != strm->adler) {
gz_error(state, Z_DATA_ERROR, "incorrect data check");
return -1;
}
if (len != (strm->total_out & 0xffffffffL)) {
gz_error(state, Z_DATA_ERROR, "incorrect length check");
return -1;
}
state->how = LOOK; /* ready for next stream, once have is 0 (leave
state->direct unchanged to remember how) */
}
/* good decompression */
return 0;
}
/* Make data and put in the output buffer. Assumes that state->have == 0.
Data is either copied from the input file or decompressed from the input
file depending on state->how. If state->how is LOOK, then a gzip header is
looked for (and skipped if found) to determine wither to copy or decompress.
Returns -1 on error, otherwise 0. gz_make() will leave state->have as COPY
or GZIP unless the end of the input file has been reached and all data has
been processed. */
local int gz_make(state)
gz_statep state;
{
z_streamp strm = &(state->strm);
if (state->how == LOOK) { /* look for gzip header */
if (gz_head(state) == -1)
return -1;
if (state->have) /* got some data from gz_head() */
return 0;
}
if (state->how == COPY) { /* straight copy */
if (gz_load(state, state->out, state->size << 1, &(state->have)) == -1)
return -1;
state->next = state->out;
}
else if (state->how == GZIP) { /* decompress */
strm->avail_out = state->size << 1;
strm->next_out = state->out;
if (gz_decomp(state) == -1)
return -1;
}
return 0;
}
/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */
local int gz_skip(state, len)
gz_statep state;
z_off64_t len;
{
unsigned n;
/* skip over len bytes or reach end-of-file, whichever comes first */
while (len)
/* skip over whatever is in output buffer */
if (state->have) {
n = GT_OFF(state->have) || (z_off64_t)state->have > len ?
(unsigned)len : state->have;
state->have -= n;
state->next += n;
state->pos += n;
len -= n;
}
/* output buffer empty -- return if we're at the end of the input */
else if (state->eof && state->strm.avail_in == 0)
break;
/* need more data to skip -- load up output buffer */
else {
/* get more output, looking for header if required */
if (gz_make(state) == -1)
return -1;
}
return 0;
}
/* -- see zlib.h -- */
int ZEXPORT gzread(file, buf, len)
gzFile file;
voidp buf;
unsigned len;
{
unsigned got, n;
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ || state->err != Z_OK)
return -1;
/* since an int is returned, make sure len fits in one, otherwise return
with an error (this avoids the flaw in the interface) */
if ((int)len < 0) {
gz_error(state, Z_BUF_ERROR, "requested length does not fit in int");
return -1;
}
/* if len is zero, avoid unnecessary operations */
if (len == 0)
return 0;
/* process a skip request */
if (state->seek) {
state->seek = 0;
if (gz_skip(state, state->skip) == -1)
return -1;
}
/* get len bytes to buf, or less than len if at the end */
got = 0;
do {
/* first just try copying data from the output buffer */
if (state->have) {
n = state->have > len ? len : state->have;
memcpy(buf, state->next, n);
state->next += n;
state->have -= n;
}
/* output buffer empty -- return if we're at the end of the input */
else if (state->eof && strm->avail_in == 0)
break;
/* need output data -- for small len or new stream load up our output
buffer */
else if (state->how == LOOK || len < (state->size << 1)) {
/* get more output, looking for header if required */
if (gz_make(state) == -1)
return -1;
continue; /* no progress yet -- go back to memcpy() above */
/* the copy above assures that we will leave with space in the
output buffer, allowing at least one gzungetc() to succeed */
}
/* large len -- read directly into user buffer */
else if (state->how == COPY) { /* read directly */
if (gz_load(state, buf, len, &n) == -1)
return -1;
}
/* large len -- decompress directly into user buffer */
else { /* state->how == GZIP */
strm->avail_out = len;
strm->next_out = buf;
if (gz_decomp(state) == -1)
return -1;
n = state->have;
state->have = 0;
}
/* update progress */
len -= n;
buf = (char *)buf + n;
got += n;
state->pos += n;
} while (len);
/* return number of bytes read into user buffer (will fit in int) */
return (int)got;
}
/* -- see zlib.h -- */
int ZEXPORT gzgetc(file)
gzFile file;
{
int ret;
unsigned char buf[1];
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ || state->err != Z_OK)
return -1;
/* try output buffer (no need to check for skip request) */
if (state->have) {
state->have--;
state->pos++;
return *(state->next)++;
}
/* nothing there -- try gzread() */
ret = gzread(file, buf, 1);
return ret < 1 ? -1 : buf[0];
}
/* -- see zlib.h -- */
int ZEXPORT gzungetc(c, file)
int c;
gzFile file;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ || state->err != Z_OK)
return -1;
/* process a skip request */
if (state->seek) {
state->seek = 0;
if (gz_skip(state, state->skip) == -1)
return -1;
}
/* can't push EOF */
if (c < 0)
return -1;
/* if output buffer empty, put byte at end (allows more pushing) */
if (state->have == 0) {
state->have = 1;
state->next = state->out + (state->size << 1) - 1;
state->next[0] = c;
state->pos--;
return c;
}
/* if no room, give up (must have already done a gzungetc()) */
if (state->have == (state->size << 1)) {
gz_error(state, Z_BUF_ERROR, "out of room to push characters");
return -1;
}
/* slide output data if needed and insert byte before existing data */
if (state->next == state->out) {
unsigned char *src = state->out + state->have;
unsigned char *dest = state->out + (state->size << 1);
while (src > state->out)
*--dest = *--src;
state->next = dest;
}
state->have++;
state->next--;
state->next[0] = c;
state->pos--;
return c;
}
/* -- see zlib.h -- */
char * ZEXPORT gzgets(file, buf, len)
gzFile file;
char *buf;
int len;
{
unsigned left, n;
char *str;
unsigned char *eol;
gz_statep state;
/* get internal structure */
if (file == NULL)
return NULL;
state = (gz_statep)file;
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ || state->err != Z_OK)
return NULL;
/* process a skip request */
if (state->seek) {
state->seek = 0;
if (gz_skip(state, state->skip) == -1)
return NULL;
}
/* check for a dumb length */
if (len < 2)
return NULL;
/* copy output bytes up to new line or len - 1, whichever comes first --
append a terminating zero to the string (we don't check for a zero in
the contents, let the user worry about that) */
str = buf;
left = (unsigned)len - 1;
do {
/* assure that something is in the output buffer */
if (state->have == 0) {
if (gz_make(state) == -1)
return NULL; /* error */
if (state->have == 0) { /* end of file */
if (buf == str) /* got bupkus */
return NULL;
break; /* got something -- return it */
}
}
/* look for end-of-line in current output buffer */
n = state->have > left ? left : state->have;
eol = memchr(state->next, '\n', n);
if (eol != NULL)
n = (eol - state->next) + 1;
/* copy through end-of-line, or remainder if not found */
memcpy(buf, state->next, n);
state->have -= n;
state->next += n;
state->pos += n;
left -= n;
buf += n;
} while (left && eol == NULL);
/* found end-of-line or out of space -- terminate string and return it */
buf[0] = 0;
return str;
}
/* -- see zlib.h -- */
int ZEXPORT gzdirect(file)
gzFile file;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return 0;
state = (gz_statep)file;
/* check that we're reading */
if (state->mode != GZ_READ)
return 0;
/* if the state is not known, but we can find out, then do so (this is
mainly for right after a gzopen() or gzdopen()) */
if (state->how == LOOK && state->have == 0)
(void)gz_head(state);
/* return 1 if reading direct, 0 if decompressing a gzip stream */
return state->direct;
}
/* -- see zlib.h -- */
int ZEXPORT gzclose_r(file)
gzFile file;
{
int ret;
gz_statep state;
/* get internal structure */
if (file == NULL)
return Z_STREAM_ERROR;
state = (gz_statep)file;
/* check that we're reading */
if (state->mode != GZ_READ)
return Z_STREAM_ERROR;
/* free memory and close file */
if (state->size) {
inflateEnd(&(state->strm));
free(state->out);
free(state->in);
}
gz_error(state, Z_OK, NULL);
ret = close(state->fd);
free(state);
return ret ? Z_ERRNO : Z_OK;
}
#endif /* !OLD_GZIO */

534
gzwrite.c Normal file
View File

@@ -0,0 +1,534 @@
/* gzwrite.c -- zlib functions for writing gzip files
* Copyright (C) 2004, 2005, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifndef OLD_GZIO
#include "gzguts.h"
/* Local functions */
local int gz_init OF((gz_statep));
local int gz_comp OF((gz_statep, int));
local int gz_zero OF((gz_statep, z_off64_t));
/* Initialize state for writing a gzip file. Mark initialization by setting
state->size to non-zero. Return -1 on failure or 0 on success. */
local int gz_init(state)
gz_statep state;
{
int ret;
z_streamp strm = &(state->strm);
/* allocate input and output buffers */
state->in = malloc(state->want);
state->out = malloc(state->want);
if (state->in == NULL || state->out == NULL) {
if (state->out != NULL)
free(state->out);
if (state->in != NULL)
free(state->in);
gz_error(state, Z_MEM_ERROR, "out of memory");
return -1;
}
/* allocate deflate memory, set up for gzip compression */
strm->zalloc = Z_NULL;
strm->zfree = Z_NULL;
strm->opaque = Z_NULL;
ret = deflateInit2(strm, state->level, Z_DEFLATED,
15 + 16, 8, state->strategy);
if (ret != Z_OK) {
free(state->in);
gz_error(state, Z_MEM_ERROR, "out of memory");
return -1;
}
/* mark state as initialized */
state->size = state->want;
/* initialize write buffer */
strm->avail_out = state->size;
strm->next_out = state->out;
state->next = strm->next_out;
return 0;
}
/* Compress whatever is at avail_in and next_in and write to the output file.
Return -1 if there is an error writing to the output file, otherwise 0.
flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH,
then the deflate() state is reset to start a new gzip stream. */
local int gz_comp(state, flush)
gz_statep state;
int flush;
{
int ret, got;
unsigned have;
z_streamp strm = &(state->strm);
/* allocate memory if this is the first time through */
if (state->size == 0 && gz_init(state) == -1)
return -1;
/* run deflate() on provided input until it produces no more output */
ret = Z_OK;
do {
/* write out current buffer contents if full, or if flushing, but if
doing Z_FINISH then don't write until we get to Z_STREAM_END */
if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
(flush != Z_FINISH || ret == Z_STREAM_END))) {
have = strm->next_out - state->next;
if (have && ((got = write(state->fd, state->next, have)) < 0 ||
(unsigned)got != have)) {
gz_error(state, Z_ERRNO, zstrerror());
return -1;
}
if (strm->avail_out == 0) {
strm->avail_out = state->size;
strm->next_out = state->out;
}
state->next = strm->next_out;
}
/* compress */
have = strm->avail_out;
ret = deflate(strm, flush);
if (ret == Z_STREAM_ERROR) {
gz_error(state, Z_STREAM_ERROR,
"internal error: deflate stream corrupt");
return -1;
}
have -= strm->avail_out;
} while (have);
/* if that completed a deflate stream, allow another to start */
if (flush == Z_FINISH)
deflateReset(strm);
/* all done, no errors */
return 0;
}
/* Compress len zeros to output. Return -1 on error, 0 on success. */
local int gz_zero(state, len)
gz_statep state;
z_off64_t len;
{
int first;
unsigned n;
z_streamp strm = &(state->strm);
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return -1;
/* compress len zeros (len guaranteed > 0) */
first = 1;
while (len) {
n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
(unsigned)len : state->size;
if (first) {
memset(state->in, 0, n);
first = 0;
}
strm->avail_in = n;
strm->next_in = state->in;
state->pos += n;
if (gz_comp(state, Z_NO_FLUSH) == -1)
return -1;
len -= n;
}
return 0;
}
/* -- see zlib.h -- */
int ZEXPORT gzwrite(file, buf, len)
gzFile file;
voidpc buf;
unsigned len;
{
unsigned put = len;
unsigned n;
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return 0;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return 0;
/* since an int is returned, make sure len fits in one, otherwise return
with an error (this avoids the flaw in the interface) */
if ((int)len < 0) {
gz_error(state, Z_BUF_ERROR, "requested length does not fit in int");
return 0;
}
/* if len is zero, avoid unnecessary operations */
if (len == 0)
return 0;
/* allocate memory if this is the first time through */
if (state->size == 0 && gz_init(state) == -1)
return 0;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return 0;
}
/* for small len, copy to input buffer, otherwise compress directly */
if (len < state->size) {
/* copy to input buffer, compress when full */
do {
if (strm->avail_in == 0)
strm->next_in = state->in;
n = state->size - strm->avail_in;
if (n > len)
n = len;
memcpy(strm->next_in + strm->avail_in, buf, n);
strm->avail_in += n;
state->pos += n;
buf = (char *)buf + n;
len -= n;
if (len && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
} while (len);
}
else {
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
/* directly compress user buffer to file */
strm->avail_in = len;
strm->next_in = (voidp)buf;
state->pos += len;
if (gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
}
/* input was all buffered or compressed (put will fit in int) */
return (int)put;
}
/* -- see zlib.h -- */
int ZEXPORT gzputc(file, c)
gzFile file;
int c;
{
unsigned char buf[1];
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return -1;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return -1;
}
/* try writing to input buffer for speed (state->size == 0 if buffer not
initialized) */
if (strm->avail_in < state->size) {
if (strm->avail_in == 0)
strm->next_in = state->in;
strm->next_in[strm->avail_in++] = c;
state->pos++;
return c;
}
/* no room in buffer or not initialized, use gz_write() */
buf[0] = c;
if (gzwrite(file, buf, 1) != 1)
return -1;
return c;
}
/* -- see zlib.h -- */
int ZEXPORT gzputs(file, str)
gzFile file;
const char *str;
{
int ret;
unsigned len;
/* write string */
len = strlen(str);
ret = gzwrite(file, str, len);
return ret == 0 && len != 0 ? -1 : ret;
}
#ifdef STDC
#include <stdarg.h>
/* -- see zlib.h -- */
int ZEXPORTVA gzprintf (gzFile file, const char *format, ...)
{
int size, len;
gz_statep state;
z_streamp strm;
va_list va;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return 0;
/* make sure we have some buffer space */
if (state->size == 0 && gz_init(state) == -1)
return 0;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return 0;
}
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
/* do the printf() into the input buffer, put length in len */
size = (int)(state->size);
state->in[size - 1] = 0;
va_start(va, format);
#ifdef NO_vsnprintf
# ifdef HAS_vsprintf_void
(void)vsprintf(state->in, format, va);
va_end(va);
for (len = 0; len < state->in; len++)
if (state->in[len] == 0) break;
# else
len = vsprintf(state->in, format, va);
va_end(va);
# endif
#else
# ifdef HAS_vsnprintf_void
(void)vsnprintf(state->in, size, format, va);
va_end(va);
len = strlen(state->in);
# else
len = vsnprintf((char *)(state->in), size, format, va);
va_end(va);
# endif
#endif
/* check that printf() results fit in buffer */
if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
return 0;
/* update buffer and position, defer compression until needed */
strm->avail_in = (unsigned)len;
strm->next_in = state->in;
state->pos += len;
return len;
}
#else /* !STDC */
/* -- see zlib.h -- */
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;
{
int size, len;
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return 0;
/* make sure we have some buffer space */
if (state->size == 0 && gz_init(state) == -1)
return 0;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return 0;
}
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
/* do the printf() into the input buffer, put length in len */
size = (int)(state->size);
state->in[size - 1] = 0;
#ifdef NO_snprintf
# ifdef HAS_sprintf_void
sprintf(state->in, 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 < size; len++)
if (state->in[len] == 0) break;
# else
len = sprintf(state->in, 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(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
len = strlen(state->in);
# else
len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
# endif
#endif
/* check that printf() results fit in buffer */
if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
return 0;
/* update buffer and position, defer compression until needed */
strm->avail_in = (unsigned)len;
strm->next_in = state->in;
state->pos += len;
return len;
}
#endif
/* -- see zlib.h -- */
int ZEXPORT gzflush(file, flush)
gzFile file;
int flush;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return Z_STREAM_ERROR;
/* check flush parameter */
if (flush < 0 || flush > Z_FINISH)
return Z_STREAM_ERROR;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return -1;
}
/* compress remaining data with requested flush */
gz_comp(state, flush);
return state->err;
}
/* -- see zlib.h -- */
int ZEXPORT gzsetparams(file, level, strategy)
gzFile file;
int level;
int strategy;
{
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return Z_STREAM_ERROR;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return Z_STREAM_ERROR;
/* if no change is requested, then do nothing */
if (level == state->level && strategy == state->strategy)
return Z_OK;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return -1;
}
/* change compression parameters for subsequent input */
if (state->size) {
/* flush previous input with previous parameters before changing */
if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1)
return state->err;
deflateParams(strm, level, strategy);
}
state->level = level;
state->strategy = strategy;
return Z_OK;
}
/* -- see zlib.h -- */
int ZEXPORT gzclose_w(file)
gzFile file;
{
int ret = 0;
gz_statep state;
/* get internal structure */
if (file == NULL)
return Z_STREAM_ERROR;
state = (gz_statep)file;
/* check that we're writing */
if (state->mode != GZ_WRITE)
return Z_STREAM_ERROR;
/* check for seek request */
if (state->seek) {
state->seek = 0;
ret += gz_zero(state, state->skip);
}
/* flush, free memory, and close file */
ret += gz_comp(state, Z_FINISH);
(void)deflateEnd(&(state->strm));
free(state->out);
free(state->in);
ret += close(state->fd);
gz_error(state, Z_OK, NULL);
free(state);
return ret ? Z_ERRNO : Z_OK;
}
#endif /* !OLD_GZIO */

View File

@@ -1,5 +1,5 @@
/* infback.c -- inflate using a call-back interface /* infback.c -- inflate using a call-back interface
* Copyright (C) 1995-2005 Mark Adler * Copyright (C) 1995-2009 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -55,7 +55,7 @@ int stream_size;
state->wbits = windowBits; state->wbits = windowBits;
state->wsize = 1U << windowBits; state->wsize = 1U << windowBits;
state->window = window; state->window = window;
state->write = 0; state->wnext = 0;
state->whave = 0; state->whave = 0;
return Z_OK; return Z_OK;
} }
@@ -253,7 +253,7 @@ void FAR *out_desc;
unsigned bits; /* bits in bit buffer */ unsigned bits; /* bits in bit buffer */
unsigned copy; /* number of stored or match bytes to copy */ unsigned copy; /* number of stored or match bytes to copy */
unsigned char FAR *from; /* where to copy match bytes from */ unsigned char FAR *from; /* where to copy match bytes from */
code this; /* current decoding table entry */ code here; /* current decoding table entry */
code last; /* parent table entry */ code last; /* parent table entry */
unsigned len; /* length to copy for repeats, bits to drop */ unsigned len; /* length to copy for repeats, bits to drop */
int ret; /* return code */ int ret; /* return code */
@@ -389,19 +389,19 @@ void FAR *out_desc;
state->have = 0; state->have = 0;
while (state->have < state->nlen + state->ndist) { while (state->have < state->nlen + state->ndist) {
for (;;) { for (;;) {
this = state->lencode[BITS(state->lenbits)]; here = state->lencode[BITS(state->lenbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if (this.val < 16) { if (here.val < 16) {
NEEDBITS(this.bits); NEEDBITS(here.bits);
DROPBITS(this.bits); DROPBITS(here.bits);
state->lens[state->have++] = this.val; state->lens[state->have++] = here.val;
} }
else { else {
if (this.val == 16) { if (here.val == 16) {
NEEDBITS(this.bits + 2); NEEDBITS(here.bits + 2);
DROPBITS(this.bits); DROPBITS(here.bits);
if (state->have == 0) { if (state->have == 0) {
strm->msg = (char *)"invalid bit length repeat"; strm->msg = (char *)"invalid bit length repeat";
state->mode = BAD; state->mode = BAD;
@@ -411,16 +411,16 @@ void FAR *out_desc;
copy = 3 + BITS(2); copy = 3 + BITS(2);
DROPBITS(2); DROPBITS(2);
} }
else if (this.val == 17) { else if (here.val == 17) {
NEEDBITS(this.bits + 3); NEEDBITS(here.bits + 3);
DROPBITS(this.bits); DROPBITS(here.bits);
len = 0; len = 0;
copy = 3 + BITS(3); copy = 3 + BITS(3);
DROPBITS(3); DROPBITS(3);
} }
else { else {
NEEDBITS(this.bits + 7); NEEDBITS(here.bits + 7);
DROPBITS(this.bits); DROPBITS(here.bits);
len = 0; len = 0;
copy = 11 + BITS(7); copy = 11 + BITS(7);
DROPBITS(7); DROPBITS(7);
@@ -438,7 +438,16 @@ void FAR *out_desc;
/* handle error breaks in while */ /* handle error breaks in while */
if (state->mode == BAD) break; if (state->mode == BAD) break;
/* build code tables */ /* check for end-of-block code (better have one) */
if (state->lens[256] == 0) {
strm->msg = (char *)"invalid code -- missing end-of-block";
state->mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state->next = state->codes; state->next = state->codes;
state->lencode = (code const FAR *)(state->next); state->lencode = (code const FAR *)(state->next);
state->lenbits = 9; state->lenbits = 9;
@@ -474,28 +483,28 @@ void FAR *out_desc;
/* get a literal, length, or end-of-block code */ /* get a literal, length, or end-of-block code */
for (;;) { for (;;) {
this = state->lencode[BITS(state->lenbits)]; here = state->lencode[BITS(state->lenbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if (this.op && (this.op & 0xf0) == 0) { if (here.op && (here.op & 0xf0) == 0) {
last = this; last = here;
for (;;) { for (;;) {
this = state->lencode[last.val + here = state->lencode[last.val +
(BITS(last.bits + last.op) >> last.bits)]; (BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + this.bits) <= bits) break; if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
DROPBITS(last.bits); DROPBITS(last.bits);
} }
DROPBITS(this.bits); DROPBITS(here.bits);
state->length = (unsigned)this.val; state->length = (unsigned)here.val;
/* process literal */ /* process literal */
if (this.op == 0) { if (here.op == 0) {
Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" : "inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", this.val)); "inflate: literal 0x%02x\n", here.val));
ROOM(); ROOM();
*put++ = (unsigned char)(state->length); *put++ = (unsigned char)(state->length);
left--; left--;
@@ -504,21 +513,21 @@ void FAR *out_desc;
} }
/* process end of block */ /* process end of block */
if (this.op & 32) { if (here.op & 32) {
Tracevv((stderr, "inflate: end of block\n")); Tracevv((stderr, "inflate: end of block\n"));
state->mode = TYPE; state->mode = TYPE;
break; break;
} }
/* invalid code */ /* invalid code */
if (this.op & 64) { if (here.op & 64) {
strm->msg = (char *)"invalid literal/length code"; strm->msg = (char *)"invalid literal/length code";
state->mode = BAD; state->mode = BAD;
break; break;
} }
/* length code -- get extra bits, if any */ /* length code -- get extra bits, if any */
state->extra = (unsigned)(this.op) & 15; state->extra = (unsigned)(here.op) & 15;
if (state->extra != 0) { if (state->extra != 0) {
NEEDBITS(state->extra); NEEDBITS(state->extra);
state->length += BITS(state->extra); state->length += BITS(state->extra);
@@ -528,30 +537,30 @@ void FAR *out_desc;
/* get distance code */ /* get distance code */
for (;;) { for (;;) {
this = state->distcode[BITS(state->distbits)]; here = state->distcode[BITS(state->distbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if ((this.op & 0xf0) == 0) { if ((here.op & 0xf0) == 0) {
last = this; last = here;
for (;;) { for (;;) {
this = state->distcode[last.val + here = state->distcode[last.val +
(BITS(last.bits + last.op) >> last.bits)]; (BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + this.bits) <= bits) break; if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
DROPBITS(last.bits); DROPBITS(last.bits);
} }
DROPBITS(this.bits); DROPBITS(here.bits);
if (this.op & 64) { if (here.op & 64) {
strm->msg = (char *)"invalid distance code"; strm->msg = (char *)"invalid distance code";
state->mode = BAD; state->mode = BAD;
break; break;
} }
state->offset = (unsigned)this.val; state->offset = (unsigned)here.val;
/* get distance extra bits, if any */ /* get distance extra bits, if any */
state->extra = (unsigned)(this.op) & 15; state->extra = (unsigned)(here.op) & 15;
if (state->extra != 0) { if (state->extra != 0) {
NEEDBITS(state->extra); NEEDBITS(state->extra);
state->offset += BITS(state->extra); state->offset += BITS(state->extra);

View File

@@ -1,5 +1,5 @@
/* inffast.c -- fast decoding /* inffast.c -- fast decoding
* Copyright (C) 1995-2004 Mark Adler * Copyright (C) 1995-2008 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -79,7 +79,7 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
#endif #endif
unsigned wsize; /* window size or zero if not using window */ unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */ unsigned whave; /* valid bytes in the window */
unsigned write; /* window write index */ unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
unsigned long hold; /* local strm->hold */ unsigned long hold; /* local strm->hold */
unsigned bits; /* local strm->bits */ unsigned bits; /* local strm->bits */
@@ -87,7 +87,7 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
code const FAR *dcode; /* local strm->distcode */ code const FAR *dcode; /* local strm->distcode */
unsigned lmask; /* mask for first level of length codes */ unsigned lmask; /* mask for first level of length codes */
unsigned dmask; /* mask for first level of distance codes */ unsigned dmask; /* mask for first level of distance codes */
code this; /* retrieved table entry */ code here; /* retrieved table entry */
unsigned op; /* code bits, operation, extra bits, or */ unsigned op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */ /* window position, window bytes to copy */
unsigned len; /* match length, unused bytes */ unsigned len; /* match length, unused bytes */
@@ -106,7 +106,7 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
#endif #endif
wsize = state->wsize; wsize = state->wsize;
whave = state->whave; whave = state->whave;
write = state->write; wnext = state->wnext;
window = state->window; window = state->window;
hold = state->hold; hold = state->hold;
bits = state->bits; bits = state->bits;
@@ -124,20 +124,20 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
hold += (unsigned long)(PUP(in)) << bits; hold += (unsigned long)(PUP(in)) << bits;
bits += 8; bits += 8;
} }
this = lcode[hold & lmask]; here = lcode[hold & lmask];
dolen: dolen:
op = (unsigned)(this.bits); op = (unsigned)(here.bits);
hold >>= op; hold >>= op;
bits -= op; bits -= op;
op = (unsigned)(this.op); op = (unsigned)(here.op);
if (op == 0) { /* literal */ if (op == 0) { /* literal */
Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" : "inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", this.val)); "inflate: literal 0x%02x\n", here.val));
PUP(out) = (unsigned char)(this.val); PUP(out) = (unsigned char)(here.val);
} }
else if (op & 16) { /* length base */ else if (op & 16) { /* length base */
len = (unsigned)(this.val); len = (unsigned)(here.val);
op &= 15; /* number of extra bits */ op &= 15; /* number of extra bits */
if (op) { if (op) {
if (bits < op) { if (bits < op) {
@@ -155,14 +155,14 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
hold += (unsigned long)(PUP(in)) << bits; hold += (unsigned long)(PUP(in)) << bits;
bits += 8; bits += 8;
} }
this = dcode[hold & dmask]; here = dcode[hold & dmask];
dodist: dodist:
op = (unsigned)(this.bits); op = (unsigned)(here.bits);
hold >>= op; hold >>= op;
bits -= op; bits -= op;
op = (unsigned)(this.op); op = (unsigned)(here.op);
if (op & 16) { /* distance base */ if (op & 16) { /* distance base */
dist = (unsigned)(this.val); dist = (unsigned)(here.val);
op &= 15; /* number of extra bits */ op &= 15; /* number of extra bits */
if (bits < op) { if (bits < op) {
hold += (unsigned long)(PUP(in)) << bits; hold += (unsigned long)(PUP(in)) << bits;
@@ -187,12 +187,34 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
if (dist > op) { /* see if copy from window */ if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */ op = dist - op; /* distance back in window */
if (op > whave) { if (op > whave) {
strm->msg = (char *)"invalid distance too far back"; if (state->sane) {
state->mode = BAD; strm->msg =
break; (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
if (len <= op - whave) {
do {
PUP(out) = 0;
} while (--len);
continue;
}
len -= op - whave;
do {
PUP(out) = 0;
} while (--op > whave);
if (op == 0) {
from = out - dist;
do {
PUP(out) = PUP(from);
} while (--len);
continue;
}
#endif
} }
from = window - OFF; from = window - OFF;
if (write == 0) { /* very common case */ if (wnext == 0) { /* very common case */
from += wsize - op; from += wsize - op;
if (op < len) { /* some from window */ if (op < len) { /* some from window */
len -= op; len -= op;
@@ -202,17 +224,17 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
from = out - dist; /* rest from output */ from = out - dist; /* rest from output */
} }
} }
else if (write < op) { /* wrap around window */ else if (wnext < op) { /* wrap around window */
from += wsize + write - op; from += wsize + wnext - op;
op -= write; op -= wnext;
if (op < len) { /* some from end of window */ if (op < len) { /* some from end of window */
len -= op; len -= op;
do { do {
PUP(out) = PUP(from); PUP(out) = PUP(from);
} while (--op); } while (--op);
from = window - OFF; from = window - OFF;
if (write < len) { /* some from start of window */ if (wnext < len) { /* some from start of window */
op = write; op = wnext;
len -= op; len -= op;
do { do {
PUP(out) = PUP(from); PUP(out) = PUP(from);
@@ -222,7 +244,7 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
} }
} }
else { /* contiguous in window */ else { /* contiguous in window */
from += write - op; from += wnext - op;
if (op < len) { /* some from window */ if (op < len) { /* some from window */
len -= op; len -= op;
do { do {
@@ -259,7 +281,7 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
} }
} }
else if ((op & 64) == 0) { /* 2nd level distance code */ else if ((op & 64) == 0) { /* 2nd level distance code */
this = dcode[this.val + (hold & ((1U << op) - 1))]; here = dcode[here.val + (hold & ((1U << op) - 1))];
goto dodist; goto dodist;
} }
else { else {
@@ -269,7 +291,7 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
} }
} }
else if ((op & 64) == 0) { /* 2nd level length code */ else if ((op & 64) == 0) { /* 2nd level length code */
this = lcode[this.val + (hold & ((1U << op) - 1))]; here = lcode[here.val + (hold & ((1U << op) - 1))];
goto dolen; goto dolen;
} }
else if (op & 32) { /* end-of-block */ else if (op & 32) { /* end-of-block */
@@ -305,7 +327,7 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
- Using bit fields for code structure - Using bit fields for code structure
- Different op definition to avoid & for extra bits (do & for table bits) - Different op definition to avoid & for extra bits (do & for table bits)
- Three separate decoding do-loops for direct, window, and write == 0 - Three separate decoding do-loops for direct, window, and wnext == 0
- Special case for distance > 1 copies to do overlapped load and store copy - Special case for distance > 1 copies to do overlapped load and store copy
- Explicit branch predictions (based on measured branch probabilities) - Explicit branch predictions (based on measured branch probabilities)
- Deferring match copy and interspersed it with decoding subsequent codes - Deferring match copy and interspersed it with decoding subsequent codes

282
inflate.c
View File

@@ -1,5 +1,5 @@
/* inflate.c -- zlib decompression /* inflate.c -- zlib decompression
* Copyright (C) 1995-2005 Mark Adler * Copyright (C) 1995-2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -45,7 +45,7 @@
* - Rearrange window copies in inflate_fast() for speed and simplification * - Rearrange window copies in inflate_fast() for speed and simplification
* - Unroll last copy for window match in inflate_fast() * - Unroll last copy for window match in inflate_fast()
* - Use local copies of window variables in inflate_fast() for speed * - Use local copies of window variables in inflate_fast() for speed
* - Pull out common write == 0 case for speed in inflate_fast() * - Pull out common wnext == 0 case for speed in inflate_fast()
* - Make op and len in inflate_fast() unsigned for consistency * - Make op and len in inflate_fast() unsigned for consistency
* - Add FAR to lcode and dcode declarations in inflate_fast() * - Add FAR to lcode and dcode declarations in inflate_fast()
* - Simplified bad distance check in inflate_fast() * - Simplified bad distance check in inflate_fast()
@@ -117,28 +117,52 @@ z_streamp strm;
state->head = Z_NULL; state->head = Z_NULL;
state->wsize = 0; state->wsize = 0;
state->whave = 0; state->whave = 0;
state->write = 0; state->wnext = 0;
state->hold = 0; state->hold = 0;
state->bits = 0; state->bits = 0;
state->lencode = state->distcode = state->next = state->codes; state->lencode = state->distcode = state->next = state->codes;
state->sane = 1;
state->back = -1;
Tracev((stderr, "inflate: reset\n")); Tracev((stderr, "inflate: reset\n"));
return Z_OK; return Z_OK;
} }
int ZEXPORT inflatePrime(strm, bits, value) int ZEXPORT inflateReset2(strm, windowBits)
z_streamp strm; z_streamp strm;
int bits; int windowBits;
int value;
{ {
int wrap;
struct inflate_state FAR *state; struct inflate_state FAR *state;
/* get the state */
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
state = (struct inflate_state FAR *)strm->state; state = (struct inflate_state FAR *)strm->state;
if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
value &= (1L << bits) - 1; /* extract wrap request from windowBits parameter */
state->hold += value << state->bits; if (windowBits < 0) {
state->bits += bits; wrap = 0;
return Z_OK; windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
#ifdef GUNZIP
if (windowBits < 48)
windowBits &= 15;
#endif
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15))
return Z_STREAM_ERROR;
if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
ZFREE(strm, state->window);
state->window = Z_NULL;
}
/* update state and reset the rest of it */
state->wrap = wrap;
state->wbits = (unsigned)windowBits;
return inflateReset(strm);
} }
int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
@@ -147,6 +171,7 @@ int windowBits;
const char *version; const char *version;
int stream_size; int stream_size;
{ {
int ret;
struct inflate_state FAR *state; struct inflate_state FAR *state;
if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
@@ -164,24 +189,13 @@ int stream_size;
if (state == Z_NULL) return Z_MEM_ERROR; if (state == Z_NULL) return Z_MEM_ERROR;
Tracev((stderr, "inflate: allocated\n")); Tracev((stderr, "inflate: allocated\n"));
strm->state = (struct internal_state FAR *)state; strm->state = (struct internal_state FAR *)state;
if (windowBits < 0) { state->window = Z_NULL;
state->wrap = 0; ret = inflateReset2(strm, windowBits);
windowBits = -windowBits; if (ret != Z_OK) {
}
else {
state->wrap = (windowBits >> 4) + 1;
#ifdef GUNZIP
if (windowBits < 48) windowBits &= 15;
#endif
}
if (windowBits < 8 || windowBits > 15) {
ZFREE(strm, state); ZFREE(strm, state);
strm->state = Z_NULL; strm->state = Z_NULL;
return Z_STREAM_ERROR;
} }
state->wbits = (unsigned)windowBits; return ret;
state->window = Z_NULL;
return inflateReset(strm);
} }
int ZEXPORT inflateInit_(strm, version, stream_size) int ZEXPORT inflateInit_(strm, version, stream_size)
@@ -192,6 +206,27 @@ int stream_size;
return inflateInit2_(strm, DEF_WBITS, version, stream_size); return inflateInit2_(strm, DEF_WBITS, version, stream_size);
} }
int ZEXPORT inflatePrime(strm, bits, value)
z_streamp strm;
int bits;
int value;
{
struct inflate_state FAR *state;
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
state = (struct inflate_state FAR *)strm->state;
if (bits < 0) {
state->hold = 0;
state->bits = 0;
return Z_OK;
}
if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
value &= (1L << bits) - 1;
state->hold += value << state->bits;
state->bits += bits;
return Z_OK;
}
/* /*
Return state with length and distance decoding tables and index sizes set to Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h. fixed code decoding. Normally this returns fixed tables from inffixed.h.
@@ -340,7 +375,7 @@ unsigned out;
/* if window not in use yet, initialize */ /* if window not in use yet, initialize */
if (state->wsize == 0) { if (state->wsize == 0) {
state->wsize = 1U << state->wbits; state->wsize = 1U << state->wbits;
state->write = 0; state->wnext = 0;
state->whave = 0; state->whave = 0;
} }
@@ -348,22 +383,22 @@ unsigned out;
copy = out - strm->avail_out; copy = out - strm->avail_out;
if (copy >= state->wsize) { if (copy >= state->wsize) {
zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
state->write = 0; state->wnext = 0;
state->whave = state->wsize; state->whave = state->wsize;
} }
else { else {
dist = state->wsize - state->write; dist = state->wsize - state->wnext;
if (dist > copy) dist = copy; if (dist > copy) dist = copy;
zmemcpy(state->window + state->write, strm->next_out - copy, dist); zmemcpy(state->window + state->wnext, strm->next_out - copy, dist);
copy -= dist; copy -= dist;
if (copy) { if (copy) {
zmemcpy(state->window, strm->next_out - copy, copy); zmemcpy(state->window, strm->next_out - copy, copy);
state->write = copy; state->wnext = copy;
state->whave = state->wsize; state->whave = state->wsize;
} }
else { else {
state->write += dist; state->wnext += dist;
if (state->write == state->wsize) state->write = 0; if (state->wnext == state->wsize) state->wnext = 0;
if (state->whave < state->wsize) state->whave += dist; if (state->whave < state->wsize) state->whave += dist;
} }
} }
@@ -564,7 +599,7 @@ int flush;
unsigned in, out; /* save starting available input and output */ unsigned in, out; /* save starting available input and output */
unsigned copy; /* number of stored or match bytes to copy */ unsigned copy; /* number of stored or match bytes to copy */
unsigned char FAR *from; /* where to copy match bytes from */ unsigned char FAR *from; /* where to copy match bytes from */
code this; /* current decoding table entry */ code here; /* current decoding table entry */
code last; /* parent table entry */ code last; /* parent table entry */
unsigned len; /* length to copy for repeats, bits to drop */ unsigned len; /* length to copy for repeats, bits to drop */
int ret; /* return code */ int ret; /* return code */
@@ -619,7 +654,9 @@ int flush;
} }
DROPBITS(4); DROPBITS(4);
len = BITS(4) + 8; len = BITS(4) + 8;
if (len > state->wbits) { if (state->wbits == 0)
state->wbits = len;
else if (len > state->wbits) {
strm->msg = (char *)"invalid window size"; strm->msg = (char *)"invalid window size";
state->mode = BAD; state->mode = BAD;
break; break;
@@ -771,7 +808,7 @@ int flush;
strm->adler = state->check = adler32(0L, Z_NULL, 0); strm->adler = state->check = adler32(0L, Z_NULL, 0);
state->mode = TYPE; state->mode = TYPE;
case TYPE: case TYPE:
if (flush == Z_BLOCK) goto inf_leave; if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
case TYPEDO: case TYPEDO:
if (state->last) { if (state->last) {
BYTEBITS(); BYTEBITS();
@@ -791,7 +828,11 @@ int flush;
fixedtables(state); fixedtables(state);
Tracev((stderr, "inflate: fixed codes block%s\n", Tracev((stderr, "inflate: fixed codes block%s\n",
state->last ? " (last)" : "")); state->last ? " (last)" : ""));
state->mode = LEN; /* decode codes */ state->mode = LEN_; /* decode codes */
if (flush == Z_TREES) {
DROPBITS(2);
goto inf_leave;
}
break; break;
case 2: /* dynamic block */ case 2: /* dynamic block */
Tracev((stderr, "inflate: dynamic codes block%s\n", Tracev((stderr, "inflate: dynamic codes block%s\n",
@@ -816,6 +857,9 @@ int flush;
Tracev((stderr, "inflate: stored length %u\n", Tracev((stderr, "inflate: stored length %u\n",
state->length)); state->length));
INITBITS(); INITBITS();
state->mode = COPY_;
if (flush == Z_TREES) goto inf_leave;
case COPY_:
state->mode = COPY; state->mode = COPY;
case COPY: case COPY:
copy = state->length; copy = state->length;
@@ -876,19 +920,19 @@ int flush;
case CODELENS: case CODELENS:
while (state->have < state->nlen + state->ndist) { while (state->have < state->nlen + state->ndist) {
for (;;) { for (;;) {
this = state->lencode[BITS(state->lenbits)]; here = state->lencode[BITS(state->lenbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if (this.val < 16) { if (here.val < 16) {
NEEDBITS(this.bits); NEEDBITS(here.bits);
DROPBITS(this.bits); DROPBITS(here.bits);
state->lens[state->have++] = this.val; state->lens[state->have++] = here.val;
} }
else { else {
if (this.val == 16) { if (here.val == 16) {
NEEDBITS(this.bits + 2); NEEDBITS(here.bits + 2);
DROPBITS(this.bits); DROPBITS(here.bits);
if (state->have == 0) { if (state->have == 0) {
strm->msg = (char *)"invalid bit length repeat"; strm->msg = (char *)"invalid bit length repeat";
state->mode = BAD; state->mode = BAD;
@@ -898,16 +942,16 @@ int flush;
copy = 3 + BITS(2); copy = 3 + BITS(2);
DROPBITS(2); DROPBITS(2);
} }
else if (this.val == 17) { else if (here.val == 17) {
NEEDBITS(this.bits + 3); NEEDBITS(here.bits + 3);
DROPBITS(this.bits); DROPBITS(here.bits);
len = 0; len = 0;
copy = 3 + BITS(3); copy = 3 + BITS(3);
DROPBITS(3); DROPBITS(3);
} }
else { else {
NEEDBITS(this.bits + 7); NEEDBITS(here.bits + 7);
DROPBITS(this.bits); DROPBITS(here.bits);
len = 0; len = 0;
copy = 11 + BITS(7); copy = 11 + BITS(7);
DROPBITS(7); DROPBITS(7);
@@ -925,7 +969,16 @@ int flush;
/* handle error breaks in while */ /* handle error breaks in while */
if (state->mode == BAD) break; if (state->mode == BAD) break;
/* build code tables */ /* check for end-of-block code (better have one) */
if (state->lens[256] == 0) {
strm->msg = (char *)"invalid code -- missing end-of-block";
state->mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state->next = state->codes; state->next = state->codes;
state->lencode = (code const FAR *)(state->next); state->lencode = (code const FAR *)(state->next);
state->lenbits = 9; state->lenbits = 9;
@@ -946,88 +999,102 @@ int flush;
break; break;
} }
Tracev((stderr, "inflate: codes ok\n")); Tracev((stderr, "inflate: codes ok\n"));
state->mode = LEN_;
if (flush == Z_TREES) goto inf_leave;
case LEN_:
state->mode = LEN; state->mode = LEN;
case LEN: case LEN:
if (have >= 6 && left >= 258) { if (have >= 6 && left >= 258) {
RESTORE(); RESTORE();
inflate_fast(strm, out); inflate_fast(strm, out);
LOAD(); LOAD();
if (state->mode == TYPE)
state->back = -1;
break; break;
} }
state->back = 0;
for (;;) { for (;;) {
this = state->lencode[BITS(state->lenbits)]; here = state->lencode[BITS(state->lenbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if (this.op && (this.op & 0xf0) == 0) { if (here.op && (here.op & 0xf0) == 0) {
last = this; last = here;
for (;;) { for (;;) {
this = state->lencode[last.val + here = state->lencode[last.val +
(BITS(last.bits + last.op) >> last.bits)]; (BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + this.bits) <= bits) break; if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
DROPBITS(last.bits); DROPBITS(last.bits);
state->back += last.bits;
} }
DROPBITS(this.bits); DROPBITS(here.bits);
state->length = (unsigned)this.val; state->back += here.bits;
if ((int)(this.op) == 0) { state->length = (unsigned)here.val;
Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? if ((int)(here.op) == 0) {
Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" : "inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", this.val)); "inflate: literal 0x%02x\n", here.val));
state->mode = LIT; state->mode = LIT;
break; break;
} }
if (this.op & 32) { if (here.op & 32) {
Tracevv((stderr, "inflate: end of block\n")); Tracevv((stderr, "inflate: end of block\n"));
state->back = -1;
state->mode = TYPE; state->mode = TYPE;
break; break;
} }
if (this.op & 64) { if (here.op & 64) {
strm->msg = (char *)"invalid literal/length code"; strm->msg = (char *)"invalid literal/length code";
state->mode = BAD; state->mode = BAD;
break; break;
} }
state->extra = (unsigned)(this.op) & 15; state->extra = (unsigned)(here.op) & 15;
state->mode = LENEXT; state->mode = LENEXT;
case LENEXT: case LENEXT:
if (state->extra) { if (state->extra) {
NEEDBITS(state->extra); NEEDBITS(state->extra);
state->length += BITS(state->extra); state->length += BITS(state->extra);
DROPBITS(state->extra); DROPBITS(state->extra);
state->back += state->extra;
} }
Tracevv((stderr, "inflate: length %u\n", state->length)); Tracevv((stderr, "inflate: length %u\n", state->length));
state->was = state->length;
state->mode = DIST; state->mode = DIST;
case DIST: case DIST:
for (;;) { for (;;) {
this = state->distcode[BITS(state->distbits)]; here = state->distcode[BITS(state->distbits)];
if ((unsigned)(this.bits) <= bits) break; if ((unsigned)(here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
if ((this.op & 0xf0) == 0) { if ((here.op & 0xf0) == 0) {
last = this; last = here;
for (;;) { for (;;) {
this = state->distcode[last.val + here = state->distcode[last.val +
(BITS(last.bits + last.op) >> last.bits)]; (BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + this.bits) <= bits) break; if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE(); PULLBYTE();
} }
DROPBITS(last.bits); DROPBITS(last.bits);
state->back += last.bits;
} }
DROPBITS(this.bits); DROPBITS(here.bits);
if (this.op & 64) { state->back += here.bits;
if (here.op & 64) {
strm->msg = (char *)"invalid distance code"; strm->msg = (char *)"invalid distance code";
state->mode = BAD; state->mode = BAD;
break; break;
} }
state->offset = (unsigned)this.val; state->offset = (unsigned)here.val;
state->extra = (unsigned)(this.op) & 15; state->extra = (unsigned)(here.op) & 15;
state->mode = DISTEXT; state->mode = DISTEXT;
case DISTEXT: case DISTEXT:
if (state->extra) { if (state->extra) {
NEEDBITS(state->extra); NEEDBITS(state->extra);
state->offset += BITS(state->extra); state->offset += BITS(state->extra);
DROPBITS(state->extra); DROPBITS(state->extra);
state->back += state->extra;
} }
#ifdef INFLATE_STRICT #ifdef INFLATE_STRICT
if (state->offset > state->dmax) { if (state->offset > state->dmax) {
@@ -1036,11 +1103,6 @@ int flush;
break; break;
} }
#endif #endif
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)); Tracevv((stderr, "inflate: distance %u\n", state->offset));
state->mode = MATCH; state->mode = MATCH;
case MATCH: case MATCH:
@@ -1048,12 +1110,32 @@ int flush;
copy = out - left; copy = out - left;
if (state->offset > copy) { /* copy from window */ if (state->offset > copy) { /* copy from window */
copy = state->offset - copy; copy = state->offset - copy;
if (copy > state->write) { if (copy > state->whave) {
copy -= state->write; if (state->sane) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
Trace((stderr, "inflate.c too far\n"));
copy -= state->whave;
if (copy > state->length) copy = state->length;
if (copy > left) copy = left;
left -= copy;
state->length -= copy;
do {
*put++ = 0;
} while (--copy);
if (state->length == 0) state->mode = LEN;
break;
#endif
}
if (copy > state->wnext) {
copy -= state->wnext;
from = state->window + (state->wsize - copy); from = state->window + (state->wsize - copy);
} }
else else
from = state->window + (state->write - copy); from = state->window + (state->wnext - copy);
if (copy > state->length) copy = state->length; if (copy > state->length) copy = state->length;
} }
else { /* copy from output */ else { /* copy from output */
@@ -1146,7 +1228,8 @@ int flush;
strm->adler = state->check = strm->adler = state->check =
UPDATE(state->check, strm->next_out - out, out); UPDATE(state->check, strm->next_out - out, out);
strm->data_type = state->bits + (state->last ? 64 : 0) + strm->data_type = state->bits + (state->last ? 64 : 0) +
(state->mode == TYPE ? 128 : 0); (state->mode == TYPE ? 128 : 0) +
(state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
ret = Z_BUF_ERROR; ret = Z_BUF_ERROR;
return ret; return ret;
@@ -1366,3 +1449,32 @@ z_streamp source;
dest->state = (struct internal_state FAR *)copy; dest->state = (struct internal_state FAR *)copy;
return Z_OK; return Z_OK;
} }
int ZEXPORT inflateUndermine(strm, subvert)
z_streamp strm;
int subvert;
{
struct inflate_state FAR *state;
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
state = (struct inflate_state FAR *)strm->state;
state->sane = !subvert;
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
return Z_OK;
#else
state->sane = 1;
return Z_DATA_ERROR;
#endif
}
long ZEXPORT inflateMark(strm)
z_streamp strm;
{
struct inflate_state FAR *state;
if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;
state = (struct inflate_state FAR *)strm->state;
return ((long)(state->back) << 16) +
(state->mode == COPY ? state->length :
(state->mode == MATCH ? state->was - state->length : 0));
}

View File

@@ -1,5 +1,5 @@
/* inflate.h -- internal inflate state definition /* inflate.h -- internal inflate state definition
* Copyright (C) 1995-2006 Mark Adler * Copyright (C) 1995-2009 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -32,11 +32,13 @@ typedef enum {
TYPE, /* i: waiting for type bits, including last-flag bit */ TYPE, /* i: waiting for type bits, including last-flag bit */
TYPEDO, /* i: same, but skip check to exit inflate on new block */ TYPEDO, /* i: same, but skip check to exit inflate on new block */
STORED, /* i: waiting for stored size (length and complement) */ STORED, /* i: waiting for stored size (length and complement) */
COPY_, /* i/o: same as COPY below, but only first time in */
COPY, /* i/o: waiting for input or output to copy stored block */ COPY, /* i/o: waiting for input or output to copy stored block */
TABLE, /* i: waiting for dynamic block table lengths */ TABLE, /* i: waiting for dynamic block table lengths */
LENLENS, /* i: waiting for code length code lengths */ LENLENS, /* i: waiting for code length code lengths */
CODELENS, /* i: waiting for length/lit and distance code lengths */ CODELENS, /* i: waiting for length/lit and distance code lengths */
LEN, /* i: waiting for length/lit code */ LEN_, /* i: same as LEN below, but only first time in */
LEN, /* i: waiting for length/lit/eob code */
LENEXT, /* i: waiting for length extra bits */ LENEXT, /* i: waiting for length extra bits */
DIST, /* i: waiting for distance code */ DIST, /* i: waiting for distance code */
DISTEXT, /* i: waiting for distance extra bits */ DISTEXT, /* i: waiting for distance extra bits */
@@ -53,19 +55,21 @@ typedef enum {
/* /*
State transitions between above modes - State transitions between above modes -
(most modes can go to the BAD or MEM mode -- not shown for clarity) (most modes can go to BAD or MEM on error -- not shown for clarity)
Process header: Process header:
HEAD -> (gzip) or (zlib) HEAD -> (gzip) or (zlib) or (raw)
(gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
NAME -> COMMENT -> HCRC -> TYPE HCRC -> TYPE
(zlib) -> DICTID or TYPE (zlib) -> DICTID or TYPE
DICTID -> DICT -> TYPE DICTID -> DICT -> TYPE
(raw) -> TYPEDO
Read deflate blocks: Read deflate blocks:
TYPE -> STORED or TABLE or LEN or CHECK TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
STORED -> COPY -> TYPE STORED -> COPY_ -> COPY -> TYPE
TABLE -> LENLENS -> CODELENS -> LEN TABLE -> LENLENS -> CODELENS -> LEN_
Read deflate codes: LEN_ -> LEN
Read deflate codes in fixed or dynamic block:
LEN -> LENEXT or LIT or TYPE LEN -> LENEXT or LIT or TYPE
LENEXT -> DIST -> DISTEXT -> MATCH -> LEN LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
LIT -> LEN LIT -> LEN
@@ -88,7 +92,7 @@ struct inflate_state {
unsigned wbits; /* log base 2 of requested window size */ unsigned wbits; /* log base 2 of requested window size */
unsigned wsize; /* window size or zero if not using window */ unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */ unsigned whave; /* valid bytes in the window */
unsigned write; /* window write index */ unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if needed */ unsigned char FAR *window; /* allocated sliding window, if needed */
/* bit accumulator */ /* bit accumulator */
unsigned long hold; /* input bit accumulator */ unsigned long hold; /* input bit accumulator */
@@ -112,4 +116,7 @@ struct inflate_state {
unsigned short lens[320]; /* temporary storage for code lengths */ unsigned short lens[320]; /* temporary storage for code lengths */
unsigned short work[288]; /* work area for code table building */ unsigned short work[288]; /* work area for code table building */
code codes[ENOUGH]; /* space for code tables */ code codes[ENOUGH]; /* space for code tables */
int sane; /* if false, allow invalid distance too far */
int back; /* bits back of last unprocessed length/lit */
unsigned was; /* initial length of match */
}; };

View File

@@ -1,5 +1,5 @@
/* inftrees.c -- generate Huffman trees for efficient decoding /* inftrees.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2005 Mark Adler * Copyright (C) 1995-2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -9,7 +9,7 @@
#define MAXBITS 15 #define MAXBITS 15
const char inflate_copyright[] = const char inflate_copyright[] =
" inflate 1.2.3.1 Copyright 1995-2005 Mark Adler "; " inflate 1.2.3.8 Copyright 1995-2010 Mark Adler ";
/* /*
If you use the zlib library in a product, an acknowledgment is welcome 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 in the documentation of your product. If for some reason you cannot
@@ -50,7 +50,7 @@ unsigned short FAR *work;
unsigned fill; /* index for replicating entries */ unsigned fill; /* index for replicating entries */
unsigned low; /* low bits for current root entry */ unsigned low; /* low bits for current root entry */
unsigned mask; /* mask for low root bits */ unsigned mask; /* mask for low root bits */
code this; /* table entry for duplication */ code here; /* table entry for duplication */
code FAR *next; /* next available space in table */ code FAR *next; /* next available space in table */
const unsigned short FAR *base; /* base value table to use */ const unsigned short FAR *base; /* base value table to use */
const unsigned short FAR *extra; /* extra bits table to use */ const unsigned short FAR *extra; /* extra bits table to use */
@@ -62,7 +62,7 @@ unsigned short FAR *work;
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; 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 */ 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, 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, 74, 196}; 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 78, 75};
static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 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, 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, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
@@ -115,15 +115,15 @@ unsigned short FAR *work;
if (count[max] != 0) break; if (count[max] != 0) break;
if (root > max) root = max; if (root > max) root = max;
if (max == 0) { /* no symbols to code at all */ if (max == 0) { /* no symbols to code at all */
this.op = (unsigned char)64; /* invalid code marker */ here.op = (unsigned char)64; /* invalid code marker */
this.bits = (unsigned char)1; here.bits = (unsigned char)1;
this.val = (unsigned short)0; here.val = (unsigned short)0;
*(*table)++ = this; /* make a table to force an error */ *(*table)++ = here; /* make a table to force an error */
*(*table)++ = this; *(*table)++ = here;
*bits = 1; *bits = 1;
return 0; /* no symbols, but wait for decoding to report error */ return 0; /* no symbols, but wait for decoding to report error */
} }
for (min = 1; min <= MAXBITS; min++) for (min = 1; min < max; min++)
if (count[min] != 0) break; if (count[min] != 0) break;
if (root < min) root = min; if (root < min) root = min;
@@ -166,11 +166,10 @@ unsigned short FAR *work;
entered in the tables. entered in the tables.
used keeps track of how many table entries have been allocated from the 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 provided *table space. It is checked for LENS and DIST tables against
against the space in *table, ENOUGH, minus the maximum space needed by the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the worst case distance code, MAXD. This should never happen, but the the initial root table size constants. See the comments in inftrees.h
sufficiency of ENOUGH has not been proven exhaustively, hence the check. for more information.
This assumes that when type == LENS, bits == 9.
sym increments through all symbols, and the loop terminates when sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This all codes of length max, i.e. all codes, have been processed. This
@@ -209,24 +208,25 @@ unsigned short FAR *work;
mask = used - 1; /* mask for comparing low */ mask = used - 1; /* mask for comparing low */
/* check available table space */ /* check available table space */
if (type == LENS && used >= ENOUGH - MAXD) if ((type == LENS && used >= ENOUGH_LENS) ||
(type == DISTS && used >= ENOUGH_DISTS))
return 1; return 1;
/* process all codes and make table entries */ /* process all codes and make table entries */
for (;;) { for (;;) {
/* create table entry */ /* create table entry */
this.bits = (unsigned char)(len - drop); here.bits = (unsigned char)(len - drop);
if ((int)(work[sym]) < end) { if ((int)(work[sym]) < end) {
this.op = (unsigned char)0; here.op = (unsigned char)0;
this.val = work[sym]; here.val = work[sym];
} }
else if ((int)(work[sym]) > end) { else if ((int)(work[sym]) > end) {
this.op = (unsigned char)(extra[work[sym]]); here.op = (unsigned char)(extra[work[sym]]);
this.val = base[work[sym]]; here.val = base[work[sym]];
} }
else { else {
this.op = (unsigned char)(32 + 64); /* end of block */ here.op = (unsigned char)(32 + 64); /* end of block */
this.val = 0; here.val = 0;
} }
/* replicate for those indices with low len bits equal to huff */ /* replicate for those indices with low len bits equal to huff */
@@ -235,7 +235,7 @@ unsigned short FAR *work;
min = fill; /* save offset to next table */ min = fill; /* save offset to next table */
do { do {
fill -= incr; fill -= incr;
next[(huff >> drop) + fill] = this; next[(huff >> drop) + fill] = here;
} while (fill != 0); } while (fill != 0);
/* backwards increment the len-bit code huff */ /* backwards increment the len-bit code huff */
@@ -277,7 +277,8 @@ unsigned short FAR *work;
/* check for enough space */ /* check for enough space */
used += 1U << curr; used += 1U << curr;
if (type == LENS && used >= ENOUGH - MAXD) if ((type == LENS && used >= ENOUGH_LENS) ||
(type == DISTS && used >= ENOUGH_DISTS))
return 1; return 1;
/* point entry in root table to sub-table */ /* point entry in root table to sub-table */
@@ -295,20 +296,20 @@ unsigned short FAR *work;
through high index bits. When the current sub-table is filled, the loop 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. drops back to the root table to fill in any remaining entries there.
*/ */
this.op = (unsigned char)64; /* invalid code marker */ here.op = (unsigned char)64; /* invalid code marker */
this.bits = (unsigned char)(len - drop); here.bits = (unsigned char)(len - drop);
this.val = (unsigned short)0; here.val = (unsigned short)0;
while (huff != 0) { while (huff != 0) {
/* when done with sub-table, drop back to root table */ /* when done with sub-table, drop back to root table */
if (drop != 0 && (huff & mask) != low) { if (drop != 0 && (huff & mask) != low) {
drop = 0; drop = 0;
len = root; len = root;
next = *table; next = *table;
this.bits = (unsigned char)len; here.bits = (unsigned char)len;
} }
/* put invalid code marker in table */ /* put invalid code marker in table */
next[huff >> drop] = this; next[huff >> drop] = here;
/* backwards increment the len-bit code huff */ /* backwards increment the len-bit code huff */
incr = 1U << (len - 1); incr = 1U << (len - 1);

View File

@@ -35,15 +35,22 @@ typedef struct {
01000000 - invalid code 01000000 - invalid code
*/ */
/* Maximum size of dynamic tree. The maximum found in a long but non- /* Maximum size of the dynamic table. The maximum number of code structures is
exhaustive search was 1444 code structures (852 for length/literals 1444, which is the sum of 852 for literal/length codes and 592 for distance
and 592 for distances, the latter actually the result of an codes. These values were found by exhaustive searches using the program
exhaustive search). The true maximum is not known, but the value examples/enough.c found in the zlib distribtution. The arguments to that
below is more than safe. */ program are the number of symbols, the initial root table size, and the
#define ENOUGH 2048 maximum bit length of a code. "enough 286 9 15" for literal/length codes
#define MAXD 592 returns returns 852, and "enough 30 6 15" for distance codes returns 592.
The initial root table size (9 or 6) is found in the fifth argument of the
inflate_table() calls in inflate.c and infback.c. If the root table size is
changed, then these maximum sizes would be need to be recalculated and
updated. */
#define ENOUGH_LENS 852
#define ENOUGH_DISTS 592
#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
/* Type of code to build for inftable() */ /* Type of code to build for inflate_table() */
typedef enum { typedef enum {
CODES, CODES,
LENS, LENS,

View File

@@ -10,15 +10,19 @@ $!
$!------------------------------------------------------------------------------ $!------------------------------------------------------------------------------
$! Version history $! Version history
$! 0.01 20060120 First version to receive a number $! 0.01 20060120 First version to receive a number
$! 0.02 20061008 Adapt to new Makefile.in
$! 0.03 20091224 Add support for large file check
$! 0.04 20100110 Add new gzclose, gzlib, gzread, gzwrite
$! $!
$ on error then goto err_exit $ on error then goto err_exit
$! $!
$!
$! Just some general constants...
$!
$ true = 1 $ true = 1
$ false = 0 $ false = 0
$ tmpnam = "temp_" + f$getjpi("","pid") $ tmpnam = "temp_" + f$getjpi("","pid")
$ tt = tmpnam + ".txt"
$ tc = tmpnam + ".c"
$ th = tmpnam + ".h"
$ define/nolog tconfig 'th'
$ its_decc = false $ its_decc = false
$ its_vaxc = false $ its_vaxc = false
$ its_gnuc = false $ its_gnuc = false
@@ -26,17 +30,25 @@ $ s_case = False
$! $!
$! Setup variables holding "config" information $! Setup variables holding "config" information
$! $!
$ Make = "" $ Make = ""
$ name = "Zlib" $ name = "Zlib"
$ version = "?.?.?" $ version = "?.?.?"
$ v_string = "ZLIB_VERSION" $ v_string = "ZLIB_VERSION"
$ v_file = "zlib.h" $ v_file = "zlib.h"
$ ccopt = "" $ ccopt = ""
$ lopts = "" $ lopts = ""
$ dnsrl = "" $ dnsrl = ""
$ aconf_in_file = "config.hin"
$ conf_check_string = ""
$ linkonly = false $ linkonly = false
$ optfile = name + ".opt" $ optfile = name + ".opt"
$ axp = f$getsyi("HW_MODEL").ge.1024 $ libdefs = ""
$ axp = f$getsyi("HW_MODEL").ge.1024 .and. f$getsyi("HW_MODEL").lt.4096
$!
$ whoami = f$parse(f$enviornment("Procedure"),,,,"NO_CONCEAL")
$ mydef = F$parse(whoami,,,"DEVICE")
$ mydir = f$parse(whoami,,,"DIRECTORY") - "]["
$ myproc = f$parse(whoami,,,"Name") + f$parse(whoami,,,"type")
$! $!
$! Check for MMK/MMS $! Check for MMK/MMS
$! $!
@@ -46,11 +58,16 @@ $!
$! $!
$ gosub find_version $ gosub find_version
$! $!
$ open/write topt tmp.opt
$ open/write optf 'optfile'
$!
$ gosub check_opts $ gosub check_opts
$! $!
$! Look for the compiler used $! Look for the compiler used
$! $!
$ gosub check_compiler $ gosub check_compiler
$ close topt
$!
$ if its_decc $ if its_decc
$ then $ then
$ ccopt = "/prefix=all" + ccopt $ ccopt = "/prefix=all" + ccopt
@@ -70,6 +87,49 @@ $ then
$ if f$trnlnm("SYS").eqs."" then define sys sys$library: $ if f$trnlnm("SYS").eqs."" then define sys sys$library:
$ endif $ endif
$! $!
$! Build a fake configure input header
$!
$ open/write conf_hin config.hin
$ write conf_hin "#undef _LARGEFILE64_SOURCE"
$ close conf_hin
$!
$!
$ i = 0
$FIND_ACONF:
$ fname = f$element(i,"#",aconf_in_file)
$ if fname .eqs. "#" then goto AMISS_ERR
$ if f$search(fname) .eqs. ""
$ then
$ i = i + 1
$ goto find_aconf
$ endif
$ open/read/err=aconf_err aconf_in 'fname'
$ open/write aconf zlibdefs.h
$ACONF_LOOP:
$ read/end_of_file=aconf_exit aconf_in line
$ work = f$edit(line, "compress,trim")
$ if f$extract(0,6,work) .nes. "#undef"
$ then
$ write aconf line
$ else
$ cdef = f$element(1," ",work)
$ gosub check_config
$ endif
$ goto aconf_loop
$ACONF_EXIT:
$ write aconf "#define VMS 1"
$ write aconf "#include <unistd.h>"
$ write aconf "#include <unixio.h>"
$ write aconf "#ifdef _LARGEFILE"
$ write aconf "#define off64_t __off64_t"
$ write aconf "#define fopen64 fopen"
$ write aconf "#define fseeko64 fseeko"
$ write aconf "#define lseek64 lseek"
$ write aconf "#define ftello64 ftell"
$ write aconf "#endif"
$ close aconf_in
$ close aconf
$ delete 'th';*
$! Build the thing plain or with mms $! Build the thing plain or with mms
$! $!
$ write sys$output "Compiling Zlib sources ..." $ write sys$output "Compiling Zlib sources ..."
@@ -84,8 +144,16 @@ $ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" -
crc32.c zlib.h zconf.h crc32.c zlib.h zconf.h
$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" - $ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" -
deflate.c deflate.h zutil.h zlib.h zconf.h deflate.c deflate.h zutil.h zlib.h zconf.h
$ CALL MAKE gzclose.OBJ "CC ''CCOPT' gzclose" -
gzclose.c zutil.h zlib.h zconf.h
$ CALL MAKE gzio.OBJ "CC ''CCOPT' gzio" - $ CALL MAKE gzio.OBJ "CC ''CCOPT' gzio" -
gzio.c zutil.h zlib.h zconf.h gzio.c zutil.h zlib.h zconf.h
$ CALL MAKE gzlib.OBJ "CC ''CCOPT' gzlib" -
gzlib.c zutil.h zlib.h zconf.h
$ CALL MAKE gzread.OBJ "CC ''CCOPT' gzread" -
gzread.c zutil.h zlib.h zconf.h
$ CALL MAKE gzwrite.OBJ "CC ''CCOPT' gzwrite" -
gzwrite.c zutil.h zlib.h zconf.h
$ CALL MAKE infback.OBJ "CC ''CCOPT' infback" - $ CALL MAKE infback.OBJ "CC ''CCOPT' infback" -
infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" - $ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" -
@@ -144,6 +212,14 @@ $ goto err_exit
$ERR_EXIT: $ERR_EXIT:
$ set message/facil/ident/sever/text $ set message/facil/ident/sever/text
$ close/nolog optf $ close/nolog optf
$ close/nolog topt
$ close/nolog conf_hin
$ close/nolog aconf_in
$ close/nolog aconf
$ close/nolog out
$ close/nolog min
$ close/nolog mod
$ close/nolog h_in
$ write sys$output "Exiting..." $ write sys$output "Exiting..."
$ exit 2 $ exit 2
$! $!
@@ -191,61 +267,72 @@ $!------------------------------------------------------------------------------
$! $!
$! Check command line options and set symbols accordingly $! Check command line options and set symbols accordingly
$! $!
$!------------------------------------------------------------------------------
$! Version history
$! 0.01 20041206 First version to receive a number
$! 0.02 20060126 Add new "HELP" target
$ CHECK_OPTS: $ CHECK_OPTS:
$ i = 1 $ i = 1
$ OPT_LOOP: $ OPT_LOOP:
$ if i .lt. 9 $ if i .lt. 9
$ then $ then
$ cparm = f$edit(p'i',"upcase") $ cparm = f$edit(p'i',"upcase")
$ if cparm .eqs. "DEBUG" $!
$! Check if parameter actually contains something
$!
$ if f$edit(cparm,"trim") .nes. ""
$ then $ then
$ ccopt = ccopt + "/noopt/deb" $ if cparm .eqs. "DEBUG"
$ lopts = lopts + "/deb"
$ endif
$ if f$locate("CCOPT=",cparm) .lt. f$length(cparm)
$ then
$ start = f$locate("=",cparm) + 1
$ len = f$length(cparm) - start
$ ccopt = ccopt + f$extract(start,len,cparm)
$ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) -
then s_case = true
$ endif
$ if cparm .eqs. "LINK" then linkonly = true
$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm)
$ then
$ start = f$locate("=",cparm) + 1
$ len = f$length(cparm) - start
$ lopts = lopts + f$extract(start,len,cparm)
$ endif
$ if f$locate("CC=",cparm) .lt. f$length(cparm)
$ then
$ start = f$locate("=",cparm) + 1
$ len = f$length(cparm) - start
$ cc_com = f$extract(start,len,cparm)
if (cc_com .nes. "DECC") .and. -
(cc_com .nes. "VAXC") .and. -
(cc_com .nes. "GNUC")
$ then $ then
$ write sys$output "Unsupported compiler choice ''cc_com' ignored" $ ccopt = ccopt + "/noopt/deb"
$ write sys$output "Use DECC, VAXC, or GNUC instead" $ lopts = lopts + "/deb"
$ else
$ if cc_com .eqs. "DECC" then its_decc = true
$ if cc_com .eqs. "VAXC" then its_vaxc = true
$ if cc_com .eqs. "GNUC" then its_gnuc = true
$ endif $ endif
$ endif $ if f$locate("CCOPT=",cparm) .lt. f$length(cparm)
$ if f$locate("MAKE=",cparm) .lt. f$length(cparm)
$ then
$ start = f$locate("=",cparm) + 1
$ len = f$length(cparm) - start
$ mmks = f$extract(start,len,cparm)
$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS")
$ then $ then
$ make = mmks $ start = f$locate("=",cparm) + 1
$ else $ len = f$length(cparm) - start
$ write sys$output "Unsupported make choice ''mmks' ignored" $ ccopt = ccopt + f$extract(start,len,cparm)
$ write sys$output "Use MMK or MMS instead" $ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) -
then s_case = true
$ endif $ endif
$ if cparm .eqs. "LINK" then linkonly = true
$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm)
$ then
$ start = f$locate("=",cparm) + 1
$ len = f$length(cparm) - start
$ lopts = lopts + f$extract(start,len,cparm)
$ endif
$ if f$locate("CC=",cparm) .lt. f$length(cparm)
$ then
$ start = f$locate("=",cparm) + 1
$ len = f$length(cparm) - start
$ cc_com = f$extract(start,len,cparm)
if (cc_com .nes. "DECC") .and. -
(cc_com .nes. "VAXC") .and. -
(cc_com .nes. "GNUC")
$ then
$ write sys$output "Unsupported compiler choice ''cc_com' ignored"
$ write sys$output "Use DECC, VAXC, or GNUC instead"
$ else
$ if cc_com .eqs. "DECC" then its_decc = true
$ if cc_com .eqs. "VAXC" then its_vaxc = true
$ if cc_com .eqs. "GNUC" then its_gnuc = true
$ endif
$ endif
$ if f$locate("MAKE=",cparm) .lt. f$length(cparm)
$ then
$ start = f$locate("=",cparm) + 1
$ len = f$length(cparm) - start
$ mmks = f$extract(start,len,cparm)
$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS")
$ then
$ make = mmks
$ else
$ write sys$output "Unsupported make choice ''mmks' ignored"
$ write sys$output "Use MMK or MMS instead"
$ endif
$ endif
$ if cparm .eqs. "HELP" then gosub bhelp
$ endif $ endif
$ i = i + 1 $ i = i + 1
$ goto opt_loop $ goto opt_loop
@@ -258,6 +345,8 @@ $!
$! Version history $! Version history
$! 0.01 20040223 First version to receive a number $! 0.01 20040223 First version to receive a number
$! 0.02 20040229 Save/set value of decc$no_rooted_search_lists $! 0.02 20040229 Save/set value of decc$no_rooted_search_lists
$! 0.03 20060202 Extend handling of GNU C
$! 0.04 20090402 Compaq -> hp
$CHECK_COMPILER: $CHECK_COMPILER:
$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) $ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
$ then $ then
@@ -273,15 +362,21 @@ $ then goto CC_ERR
$ else $ else
$ if its_decc $ if its_decc
$ then $ then
$ write sys$output "CC compiler check ... Compaq C" $ write sys$output "CC compiler check ... hp C"
$ if f$trnlnm("decc$no_rooted_search_lists") .nes. "" $ if f$trnlnm("decc$no_rooted_search_lists") .nes. ""
$ then $ then
$ dnrsl = f$trnlnm("decc$no_rooted_search_lists") $ dnrsl = f$trnlnm("decc$no_rooted_search_lists")
$ endif $ endif
$ define decc$no_rooted_search_lists 1 $ define/nolog decc$no_rooted_search_lists 1
$ else $ else
$ if its_vaxc then write sys$output "CC compiler check ... VAX C" $ if its_vaxc then write sys$output "CC compiler check ... VAX C"
$ if its_gnuc then write sys$output "CC compiler check ... GNU C" $ if its_gnuc
$ then
$ write sys$output "CC compiler check ... GNU C"
$ if f$trnlnm(topt) then write topt "gnu_cc:[000000]gcclib.olb/lib"
$ if f$trnlnm(optf) then write optf "gnu_cc:[000000]gcclib.olb/lib"
$ cc = "gcc"
$ endif
$ if f$trnlnm(topt) then write topt "sys$share:vaxcrtl.exe/share" $ if f$trnlnm(topt) then write topt "sys$share:vaxcrtl.exe/share"
$ if f$trnlnm(optf) then write optf "sys$share:vaxcrtl.exe/share" $ if f$trnlnm(optf) then write optf "sys$share:vaxcrtl.exe/share"
$ endif $ endif
@@ -301,7 +396,8 @@ $ deck
# written by Martin P.J. Zinser # written by Martin P.J. Zinser
# <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com> # <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com>
OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj, infback.obj\ OBJS = adler32.obj, compress.obj, crc32.obj, gzclose.obj, gzio.obj, gzlib.obj\
gzread.obj, gzwrite.obj, uncompr.obj, infback.obj\
deflate.obj, trees.obj, zutil.obj, inflate.obj, \ deflate.obj, trees.obj, zutil.obj, inflate.obj, \
inftrees.obj, inffast.obj inftrees.obj, inffast.obj
@@ -333,7 +429,11 @@ compress.obj : compress.c zlib.h zconf.h
crc32.obj : crc32.c zutil.h zlib.h zconf.h crc32.obj : crc32.c zutil.h zlib.h zconf.h
deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h
example.obj : example.c zlib.h zconf.h example.obj : example.c zlib.h zconf.h
gzclose.obj : gzclose.c zutil.h zlib.h zconf.h
gzio.obj : gzio.c zutil.h zlib.h zconf.h gzio.obj : gzio.c zutil.h zlib.h zconf.h
gzlib.obj : gzlib.c zutil.h zlib.h zconf.h
gzread.obj : gzread.c zutil.h zlib.h zconf.h
gzwrite.obj : gzwrite.c zutil.h zlib.h zconf.h
inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h
inflate.obj : inflate.c zutil.h zlib.h zconf.h inflate.obj : inflate.c zutil.h zlib.h zconf.h
inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h
@@ -353,7 +453,7 @@ $!
$CREA_OLIST: $CREA_OLIST:
$ open/read min makefile.in $ open/read min makefile.in
$ open/write mod modules.opt $ open/write mod modules.opt
$ src_check = "OBJS =" $ src_check = "OBJC ="
$MRLOOP: $MRLOOP:
$ read/end=mrdone min rec $ read/end=mrdone min rec
$ if (f$extract(0,6,rec) .nes. src_check) then goto mrloop $ if (f$extract(0,6,rec) .nes. src_check) then goto mrloop
@@ -407,7 +507,170 @@ $ close h_in
$ return $ return
$!------------------------------------------------------------------------------ $!------------------------------------------------------------------------------
$! $!
$! Analyze Object files for OpenVMS AXP to extract Procedure and Data $CHECK_CONFIG:
$!
$ in_ldef = f$locate(cdef,libdefs)
$ if (in_ldef .lt. f$length(libdefs))
$ then
$ write aconf "#define ''cdef' 1"
$ libdefs = f$extract(0,in_ldef,libdefs) + -
f$extract(in_ldef + f$length(cdef) + 1, -
f$length(libdefs) - in_ldef - f$length(cdef) - 1, -
libdefs)
$ else
$ if (f$type('cdef') .eqs. "INTEGER")
$ then
$ write aconf "#define ''cdef' ", 'cdef'
$ else
$ if (f$type('cdef') .eqs. "STRING")
$ then
$ write aconf "#define ''cdef' ", """", '''cdef'', """"
$ else
$ gosub check_cc_def
$ endif
$ endif
$ endif
$ return
$!------------------------------------------------------------------------------
$!
$! Check if this is a define relating to the properties of the C/C++
$! compiler
$!
$ CHECK_CC_DEF:
$ if (cdef .eqs. "_LARGEFILE64_SOURCE")
$ then
$ copy sys$input: 'tc'
$ deck
#include "tconfig"
#define _LARGEFILE
#include <stdio.h>
int main(){
FILE *fp;
fp = fopen("temp.txt","r");
fseeko(fp,1,SEEK_SET);
fclose(fp);
}
$ eod
$ test_inv = false
$ comm_h = false
$ gosub cc_prop_check
$ return
$ endif
$ write aconf "/* ", line, " */"
$ return
$!------------------------------------------------------------------------------
$!
$! Check for properties of C/C++ compiler
$!
$! Version history
$! 0.01 20031020 First version to receive a number
$! 0.02 20031022 Added logic for defines with value
$! 0.03 20040309 Make sure local config file gets not deleted
$! 0.04 20041230 Also write include for configure run
$! 0.05 20050103 Add processing of "comment defines"
$CC_PROP_CHECK:
$ cc_prop = true
$ is_need = false
$ is_need = (f$extract(0,4,cdef) .eqs. "NEED") .or. (test_inv .eq. true)
$ if f$search(th) .eqs. "" then create 'th'
$ set message/nofac/noident/nosever/notext
$ on error then continue
$ cc 'tmpnam'
$ if .not. ($status) then cc_prop = false
$ on error then continue
$! The headers might lie about the capabilities of the RTL
$ link 'tmpnam',tmp.opt/opt
$ if .not. ($status) then cc_prop = false
$ set message/fac/ident/sever/text
$ on error then goto err_exit
$ delete/nolog 'tmpnam'.*;*/exclude='th'
$ if (cc_prop .and. .not. is_need) .or. -
(.not. cc_prop .and. is_need)
$ then
$ write sys$output "Checking for ''cdef'... yes"
$ if f$type('cdef_val'_yes) .nes. ""
$ then
$ if f$type('cdef_val'_yes) .eqs. "INTEGER" -
then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_yes)
$ if f$type('cdef_val'_yes) .eqs. "STRING" -
then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_yes)
$ else
$ call write_config f$fao("#define !AS 1",cdef)
$ endif
$ if (cdef .eqs. "HAVE_FSEEKO") .or. (cdef .eqs. "_LARGE_FILES") .or. -
(cdef .eqs. "_LARGEFILE64_SOURCE") then -
call write_config f$string("#define _LARGEFILE 1")
$ else
$ write sys$output "Checking for ''cdef'... no"
$ if (comm_h)
$ then
call write_config f$fao("/* !AS */",line)
$ else
$ if f$type('cdef_val'_no) .nes. ""
$ then
$ if f$type('cdef_val'_no) .eqs. "INTEGER" -
then call write_config f$fao("#define !AS !UL",cdef,'cdef_val'_no)
$ if f$type('cdef_val'_no) .eqs. "STRING" -
then call write_config f$fao("#define !AS !AS",cdef,'cdef_val'_no)
$ else
$ call write_config f$fao("#undef !AS",cdef)
$ endif
$ endif
$ endif
$ return
$!------------------------------------------------------------------------------
$!
$! Check for properties of C/C++ compiler with multiple result values
$!
$! Version history
$! 0.01 20040127 First version
$! 0.02 20050103 Reconcile changes from cc_prop up to version 0.05
$CC_MPROP_CHECK:
$ cc_prop = true
$ i = 1
$ idel = 1
$ MT_LOOP:
$ if f$type(result_'i') .eqs. "STRING"
$ then
$ set message/nofac/noident/nosever/notext
$ on error then continue
$ cc 'tmpnam'_'i'
$ if .not. ($status) then cc_prop = false
$ on error then continue
$! The headers might lie about the capabilities of the RTL
$ link 'tmpnam'_'i',tmp.opt/opt
$ if .not. ($status) then cc_prop = false
$ set message/fac/ident/sever/text
$ on error then goto err_exit
$ delete/nolog 'tmpnam'_'i'.*;*
$ if (cc_prop)
$ then
$ write sys$output "Checking for ''cdef'... ", mdef_'i'
$ if f$type(mdef_'i') .eqs. "INTEGER" -
then call write_config f$fao("#define !AS !UL",cdef,mdef_'i')
$ if f$type('cdef_val'_yes) .eqs. "STRING" -
then call write_config f$fao("#define !AS !AS",cdef,mdef_'i')
$ goto msym_clean
$ else
$ i = i + 1
$ goto mt_loop
$ endif
$ endif
$ write sys$output "Checking for ''cdef'... no"
$ call write_config f$fao("#undef !AS",cdef)
$ MSYM_CLEAN:
$ if (idel .le. msym_max)
$ then
$ delete/sym mdef_'idel'
$ idel = idel + 1
$ goto msym_clean
$ endif
$ return
$!------------------------------------------------------------------------------
$!
$! Analyze Object files for OpenVMS AXP to extract Procedure and Data
$! information to build a symbol vector for a shareable image $! information to build a symbol vector for a shareable image
$! All the "brains" of this logic was suggested by Hartmut Becker $! All the "brains" of this logic was suggested by Hartmut Becker
$! (Hartmut.Becker@compaq.com). All the bugs were introduced by me $! (Hartmut.Becker@compaq.com). All the bugs were introduced by me
@@ -420,10 +683,10 @@ $! 0.02 20041109 Fix option file for shareable images with case_sensitive=YES
$! 0.03 20050107 Skip over Identification labels in option file $! 0.03 20050107 Skip over Identification labels in option file
$! 0.04 20060117 Add uppercase alias to code compiled with /name=as_is $! 0.04 20060117 Add uppercase alias to code compiled with /name=as_is
$! $!
$ ANAL_OBJ_AXP: Subroutine $ ANAL_OBJ_AXP: Subroutine
$ V = 'F$Verify(0) $ V = 'F$Verify(0)
$ SAY := "WRITE_ SYS$OUTPUT" $ SAY := "WRITE_ SYS$OUTPUT"
$ $
$ IF F$SEARCH("''P1'") .EQS. "" $ IF F$SEARCH("''P1'") .EQS. ""
$ THEN $ THEN
$ SAY "ANAL_OBJ_AXP-E-NOSUCHFILE: Error, inputfile ''p1' not available" $ SAY "ANAL_OBJ_AXP-E-NOSUCHFILE: Error, inputfile ''p1' not available"
@@ -502,15 +765,15 @@ $ if f$locate("=PROCEDURE)",raw_element) .lt. f$length(raw_element)
$ then $ then
$ name = f$element(1,"=",raw_element) - "(" $ name = f$element(1,"=",raw_element) - "("
$ if f$edit(name,"UPCASE") .nes. name then - $ if f$edit(name,"UPCASE") .nes. name then -
write case_vector f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)", - write case_vector f$fao(" symbol_vector=(!AS/!AS=PROCEDURE)", -
f$edit(name,"UPCASE"), name) f$edit(name,"UPCASE"), name)
$ endif $ endif
$ if f$locate("=DATA)",raw_element) .lt. f$length(raw_element) $ if f$locate("=DATA)",raw_element) .lt. f$length(raw_element)
$ then $ then
$ name = f$element(1,"=",raw_element) - "(" $ name = f$element(1,"=",raw_element) - "("
$ if f$edit(name,"UPCASE") .nes. name then - $ if f$edit(name,"UPCASE") .nes. name then -
write case_vector f$fao(" symbol_vector=(!AS/!AS=DATA)", - write case_vector f$fao(" symbol_vector=(!AS/!AS=DATA)", -
f$edit(name,"UPCASE"), name) f$edit(name,"UPCASE"), name)
$ endif $ endif
$ goto rawloop $ goto rawloop
$ END_RAWLOOP: $ END_RAWLOOP:
@@ -522,5 +785,18 @@ $ if f$search("x.tmp") .nes. "" -
$! $!
$ EXIT_AA: $ EXIT_AA:
$ if V then set verify $ if V then set verify
$ endsubroutine $ endsubroutine
$!------------------------------------------------------------------------------
$!
$! Write configuration to both permanent and temporary config file
$!
$! Version history
$! 0.01 20031029 First version to receive a number
$!
$WRITE_CONFIG: SUBROUTINE
$ write aconf 'p1'
$ open/append confh 'th'
$ write confh 'p1'
$ close confh
$ENDSUBROUTINE
$!------------------------------------------------------------------------------ $!------------------------------------------------------------------------------

View File

@@ -1,5 +1,5 @@
/* minigzip.c -- simulate gzip using the zlib compression library /* minigzip.c -- simulate gzip using the zlib compression library
* Copyright (C) 1995-2006 Jean-loup Gailly. * Copyright (C) 1995-2006, 2010 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
@@ -54,6 +54,70 @@
extern int unlink OF((const char *)); extern int unlink OF((const char *));
#endif #endif
#if defined(UNDER_CE) && defined(NO_ERRNO_H)
# include <windows.h>
# define perror(s) pwinerror(s)
/* Map the Windows error number in ERROR to a locale-dependent error
message string and return a pointer to it. Typically, the values
for ERROR come from GetLastError.
The string pointed to shall not be modified by the application,
but may be overwritten by a subsequent call to strwinerror
The strwinerror function does not change the current setting
of GetLastError. */
static char *strwinerror (error)
DWORD error;
{
static char buf[1024];
wchar_t *msgbuf;
DWORD lasterr = GetLastError();
DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
error,
0, /* Default language */
(LPVOID)&msgbuf,
0,
NULL);
if (chars != 0) {
/* If there is an \r\n appended, zap it. */
if (chars >= 2
&& msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
chars -= 2;
msgbuf[chars] = 0;
}
if (chars > sizeof (buf) - 1) {
chars = sizeof (buf) - 1;
msgbuf[chars] = 0;
}
wcstombs(buf, msgbuf, chars + 1);
LocalFree(msgbuf);
}
else {
sprintf(buf, "unknown win32 error (%ld)", error);
}
SetLastError(lasterr);
return buf;
}
static void pwinerror (s)
const char *s;
{
if (s && *s)
fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ()));
else
fprintf(stderr, "%s\n", strwinerror(GetLastError ()));
}
#endif /* UNDER_CE && NO_ERRNO_H */
#ifndef GZ_SUFFIX #ifndef GZ_SUFFIX
# define GZ_SUFFIX ".gz" # define GZ_SUFFIX ".gz"
#endif #endif

View File

@@ -41,10 +41,10 @@ LDFLAGS=-m$(MODEL) -f-
# variables # variables
ZLIB_LIB = zlib_$(MODEL).lib ZLIB_LIB = zlib_$(MODEL).lib
OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzio.obj infback.obj OBJ1 = adler32.obj compress.obj crc32.obj deflate.obj gzclose.obj gzio.obj gzlib.obj gzread.obj
OBJ2 = inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj OBJ2 = gzwrite.obj infback.obj inffast.obj inflate.obj inftrees.obj trees.obj uncompr.obj zutil.obj
OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzio.obj+infback.obj OBJP1 = +adler32.obj+compress.obj+crc32.obj+deflate.obj+gzclose.obj+gzio.obj+gzlib.obj+gzread.obj
OBJP2 = +inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj OBJP2 = +gzwrite.obj+infback.obj+inffast.obj+inflate.obj+inftrees.obj+trees.obj+uncompr.obj+zutil.obj
# targets # targets
@@ -61,8 +61,16 @@ crc32.obj: crc32.c zlib.h zconf.h crc32.h
deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h deflate.obj: deflate.c deflate.h zutil.h zlib.h zconf.h
gzclose.obj: gzclose.c zlib.h zconf.h gzguts.h
gzio.obj: gzio.c zutil.h zlib.h zconf.h gzio.obj: gzio.c zutil.h zlib.h zconf.h
gzlib.obj: gzlib.c zlib.h zconf.h gzguts.h
gzread.obj: gzread.c zlib.h zconf.h gzguts.h
gzwrite.obj: gzwrite.c zlib.h zconf.h gzguts.h
infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \ infback.obj: infback.c zutil.h zlib.h zconf.h inftrees.h inflate.h \
inffast.h inffixed.h inffast.h inffixed.h

Some files were not shown because too many files have changed in this diff Show More